Issue
In app.component.html I print a list of section.component.html
<div class="col-md-12 col-lg-4" *ngFor="let section of sectionObjectList">
<app-section [section]="section"></app-section>
</div>
When the template is rendered, I want to call from app.component.ts (the parent) a function inside the first section.component.ts of the list (the children).
What’s the correct way to do it?
Thank you
Solution
You can use the @Output decorator:
Parent component:
HTML:
<div class="col-md-12 col-lg-4" *ngFor="let section of sectionObjectList">
<app-section [section]="section" (callback)="childCallback($event)"></app-section>
</div>
TS:
childCallback(event) {
console.log("Event data: ",event);
}
Child component:
@Output() callback = new EventEmitter<string>();
someFuntion() {
callback.emit(value);
}
Sharing data between child and parent directives and components
Use ViewChild
for DOM manipulations (change the native HTML element), and use input/output
for data binding and controlling the state of a child component from the parent to keep him isolated and stateless.