I am currently experimenting with Angular 2 in an effort to learn more about it. I noticed that ngOnChanges
is not triggering in the code below:
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 does not trigger ngOnChanges
However, when I create a separate component called "simple" and use it in app.component.ts, the following setup works correctly:
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;
}
Could someone offer an explanation? What mistake am I making here?