为什么AppComponent默认没有ngOnInit函数?

问题描述 投票:6回答:1

在使用CLI生成Angular项目时,根组件 - AppComponent没有ngOnInit块,但生成的每个其他组件都有一个ngOnInit块。在根组件中有一个ngOnInit是不对的吗?

angular angular-cli
1个回答
0
投票

在根组件中有一个ngOnInit没有错。但没有必要。

根据定义,root组件只需在index.html中调用<app-root></app-root>一次。并没有被任何其他组件调用。因此,根组件不会有@Input()确保设置正确的ngOnInit绑定。

未viable.component.html:

<app-root [someInput]="variable"></app-root>

结论

您可以在根组件中使用ngOnInit,但constructor可以做同样的事情而没有任何缺陷。

© www.soinside.com 2019 - 2024. All rights reserved.