Angular 2 parent afterViewInit fired before Child afterViewInit

I have a parent container and a child component.

Child components have a variable number and receive an 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');
}

Children's component:

@Component({
selector: 'child',
template: `      
   <div>Child</div>
`
})
export default class ChildComponent implements AfterViewInit {
@Input() c: C;

ngAfterViewInit() {
  console.log('child afterViewInit');
}

When I do this, I see parent afterNgViewin front of all the magazines child afterNgView. I expected the ngAfterViewInit children to be executed first.

There must be a way to ensure that all children are loaded before the parent handler is called. I looked over NG2 LifeCycle Hooks, suggesting that the parent AfterViewInit will only be called after the children. This is not the case.

How can I get children to tell parents that they are finished? There must be something in the box ...?

NGC LifeCycle Hooks (https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html)

, , - :

:

@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\ ngAfterViewInit Complete !!');    
}

ngAfterViewInit() {
  console.log('parent afterNgView');
}

:

@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();
}

, , ngAfterViewInit . - , ? , child-notify-parent ..?

+4

Source: https://habr.com/ru/post/1666211/


All Articles