Files
Angular-Docs-Cn/aio/content/examples/lifecycle-hooks/src/app/do-check.component.ts
T
Kristiyan Kostadinov e86a1d3441 docs: make all examples compatible with strict mode (#41999)
Turns on the `strict` compiler flag and resolves the compilation errors in the various AIO examples.

PR Close #41999
2021-05-17 10:42:18 -07:00

68 lines
1.7 KiB
TypeScript

/* tslint:disable:forin */
// #docregion
import { Component, DoCheck, Input } from '@angular/core';
import { Hero } from './hero';
@Component({
selector: 'do-check',
template: `
<div class="info">
<p>{{hero.name}} can {{power}}</p>
<h3>Change Log</h3>
<div *ngFor="let chg of changeLog" class="log">{{chg}}</div>
</div>
`
})
export class DoCheckComponent implements DoCheck {
@Input() hero!: Hero;
@Input() power = '';
changeDetected = false;
changeLog: string[] = [];
oldHeroName = '';
oldPower = '';
oldLogLength = 0;
noChangeCount = 0;
// #docregion ng-do-check
ngDoCheck() {
if (this.hero.name !== this.oldHeroName) {
this.changeDetected = true;
this.changeLog.push(`DoCheck: Hero name changed to "${this.hero.name}" from "${this.oldHeroName}"`);
this.oldHeroName = this.hero.name;
}
if (this.power !== this.oldPower) {
this.changeDetected = true;
this.changeLog.push(`DoCheck: Power changed to "${this.power}" from "${this.oldPower}"`);
this.oldPower = this.power;
}
if (this.changeDetected) {
this.noChangeCount = 0;
} else {
// log that hook was called when there was no relevant change.
const count = this.noChangeCount += 1;
const noChangeMsg = `DoCheck called ${count}x when no change to hero or power`;
if (count === 1) {
// add new "no change" message
this.changeLog.push(noChangeMsg);
} else {
// update last "no change" message
this.changeLog[this.changeLog.length - 1] = noChangeMsg;
}
}
this.changeDetected = false;
}
// #enddocregion ng-do-check
reset() {
this.changeDetected = true;
this.changeLog = [];
}
}