【问题标题】:Angular directive AfterContent and AfterView lifecycle hooksAngular 指令 AfterContent 和 AfterView 生命周期钩子
【发布时间】:2018-11-12 13:55:55
【问题描述】:

Angular documentation 声明 AfterContent 和 AfterView 生命周期挂钩仅适用于组件(而不是指令)。尽管如此,我有一个指令显然可以毫无问题地使用它们。

在指令中使用这些钩子有哪些限制/可能的问题?

这是一个使用 AfterContentInit 的指令示例:

@Directive({
  selector: '[myDirective]'
})
export class MyDirective implements AfterContentInit {
  ngAfterContentInit() {
    console.log('my directive after content init');
  }
}

@Component({
  selector: 'my-app',
  template: `
    <div myDirective></div>
  `,
})
export class App {}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App, MyDirective ],
  bootstrap: [ App ]
})
export class AppModule {}

Code live on Plunker

【问题讨论】:

    标签: angular


    【解决方案1】:

    是的,你是对的,他们也将被称为 directives,因为在幕后 angular 仅使用 Directive 定义。另请阅读Here is why you will not find components inside Angular

    我只看到一个限制:只保证这些钩子会被组件调用,因为这种行为可能会改变,恕不另行通知

    就个人而言,我在指令内部使用ngAfterContentInit,因为我知道自己在做什么。

    【讨论】:

      猜你喜欢
      • 2017-11-22
      • 2018-08-30
      • 2018-01-11
      • 2019-06-26
      • 2020-03-15
      • 2018-05-28
      • 2017-01-18
      • 2017-11-13
      相关资源
      最近更新 更多