I have a parent container and a child component.
Child components are variable in number and are fetched off XHR request.
Parent Component:
@Component({
selector: 'parent',
template: `
<child *ngFor="let c of children" [c]="c"></child>
`
})
export default class ParentContainer implements AfterViewInit {
children: C[];
constructor(public api: Api) {
this.api.getC().subscribe(res => this.children = res);
ngAfterViewInit() {
console.log('parent afterNgView');
}
Child Component:
@Component({
selector: 'child',
template: `
<div>Child</div>
`
})
export default class ChildComponent implements AfterViewInit {
@Input() c: C;
ngAfterViewInit() {
console.log('child afterViewInit');
}
When I execute this I see parent afterNgView
appear before all the child afterNgView
logs. I was expecting the children ngAfterViewInit to execute first.
There must be a way to ensure all children are done loading before a parent handler is invoked. I looked through NG2 LifeCycle Hooks assuming the parent AfterViewInit would only get called after the children. That's not the case.
How can I get the children to inform the parent they are finished? There should be something out the box ... ?
This is a screenshot from NG2 LifeCycle Hooks guide (https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html)
This is what I'm doing until I find something cleaner:
Parent Component:
@Component({
selector: 'parent',
template: `
<child *ngFor="let c of children" [c]="c" (childIsLoaded)="childIsLoaded($event)"></child>
`
})
export default class ParentContainer implements AfterViewInit {
children: C[];
constructor(public api: Api) {
this.api.getC().subscribe(res => this.children = res);
childIsLoaded() {
console.log('Child\'s ngAfterViewInit Complete !!');
}
ngAfterViewInit() {
console.log('parent afterNgView');
}
Child Component:
@Component({
selector: 'child',
template: `
<div>Child</div>
`
})
export default class ChildComponent implements AfterViewInit {
@Input() c: C;
@Output() childIsLoaded = new EventEmitter<any>();
ngAfterViewInit() {
...init code...
this.childIsLoaded.emit();
}
In the above snippet, the child emits an event notifying the parent that its ngAfterViewInit fired. There must be something out of the box that does this for me ? Instead of me re-writing this child-notify-parent scheme for all my nested components .. ?