There are two components namely ParentComponent and ChildComponent. We are binding a variable from parent component to child component. As per angular documentation "ngOnChanges" of child component gets called whenever the value of property in parent component get changed. Now in ParentComponent we are changing the value of that variable for the two times but in ChildComponent , "ngOnChanges" is getting called only one time.
Parent Component is as follows:
ParentComponent.html
<p>parentcomponent works!</p>
<button (click)="onClicking()">Click here</button>
<app-childcomponent [temp]="inputfromparent"></app-childcomponent>
ParentComponent.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-parentcomponent',
templateUrl: './parentcomponent.component.html',
styleUrls: ['./parentcomponent.component.css']
})
export class ParentcomponentComponent implements OnInit {
private inputfromparent = "B"
constructor() { }
ngOnInit() {
}
onClicking(){
this.inputfromparent = "C"; //line1
console.log("Hello");
this.inputfromparent= "D"; //line2
}
}
Child Component is as follows:
ChildComponent.ts
import { Component, OnInit, OnChanges, Input } from '@angular/core';
@Component({
selector: 'app-childcomponent',
templateUrl: './childcomponent.component.html',
styleUrls: ['./childcomponent.component.css']
})
export class ChildcomponentComponent implements OnInit, OnChanges{
@Input() private temp = "A";
constructor() { }
ngOnInit() {
}
ngOnChanges(change){
var test = change;
console.log(test);
console.log(this.temp);
}
}
In ParentComponent.ts file we are changing the value of "inputfromparent " two times whenever "onClicking" method gets called on clicking button defined in ParentComponent.html file (refer line1 and line2). And since we are binding this variable with variable "temp" of ChildComponent.ts file, so "ngOnChanges" of ChildComponent.ts file should get called twice as per angular documentation, which is as follows:
A lifecycle hook that is called when any data-bound property of a directive changes. Define an ngOnChanges() method to handle the changes.
But "ngOnChanges" of ChildComponent.ts file is only getting called only one time whenever "onClicking" is called on clicking button defined in ParentComponent.html file.
My doubt is that, since we are changing the value of "inputfromparent", two times in "onClicking" method of ParentComponent.ts file, so "ngOnChanges" of ChildComponent.ts file should get called for the two times. But it is getting called only once.