组件里的生命周期函数
- ngOnChanges() 父子组件传值,传值数据发生改变
- ngOnInit() (重要)请求数据
- ngDoCheck() 自定义操作
- ngAfterContentInit() 组件渲染结束后
- ngAfterViewInit() (重要)进行DOM操作 视图加载完成
- ngAfterViewChecked() 自定义操作
- ngOnDestroy() 销毁(重要)
html
<button (click)='changeMsg()'>改变msg的值</button>
ts
export class HeaderComponent implements OnInit {
public msg: string = '我是一个生命周期演示';
constructor() {
console.log('00构造函数执行了--除了使用简单的值对局部变量进行初始化之外,什么都应该做')
}
ngOnChanges() {
console.log('01ngOnchanges执行了--当被绑定的输入属性的值发生变化时调用(父子组件传值的时候会触发)')
}
ngOnInit() {
console.log('02ngOnInit执行了--请求数据一般放在这个里面')
}
ngDoCheck() {
console.log('03ngDoCheck执行了--检测,并在发生Angular无法或不愿意自己检测的变化时做出反应')
}
ngAfterContentInit() {
console.log('04ngAfterContentInit执行了--当吧内容头型进组件之后调用')
}
ngAfterContentChecked() {
console.log('05 ngAfterContentChecked执行了--每次完成头型组件内容的变更检测之后调用')
}
ngAfterViewInit() {
console.log('06ngAfterViewInit执行了--初始化完组件视图及其子视图之后调用(DOM操作放在这个里面)')
}
ngAfterViewChecked() {
console.log('07ngAfterViewChecked执行了--每次做完组件视图和子视图的变更检测之后调用')
}
ngOnDestroy() {
console.log('08销毁')
}
//自定义方法
changeMsg() {
this.msg='数据改变了'
}
}