繁体   English   中英

在生命周期中何时在Angular中创建子组件的init钩子?

[英]When in the life cycle is the init hook for subcomponents' creation in Angular?

在组件的模板中,我有一堆子组件。 开始时,我想对其中一个执行命令。 如图所示,获取了对它们的引用,包括我尝试与之交谈的不同步骤。

@ViewChildren(SubComponent) subs: QueryList<SubComponent>;

constructor(...) { console.log("constructed " + this.subs); }
ngOnInit()       { console.log("inited      " + this.subs); }

ngAfterContentInit()    { console.log("content init    " + this.subs); }
ngAfterContentChecked() { console.log("content checked " + this.subs); }
ngAfterViewInit()       { console.log("view init       " + this.subs.length); }
ngAfterViewChecked()    { console.log("view checked"     + this.subs.length); }

我面临的问题是,在每次调用中(第一次运行)我什么都没有或者为零。 最后,经过ngXxxChecked()我得到了结果并且可以对此做出反应。

但是 ,应该只在第一次出现潜艇时才发生反应。 每次用户与页面互动时,上述方法都会做到这一点。

一种解决方案是为操作设置超时。 优秀的程序员为此而死是一种丑陋的骇客。 我可以想到的另一个方法是设置一个标志,并且仅在未设置标志的情况下执行我的操作。 这是一个丑陋的骇客(我们不是在说地狱,而是​​炼狱)。

如果我想去天堂,那里的源代码可以自由漫游,而错误会杀死自己,该怎么办?

我的解决方案是让子组件公开一个事件,该事件在ngOnInit中发出自己的实例。 然后,父组件可以侦听该事件,并在实例可用时获取实例。 这是一些基本代码:

子组件

export class SubComponent implements OnInit{
  @Input() name:string;
  @Output() init = new EventEmitter<SubComponent>();

  ngOnInit(){
    this.init.emit(this);
    this.init.complete();
  }
}

ParentComponent模板

<sub-cmp *ngFor="let d of data" [name]="d" (init)="onSubInit($event)"></sub-cmp>

ParentComponent类:

onSubInit(sub:SubComponent){
  console.log(sub);
}

现在,在父级的onSubInit中,您将具有子组件的实例,以执行您想执行的任何操作。

现场演示

参见文档。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM