Angular 8 组件的生命周期-ngOnChanges
1. 使用变更检测钩子
- 一旦检测到该组件或指令的输入属性发生了变化,Angular 就会调用它的 ngOnChanges() 方法。 这个 onChanges 范例通过监控 OnChanges() 钩子演示了这一点。
- ngOnChanges() 方法获取了一个对象,它把每个发生变化的属性名都映射到了一个SimpleChange对象, 该对象中有属性的当前值和前一个值。这个钩子会在这些发生了变化的属性上进行迭代,并记录它们。
- 日志条目把 power 属性的变化显示为字符串。但请注意,ngOnChanges() 方法不会捕获对 hero.name 更改。这是因为只有当输入属性的值发生变化时,Angular 才会调用该钩子。在这种情况下,hero 是输入属性,hero 属性的值是对 hero 对象的引用 。当它自己的 name 属性的值发生变化时,对象引用并没有改变。
father.component.html
<app-on-changes-parent></app-on-changes-parent>
on-changes-parent.component.html
<div>
<h2>{{title}}</h2>
<label>Power:</label>
<input [(ngModel)]="power"/>
<label>Hero Name:</label>
<input [(ngModel)]="hero.name"/>
<button pButton type="button" (click)="reset()">Reset Log</button>
<app-on-changes [hero]="hero" [power]="power"></app-on-changes>
</div>
on-changes-parent.component.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { OnChangesComponent } from '../on-changes/on-changes.component';
class Hero {
constructor(public name:string) {
this.name = name;
}
}
@Component({
selector: 'app-on-changes-parent',
templateUrl: './on-changes-parent.component.html',
styleUrls: ['./on-changes-parent.component.css']
})
export class OnChangesParentComponent implements OnInit {
public title:string = 'OnChanges';
public power:string = '';
public hero:Hero = new Hero('');
@ViewChild(OnChangesComponent)childCompent!:OnChangesComponent;
constructor() {
this.reset();
}
ngOnInit() {
console.log(`on changes parent ngOnInit!`);
}
reset() {
this.hero = new Hero('Windstorm');
this.power = 'sing';
// 访问子节点的函数
if(this.childCompent) {
this.childCompent.reset();
}
}
}
on-changes.component.html
<div>
<p> {{hero.name}} can {{power}}</p>
<h2>Change Log</h2>
<p *ngFor="let chg of changeLog">{{chg}}</p>
</div>
on-changes.component.ts
import { Component, Input, OnInit, SimpleChanges } from '@angular/core';
import { resetFakeAsyncZone } from '@angular/core/testing';
class Hero {
constructor(public name:string) {
this.name = name;
}
}
@Component({
selector: 'app-on-changes',
templateUrl: './on-changes.component.html',
styleUrls: ['./on-changes.component.css']
})
export class OnChangesComponent implements OnInit {
@Input() power:string = '';
@Input() hero: Hero = new Hero('');
public changeLog:string[] = [];
constructor() { }
ngOnInit() {
console.log(`on changes component ngOnInit!`);
}
ngOnChanges(changes: SimpleChanges): void {
for(const propName in changes) {
const chng = changes[propName];
const current = JSON.stringify(chng.currentValue);
const previous = JSON.stringify(chng.previousValue);
this.changeLog.push(`${propName}:currentValue=${current}, pervious=${previous}`);
}
}
reset() {
this.changeLog = [];
}
}
运行效果: