I'm trying to call function ngOnChanges()
in my Angular 5.x component whenever the variable this.test
in component lifecycle or in template is changed but it's not working, ngOnChanges()
function is not called anytime. Please can someone help me?
src/app.ts:
import {Component, NgModule, Input, OnChanges, SimpleChanges} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
@Component({
selector: 'my-app',
template: `
<div>
<input type="text" placeholder="Test field" value="{{ test }}">
</div>
`,
})
export class App implements OnChanges {
@Input() test: string;
name: string;
constructor() {
}
ngOnChanges(changes: SimpleChanges) {
console.log('ngOnChanges');
if (changes.test && !changes.test.isFirstChange()) {
// exteranl API call or more preprocessing...
}
for (let propName in changes) {
let change = changes[propName];
console.dir(change);
if(change.isFirstChange()) {
console.log(`first change: ${propName}`);
} else {
console.log(`prev: ${change.previousValue}, cur: ${change.currentValue}`);
}
}
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
Live preview: https://plnkr.co/edit/ZHFOXFhEkSv2f1U3lehv
Thanks a lot!