angular/aio/content/examples/lifecycle-hooks/src/app/on-changes.component.ts
George Kalpakas 97ae2d3b9b refactor(docs-infra): fix docs examples for tslint rule prefer-const (#38143)
This commit updates the docs examples to be compatible with the
`prefer-const` tslint rule.

This is in preparation of updating the docs examples `tslint.json` to
match the one generated for new Angular CLI apps in a future commit.

PR Close #38143
2020-08-07 22:10:55 -04:00

72 lines
1.7 KiB
TypeScript

/* tslint:disable:forin */
// #docregion
import {
Component, Input, OnChanges,
SimpleChanges, ViewChild
} from '@angular/core';
class Hero {
constructor(public name: string) {}
}
@Component({
selector: 'on-changes',
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 OnChangesComponent implements OnChanges {
// #docregion inputs
@Input() hero: Hero;
@Input() power: string;
// #enddocregion inputs
changeLog: string[] = [];
// #docregion ng-on-changes
ngOnChanges(changes: SimpleChanges) {
for (const propName in changes) {
const chng = changes[propName];
const cur = JSON.stringify(chng.currentValue);
const prev = JSON.stringify(chng.previousValue);
this.changeLog.push(`${propName}: currentValue = ${cur}, previousValue = ${prev}`);
}
}
// #enddocregion ng-on-changes
reset() { this.changeLog = []; }
}
@Component({
selector: 'on-changes-parent',
templateUrl: './on-changes-parent.component.html',
styles: ['.parent {background: Lavender;}']
})
export class OnChangesParentComponent {
hero: Hero;
power: string;
title = 'OnChanges';
@ViewChild(OnChangesComponent) childView: OnChangesComponent;
constructor() {
this.reset();
}
reset() {
// new Hero object every time; triggers onChanges
this.hero = new Hero('Windstorm');
// setting power only triggers onChanges if this value is different
this.power = 'sing';
if (this.childView) { this.childView.reset(); }
}
}