在使用CLI生成Angular项目时,根组件 - AppComponent没有ngOnInit块,但生成的每个其他组件都有一个ngOnInit块。在根组件中有一个ngOnInit是不对的吗?
在根组件中有一个ngOnInit没有错。但没有必要。
根据定义,root组件只需在index.html中调用<app-root></app-root>
一次。并没有被任何其他组件调用。因此,根组件不会有@Input()
确保设置正确的ngOnInit
绑定。
未viable.component.html:
<app-root [someInput]="variable"></app-root>
结论
您可以在根组件中使用ngOnInit
,但constructor
可以做同样的事情而没有任何缺陷。