angular学习(OnChanges)
1.OnChanges
当组件的任何输入属性发生变化,组件生命周期提供的钩子ngOnChanges 可捕获变化的内容。
示例:
Parent组件是Child组件的父组件,变化检测从根组件开始,会比 Child更早执行变化检测,在执行变化检测时 Parent中的pa属性,会传递到 Child的输入属性param中。此时 Child组件检测到param属性发生变化,因此组件内的 p 元素内的文本值从空字符串 变成 param的值。
child.component.ts
import {
Component, OnInit, Input, OnChanges, SimpleChange } from '@angular/core';
@Component({
selector: 'exe-child',
// templateUrl: './child.component.html',
template: `
<p>{
{ param1 }}</p>
<p>{
{ param2 }}</p>
<button (click)="changeParam1()">change param1</button>
`,
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
@Input()
param1: string;
@Input()
param2: string;
ngOnChanges(changes: SimpleChange){
console.log(changes);
}
//不会触发ngOnChanges钩子,但能改变param1的值
changeParam1(){
this.param1 = 'abc';
console.log(this.param1);
}
constructor() {
}
ngOnInit() {
}
}
parent.component.ts
import {
Component, OnInit } from '@angular/core';
@Component({
selector: 'exe-parent',
// templateUrl: './parent.component.html',
template: `
<exe-child [param1]="pa1" [param2]="pa2"></exe-child>
`,
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
pa1: string = 'aaa';
pa2: string = 'bbb';
constructor() {
}
ngOnInit() {
// this.pa1 = '666';
}
}
用ngOnChanges()捕获的变化内容如图: