Reputation: 375
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
Upvotes: 0
Views: 212
Reputation: 13078
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.
Upvotes: 2
Reputation: 2135
In app.component.html:
<div class="col-md-12 col-lg-4" *ngFor="let section of sectionObjectList">
<app-section #section [section]="section"></app-section>
</div>
In app.component.ts:
export class AppComonent {
@ViewChild('section) sectionCmp: SectionComponent;
someMethod() {
if (this.sectionCmp) {
this.sectionCmp.childMethod();
}
}
}
Upvotes: 1