• 挂载阶段的生命周期函数只在挂载阶段执行一次,数据更新时不再执行

    constructor

  • Angular 在实例化组件类时执行, 可以用来接收 Angular 注入的服务实例对象

    1. export class HelloComponent {
    2. constructor(private test: TestService) {
    3. console.log(this.test) // "test"
    4. }
    5. }

    ngOnInit

  • 在首次接收到输入属性值后执行,在此处可以执行请求操作

    1. export class HelloComponent implements OnInit {
    2. @Input("name") name: string = ""
    3. constructor() { }
    4. ngOnInit() {
    5. console.log(this.name) // "张三"
    6. }
    7. }

    ngAfterContentInit

  • 当内容投影初始渲染完成后调用 ```typescript

    Hello Angular

export class ChildComponent implements AfterContentInit { @ContentChild(“box”) box: ElementRef | undefined

  1. ngAfterContentInit() {
  2. console.log(this.box) // <div>Hello Angular</div>
  3. }

}

  1. <a name="s06XN"></a>
  2. ### ngAfterViewInit
  3. - 当组件视图渲染完成后调用
  4. ```typescript
  5. <!-- app-child 组件模板 -->
  6. <p #p>app-child works</p>
  7. export class ChildComponent implements AfterViewInit {
  8. @ViewChild("p") p: ElementRef<HTMLParagraphElement> | undefined
  9. ngAfterViewInit () {
  10. console.log(this.p) // <p>app-child works</p>
  11. }
  12. }