app HTML
<div class="parent">
<div>
问候语:<input type = "text" [(ngModel)]="greeting">
</div>
<div>
姓名: <input type = "text" [(ngModel)]="user.name">
</div>
</div>
<app-child [greeting]="greeting" [user]="user "></app-child>
app TS
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
greeting = 'Hello';
user: {name: string} = {name: 'Jenny'};
// tslint:disable-next-line:use-lifecycle-interface
ngOnInit(): void {
}
}
child HTML
<div class="child">
<h2>我是子组件</h2>
<div>问候语:{{greeting}}</div>
<div>姓名:{{user.name}}</div>
<div>消息:<input [ngModel]="message"></div>
</div>
child TS
import {Component, DoCheck, Input, OnChanges, OnInit, SimpleChanges} from '@angular/core';
// tslint:disable-next-line:no-conflicting-lifecycle
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit, OnChanges, DoCheck {
@Input()
greeting: string;
@Input()
user: { name: string };
oldUsername: string;
changeDetected = false;
noChangeCount = 0;
message = '初始化消息';
constructor() {
}
ngOnChanges(changes: SimpleChanges): void {
console.log(JSON.stringify(changes, null, 2));
}
ngOnInit(): void {
}
ngDoCheck(): void {
if (this.user.name !== this.oldUsername){
this.changeDetected = true;
console.log('ngDoCheck:用户名发生了变化,由' + this.oldUsername + '变更为了' + this.user.name);
this.oldUsername = this.user.name;
}
if (this.changeDetected){
this.noChangeCount = 0;
}else{
this.noChangeCount = this.noChangeCount + 1;
console.log('名称无变化时,ngDoCheck方法被调用了多少' + this.noChangeCount + '次');
}
this.changeDetected = false;
}
}
其中doCheck方法,因为是事件触发,及时调整一下光标也能触发,会造成性能问题,慎用。
本文探讨Angular组件的onChanges和doCheck生命周期钩子。doCheck由于事件触发频繁,可能导致性能问题,建议谨慎使用。
2704





