Angular生命周期

生命周期

Angular从程序引导启动、再到创建与销毁组件动作都有一系列钩子事件,它允许我们在某个阶段有机会做点处理。

名称说明范围
constructor构造函数指令和组件
ngOnChanges属性变更通知指令和组件
ngOnInit组件初始化指令和组件
ngDoCheck每一次变更检测时指令和组件
ngAfterContentInit子组件初始化后组件
ngAfterContentChecked子组件变更检测之后组件
ngAfterViewInit组件初始化后组件
ngAfterViewChecked组件每次变更检测之后组件
ngOnDestroy初始销毁之前指令和组件

step1:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'untitled2906';
  //参考网址:https://cipchk.gitbooks.io/angular-practice/content/component/lifecycle.html


  /**
   * 组件或指令初始化完成后数据变更检测前触发。
   * 因此,这个时候组件的模板 template 值已经写入DOM树当中,这个时候在这里做数据请求与处理再适合不过了。
   */
  ngOnInit() {
    console.log('ngOnInit')
  }


  /**
   每次变更检测(不管是否有数据)周期时触发,这是一个高频率触发,所以不要在这时在做一些复杂的操作。
   */
  ngDoCheck() {
    console.log('ngDoCheck')
  }

  /**
   * AfterContent 系列钩子优先于 AfterView
   */
  ngAfterContentInit() {
    console.log('ngAfterContentInit')
  }

  /**
   * 每次变更检测(不管是否有数据)周期时触发,优先级略低于 ngDoCheck()。
   */
  ngAfterContentChecked() {
    console.log('ngAfterContentChecked')
  }

  /**
   * AfterContent 系列钩子优先于 AfterView
   */
  ngAfterViewInit() {
    console.log('ngAfterViewInit')
  }

  /**
   * 每次变更检测(不管是否有数据)周期时触发,优先级略低于 ngDoCheck()。
   */
  ngAfterViewChecked() {
    console.log('ngAfterViewChecked')
  }

  /**
   * 组件或指令初始销毁之前触发。
   */
  ngOnDestroy() {
    console.log('ngOnDestroy')
  }

}

step2: run ,执行顺序

ngOnInit
ngDoCheck
ngAfterContentInit
ngAfterContentChecked
ngAfterViewInit
ngAfterViewChecked
ngDoCheck
ngAfterContentChecked
ngAfterViewChecked

end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值