Angular指令AfterContent和AfterView生命周期钩子

时间:2017-10-26 09:31:31

标签: angular

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

1 个答案:

答案 0 :(得分:4)

是的,你是对的,他们也会被称为 指令 ,因为幕后角度仅使用指令定义。另请阅读Here is why you will not find components inside Angular

我只看到一个限制:只保证会为组件调用这些钩子,因为这种行为可能会在没有进一步通知的情况下发生变化

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