Reputation: 3636
I have a parent component that gets a list of objects. The parent component's corresponding html file creates several children components based on that list using an ngFor. How do you go about calling a function in EACH of the children components?
Here is my parent component Typescript file (edited for clarity):
export class HomeComponent {
childObjects: Array<ChildObject> = [];
constructor() {
this.childObjectService.getChildObjects()
.subscribe(res => {
this.childObjects = res;
});
}
}
and here is my parent component HTML:
<childObjectComponent *ngFor="let childObject of childObjects">
<!--I want to call a function on each of these childObjectComponent template objects-->
<childObjectComponent>
So if all of my ChildObject component class has a function called AddNumbers(), how would I call it on all of my ChildObjects?
Upvotes: 2
Views: 2173
Reputation: 3636
I managed to solve my problem by creating a list of objects associated with the childObjectComponent template objects. Basically, whenever a childObjectComponent is created, I use the ngAfterViewInit() method provided by Angular to emit the object to my parent component. The parent component adds the emitted object to a list it maintains.
For example, if 5 childObjectComponent template objects are created, then 5 objects will be emitted to the parent component. The parent component will add those 5 to a list. I can then do whatever I want to do with those template objects using a for loop.
Upvotes: 2
Reputation: 1523
If I understand correctly you want to have a DOM element for each of your childObjects (ngFor
) where you can execute a function on the object when you click the element:
export class HomeComponent {
childObjects: Array<ChildObject> = [];
constructor() {
this.childObjectService.getChildObjects()
.subscribe(res => {
this.childObjects = res;
});
}
doSomething(childObject : ChildObjectType) {
/* Do something with child object */
}
}
<childObjectComponent *ngFor="let childObject of childObjects">
<div (click)="doSomething(childObject)">{{childObject.text}}</div>
<childObjectComponent>
Edit: Do something on all the objects:
export class HomeComponent {
childObjects: Array<ChildObject> = [];
constructor() {
this.childObjectService.getChildObjects()
.subscribe(res => {
this.childObjects = res;
});
}
doSomethingOnAll() {
this.childObjects.forEach((child) => {
/* do something on each child object */
}
}
}
<childObjectComponent *ngFor="let childObject of childObjects">
<div (click)="doSomethingOnAll()">{{childObject.text}}</div>
<childObjectComponent>
Upvotes: 1
Reputation: 136
One way to have the parent call methods in a child is with @ViewChild. It is documented here in the Angular docs: https://angular.io/guide/component-interaction#parent-calls-an-viewchild
Note that in the parent you have to wait for ngAfterViewInit, which allows the children to render themselves.
That entire page lists out several different ways for components to talk to each other.
Upvotes: 1