ngOnChanges is a callback method. It is used to detect the changes in input property in angular programming. ngOnChanges is called immediately data-bound properties through the default change detector. When the default change detector has checked the data-bound properties then the ngOnChanges method is called. You can say ngOnChanges is a lifecycle hook. And It’s called when any data-bound property of directive change. The ngOnChanges lifecycle-hook is called when the angular ChangeDetection directs an @Input change in your component.
Read more
child.component.ts
import { Component, OnInit, Input, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<a (click)="changeFromChild()">Change from child</a>
<br/>
{{parentData}}
`
})
export class ChildComponent implements OnInit {
@Input() parentData: any;
constructor() {
}
ngOnInit() {
}
changeFromChild(){
this.parentData -= 1;
}
ngOnChanges(changes: SimpleChanges) {
console.log(changes)
}
}
parent.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
<a (click)="changeFromParent()">Change from parent</a>
<br/>
<app-child [parentData]=data></app-child>
`
})
export class ParentComponent implements OnInit {
data = 0
constructor() {
}
ngOnInit() {
}
changeFromParent(){
this.data += 1;
}
}
ngOnChanges() will fire before ngOnInit() and every time parentDatais updated from its parent component.
ngOnChanges() takes a changes argument of type SimpleChanges.
changeFromChild() won't call ngOnChanges()
changeFromParent() will call ngOnChanges()
When ngOnChanges() is called, this example simply logs the SimpleChanges instance.
The SimpleChanges instance looks like this...
Read more
Comments
Post a Comment