If I have this components hierarchy in Angular:
And there is something happening in component F that B should know about.
One way I can do it is using emit()
in F and pass it along the way up to A, but this will require me to emit event in each component E,D and C, even though they don't care and should not care about the data being emitted - So in F I will write
export class F .... {
...
@Output() emitterName: EventEmitter<any> = new EventEmitter<any>();
doSomething(data) {
...
this.emitterName.emit(data);
}
...
}
Then, class E should call F like <app-f-selector (emitterName)="setData($event)"><app-f-selector/>
And in E, I should create a new function setData()
that just emits the event up to D:
export class E .... {
...
@Output() emitterName: EventEmitter<any> = new EventEmitter<any>();
setData(data) {
...
this.emitterName.emit(data);
}
...
}
Now again I should do the same for D and C. That looks really bad, is there some elegant way in Angular to pass data from children component up to parent component, when there are n children along the way without code duplication? Something like React context?
Something like this (not checked, but as a guide):
then in any component that requires this data, inject via constructor and subscribe to changes: