Asa*_*bgi 5 javascript lifecycle angular
我有一个父容器和一个子组件。
子组件的数量是可变的,并从XHR请求中获取。
父组件:
@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');
}
Run Code Online (Sandbox Code Playgroud)
子组件:
@Component({
selector: 'child',
template: `
<div>Child</div>
`
})
export default class ChildComponent implements AfterViewInit {
@Input() c: C;
ngAfterViewInit() {
console.log('child afterViewInit');
}
Run Code Online (Sandbox Code Playgroud)
执行此命令时,我会看到parent afterNgView
出现在所有child afterNgView
日志之前。我期望孩子ngAfterViewInit首先执行。
必须有一种方法可以确保在调用父处理程序之前完成所有子级的加载。我浏览了NG2 LifeCycle Hooks,并假设父AfterViewInit仅在子项之后被调用。事实并非如此。
我如何让孩子们通知父母他们已经完成了?应该有开箱即用的东西吗?
这是NG2 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\'s ngAfterViewInit Complete !!');
}
ngAfterViewInit() {
console.log('parent afterNgView');
}
Run Code Online (Sandbox Code Playgroud)
子组件:
@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();
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码段中,子级发出一个事件,通知父级ngAfterViewInit被触发。必须有开箱即用的东西对我有用吗?代替我为所有嵌套组件重写此child-notify-parent方案。
归档时间: |
|
查看次数: |
4654 次 |
最近记录: |