指令和组件的实例有一个生命周期:新建、更新和销毁。 通过实现一个或多个 Angular core
库里定义的生命周期钩子接口,开发者可以介入该生命周期中的这些关键时刻。
每个接口都有唯一的一个钩子方法,它们的名字是由接口名再加上 ng
前缀构成的。比如,OnInit
接口的钩子方法叫做 ngOnInit
, Angular 在创建组件后立刻调用它,:
生命周期的顺序:
钩子 | 用途及时机 |
---|---|
ngOnChanges() | 当 Angular(重新)设置数据绑定输入属性时响应。 该方法接受当前和上一属性值的 SimpleChanges 对象当被绑定的输入属性的值发生变化时调用,首次调用一定会发生在 ngOnInit() 之前。 |
ngOnInit() | 在 Angular 第一次显示数据绑定和设置指令/组件的输入属性之后,初始化指令/组件。在第一轮 ngOnChanges() 完成之后调用,只调用一次。 |
ngDoCheck() | 检测,并在发生 Angular 无法或不愿意自己检测的变化时作出反应。在每个 Angular 变更检测周期中调用,ngOnChanges() 和 ngOnInit() 之后。 |
ngAfterContentInit() | 当把内容投影进组件之后调用。第一次 ngDoCheck() 之后调用,只调用一次。 |
ngAfterContentChecked() | 每次完成被投影组件内容的变更检测之后调用。ngAfterContentInit() 和每次 ngDoCheck() 之后调用 |
ngAfterViewInit() | 初始化完组件视图及其子视图之后调用。第一次 ngAfterContentChecked() 之后调用,只调用一次。 |
ngAfterViewChecked() | 每次做完组件视图和子视图的变更检测之后调用。ngAfterViewInit() 和每次 ngAfterContentChecked() 之后调用。 |
ngOnDestroy() | 当 Angular 每次销毁指令/组件之前调用并清扫。 在这儿反订阅可观察对象和分离事件处理器,以防内存泄漏。在 Angular 销毁指令/组件之前调用。 |
ngOnchanges函数触发的例子:
父组件:
import { Component, OnInit } from '@angular/core';
import { LogCustomService } from '../log-custom.service';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
name = '小明';
constructor(private logCustomService: LogCustomService) { }
ngOnInit() {
this.logCustomService.log('ngOnInit');
}
}
// 模板
<div>
<label>姓名:</label>
<input type="text" [(ngModel)]="name">
<div>名字为{{ name }}</div>
</div>
<app-child [userName]="name"></app-child>
子组件:
import { Component, OnInit, Input, OnChanges, SimpleChanges } from '@angular/core';
import { LogCustomService } from '../log-custom.service';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit, OnChanges {
@Input() userName: string;
constructor(private logCustomService: LogCustomService) { }
ngOnInit() {
console.log('子组件初始化');
}
ngOnChanges(changes: SimpleChanges) {
console.log(changes);
}
}
// 模板
<p>
该用户的名字叫做 {{userName}}
</p>
当子组件的输入属性改变的时候,触发ngOnchanges函数。
一般在ngOnInit()函数中获取初始数据是比较好的,ngAfterViewInit()在组件交互中父组件获取子组件属性的例子中用到,还有ngAfterViewChecked()