I have a parent component, and parent component have multiple child component. And each child may be different component. For example;
--- Parent ---
|
Child1(component1) --- Child2(component1) --- Child3(component5) .....
I want that when I click the button in the parent
component, I want to get messages from the all child
components at the same time. I'm able to use EventEmitter
to get value from child to parent, but I don't know how to get all child values at the same time?
Edit:
My child components are created dynamically like this;
@ViewChild('component1Container', { read: ViewContainerRef }) component1ContainerRef: ViewContainerRef;
@ViewChild('component2Container', { read: ViewContainerRef }) component2ContainerRed: ViewContainerRef;
You can access your components by ids inside the parent template:
@Component({selector: 'parent', template: `
<app-child1 #child1>
<app-child2 #child2>
<app-child3 #child3>
<button (click)="onButtonClick(child1.aProp, child2.anotherProp, child3.thirdProp)"></button>
`})
class ParentComponent {
onButtonClick(aProp: string, anotherProp: number, thirdProp: string): void { ... }
}
Or, you can use @ViewChild directive to direct access children components inside the parent component, like this:
@Component({selector: 'parent', template: `
<app-child1 #child1>
<app-child2 #child2>
<app-child3 #child3>
<button (click)="onButtonClick()"
`})
class ParentComponent {
@ViewChild("child1", {static: false}) child1!: Child1Component;
@ViewChild("child2", {static: false}) child2!: Child2Component;
@ViewChild("child3", {static: false}) child3!: Child3Component;
onButtonClick(): void {
console.log(this.child1.aProp, this.child2.anotherProp, this.child3.thirdProp);
}
}