一、说明
Angular每个组件都存在一个生命周期,从创建,变更到销毁。Angular提供组件生命周期钩子,把这些关键时刻暴露出来,赋予在这些关键结点和组件进行交互的能力。
二、angular中总共有8个生命周期钩子函数下面统一介绍
名称调用时机接口名称范围
ngOnChanges当被绑定的输入属性的值发生变化时调用,首次调用一定会发生在 ngOnInit之前。OnChanges指令和组件ngOnInit在第一轮 ngOnChanges 完成之后调用。 ( 译注:也就是说当每个输入属性的值都被触发了一次 ngOnChanges 之后才会调用 ngOnInit ,此时所有输入属性都已经有了正确的初始绑定值 )OnInit指令和组件ngDoCheck在每个 Angular 变更检测周期中调用。DoCheck指令和组件ngAfterContentInit当把内容投影进组件之后调用。AfterContentInit组件ngAfterContentChecked每次完成被投影组件内容的变更检测之后调用。AfterContentChecked组件ngAfterViewInit初始化完组件视图及其子视图之后调用。after initializing the component’s views and child views.AfterViewInit组件ngAfterViewChecked每次做完组件视图和子视图的变更检测之后调用。AfterViewChecked组件ngOnDestroy当 Angular 每次销毁指令 / 组件之前调用。OnDestroy指令和组件
三、查看调用顺序
//在app.component.html代码
<input type="text" [(ngModel)]="name" />
<app-life [item]="name"></app-life>
import { Component } from
'@angular/core';
@Component({
selector:
'app-root',
templateUrl:
'./app.component.html',
styleUrls: [
'./app.component.css']
})
export
class AppComponent {
name:any =
"";
}
//在life.component.html代码
<p>
我是life组件
</p>
<p>我是从父组件输入的内容:{{item}}</p>
import { Component, OnInit,Input,OnChanges,SimpleChanges,DoCheck,AfterContentInit,AfterContentChecked,AfterViewInit,AfterViewChecked,OnDestroy} from
'@angular/core';
@Component({
selector:
'app-life',
templateUrl:
'./life.component.html',
styleUrls: [
'./life.component.css']
})
export
class LifeComponent implements OnInit,OnChanges,DoCheck,AfterContentInit,AfterContentChecked,AfterViewInit,AfterViewChecked,OnDestroy {
@Input() item:any =
"";
index:number =
0;
log(arg):
void{
console.log(`
#${this.index}我是${arg}内容`);
this.
index ++;
}
constructor() {
this.log(
"constructor");
}
ngOnInit() {
this.log(
"ngOnInit");
}
ngOnChanges(changes:SimpleChanges){
this.log(
"ngOnChanges");
}
ngDoCheck(){
this.log(
"ngDoCheck");
}
ngAfterContentInit(){
this.log(
"ngAfterContentInit");
}
ngAfterContentChecked(){
this.log(
"ngAfterContentChecked");
}
ngAfterViewInit(){
this.log(
"ngAfterViewInit");
}
ngAfterViewChecked(){
this.log(
"ngAfterViewChecked");
}
ngOnDestroy(){
this.log(
"ngOnDestroy");
}
}
1、项目初始化后运行效果如下:
2、当用户在输入框输入的时候,传递数据到子组件中运行效果如下:
3、当鼠标离开输入框的时候谷歌控制台的效果 4、angular中变化检测的钩子函数有ngOnChanges、ngDocheck、ngAfterContentChecked、ngAfterViewChecked
四、ngOnChanges的介绍
1、在父组件初始化2、修改子组件 在上面两种情况下会触发ngOnChanges钩子函数,把上面的代码修改下直接打印输出值
ngOnChanges(changes:SimpleChanges){
console.log(
JSON.stringify(changes,
null,
2));
}
运行输出结果,会展示一个对象,显示当前值与上一次的值