【问题标题】:Why doesn't the AppComponent have an ngOnInit function by default?为什么 AppComponent 默认没有 ngOnInit 函数?
【发布时间】:2017-08-18 11:10:42
【问题描述】:

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

【问题讨论】:

    标签: angular angular-cli


    【解决方案1】:

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

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

    不可行.component.html:

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

    结论

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-17
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      • 2013-03-20
      • 2018-07-01
      • 2011-06-17
      相关资源
      最近更新 更多