I am trying to learn Angular 2 by experimenting and I found that ngOnChanges
doesn't fire in the following code:
app.component.ts:
import { Component, Input } from "@angular/core"
import { FormsModule } from '@angular/forms';
import { OnChanges, SimpleChanges } from '@angular/core/src/metadata/lifecycle_hooks';
@Component({
selector: 'my-app',
template: `
Enter text : <input type="text" [(ngModel)]='userText' />
<br/>
Entered text : {{userText}}
`
})
export class AppComponent {
@Input() userText: string;
name: string = "Tom";
ngOnChanges(changes: SimpleChanges): void {
for (let propertyName in changes) {
let change = changes[propertyName];
let current = JSON.stringify(change.currentValue);
let previouis = JSON.stringify(change.previousValue);
console.log(propertyName + ' ' + current + ' ' + previouis);
}
}
}
The above code doesn't fire ngOnChanges
However, if I create a separate component "simple" and use it in app.scomponent.ts, the following works:
app.component.ts:
import {Component} from "@angular/core"
import {FormsModule} from '@angular/forms';
@Component({
selector: 'my-app',
template: `
Enter text : <input type="text" [(ngModel)]='userText' />
<br/>
<simple [simpleInput]='userText'></simple>
`
})
export class AppComponent{
userText:string;
name:string ="Tom";
}
simple.component.ts:
import {Component,Input} from '@angular/core';
import { OnChanges,SimpleChanges } from '@angular/core/src/metadata/lifecycle_hooks';
@Component({
selector:'simple',
template: `You entered {{simpleInput}} `
})
export class SimpleComponent implements OnChanges{
ngOnChanges(changes: SimpleChanges): void {
for(let propertyName in changes){
let change=changes[propertyName];
let current=JSON.stringify(change.currentValue);
let previouis=JSON.stringify(change.previousValue);
console.log(propertyName+ ' '+current+ ' ' +previouis);
}
}
@Input() simpleInput: string;
}
Can someone please provide an explanation? What am I doing wrong here?