Reputation: 2747
I am angular developer and currently I am developing complex application in angular. In angular My project structure is look like below image :
I have one parent component and one child component. I am passing some data into child component and process it into child and display it in the screen. Now I want to change that data from parent component. I have found that way to call child function into parent function by make reference of child component into parent component using following way :
@ViewChild(ChildComponent) child: ChildComponent
And call function from it like this :
child.functionName();
But this code only call from first child only.
Is there any way to call function from all child component at a time by single trigger from parent ?
Please write here If any one have solution for it.
Upvotes: 0
Views: 691
Reputation: 762
You are only fetching a single child. In it's place, you can use the QueryList to get all the children of single type. And then use it fire the event in the child in a loop.
For example:
@ContentChildren(ChildComponent) children: QueryList<ChildComponent>;
onButtonClick() {
this.children.forEach((child: ChildComponent) => { child.functionName() });
}
Or going the Subject way:
ParentComponent
template: '<child [subject]="mySubject"></child>'
mySubject: Subject<boolean> = new Subkect<boolean>();
someButtonClick() {
this.mySubject.emit(true);
}
Child Component
@Input() subject: Subject<boolean>;
ngOnInit() {
this.subject.subscribe((value: boolean) => doSomething{});
}
Better to move the Subject to a service, which can be injected wherever required.
Upvotes: 1