forked from angular/angular.io
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathdo-check.component.ts
96 lines (82 loc) · 2.41 KB
/
do-check.component.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/* tslint:disable:forin */
// #docregion
import { Component, DoCheck, Input, ViewChild } from '@angular/core';
class Hero {
constructor(public name: string) {}
}
@Component({
selector: 'do-check',
template: `
<div class="hero">
<p>{{hero.name}} can {{power}}</p>
<h4>-- Change Log --</h4>
<div *ngFor="let chg of changeLog">{{chg}}</div>
</div>
`,
styles: [
'.hero {background: LightYellow; padding: 8px; margin-top: 8px}',
'p {background: Yellow; padding: 8px; margin-top: 8px}'
]
})
export class DoCheckComponent implements DoCheck {
@Input() hero: Hero;
@Input() power: string;
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.
let count = this.noChangeCount += 1;
let 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.length = 0;
}
}
/***************************************/
@Component({
moduleId: module.id,
selector: 'do-check-parent',
templateUrl: './do-check-parent.component.html',
styles: ['.parent {background: Lavender}']
})
export class DoCheckParentComponent {
hero: Hero;
power: string;
title = 'DoCheck';
@ViewChild(DoCheckComponent) childView: DoCheckComponent;
constructor() { this.reset(); }
reset() {
this.hero = new Hero('Windstorm');
this.power = 'sing';
if (this.childView) { this.childView.reset(); }
}
}