关联学习:
- Angular 8 组件的生命周期-指令的生命周期
- Angular 8 组件的生命周期-ngOnChanges
- Angular 8 组件的生命周期-AfterView
- Angular 8 组件的生命周期-AfterContent
1. 什么是生命周期
- 生命周期函数通俗的讲就是组件创建、组件更新、组件销毁的时候会触发的一系列的方法。
- 当 Angular 使用构造函数新建一个组件或指令后,就会按下面的顺序在特定时刻调用这些 生命周期钩子方法。
- 每个接口都有唯一的一个钩子方法,它们的名字是由接口名再加上ng前缀构成的,比如OnInit接口的钩子方法叫做ngOnInit
2. 生命周期钩子分类
2.1 指令与组件共有的钩子
- ngOnChanges
- ngOnInit
- ngDoCheck
- ngOnDestroy
2.2组件特有的钩子
- ngAfterContentInit
- ngAfterContentChecked
- ngAfterViewInit
- ngAfterViewChecked
3. 生命周期的顺序
constructor-构造函数
钩子方法 | 时机 |
---|---|
ngOnChanges | 当数据绑定输入属性的值发生变化时调用 |
ngOnInit | 在第一次 ngOnChanges 后调用 |
ngDoCheck | 自定义的方法,用于检测和处理值的改变 |
ngAfterContentInit | 在组件内容初始化之后调用 |
ngAfterContentChecked | 组件每次检查内容时调用 |
ngAfterViewInit | 组件相应的视图初始化之后调用 |
ngAfterViewChecked | 组件每次检查视图时调用 |
ngOnDestroy | 指令销毁前调用 |
3.1 实例
1.father.component.html
<p>father works!</p>
<button pButton type="button" (click)="toggleChild()">{{hasChild?'Destroy':'Create'}} Child1Component</button>
<button pButton type="button" label="Update" class="p-button-outlined" (click)="updateName()" [hidden]="!hasChild"></button>
<app-child1 *ngIf="hasChild" [name]="name" >child1</app-child1>
- father.component.ts
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-father',
templateUrl: './father.component.html',
styleUrls: ['./father.component.css']
})
export class FatherComponent implements OnInit {
public hasChild:boolean = false;
public name:string = 'child1';
constructor() {}
ngOnInit(): void {
}
toggleChild() {
this.hasChild = !this.hasChild;
}
updateName() {
this.name = 'child change!'
}
}
- child1.component.html
<h1>{{name}}</h1>
- child2.component.ts
import { AfterContentChecked, AfterContentInit, AfterViewChecked, AfterViewInit, Component, DoCheck, Input, OnChanges, OnDestroy, OnInit } from '@angular/core';
@Component({
selector: 'app-child1',
templateUrl: './child1.component.html',
styleUrls: ['./child1.component.css']
})
export class Child1Component implements OnInit,
OnChanges,
DoCheck,
AfterContentInit,
AfterContentChecked,
AfterViewInit,
AfterViewChecked,
OnDestroy {
@Input() name:string = '';
constructor() {
console.log('1#.constructor!');
}
ngOnInit(): void {
console.log('3#.ngOnInit!');
}
ngOnChanges() {
console.log('2#.ngOnChanges!');
}
ngDoCheck() {
console.log('4#.ngDoCheck!');
}
ngAfterContentInit() {
console.log('5#.ngAfterContentInit!');
}
ngAfterContentChecked() {
console.log('6#.ngAfterContentChecked!');
}
ngAfterViewInit() {
console.log('7#.ngAfterViewInit!');
}
ngAfterViewChecked() {
console.log('8#.ngAfterViewChecked!');
}
ngOnDestroy() {
console.log('9#.ngOnDestroy!');
}
}