Reputation: 1
Even though the doc mentions - A lifecycle hook that is called when any data-bound property of a directive changes. Just want to know why change detection using ngOnchanges() doesn't work when we manually change the color property received from the parent component.
Inside app-component > app-child component
app-child template -
<p>app-child works!</p>
<p> color :: {{color}}</p>
<button (click)="changeColor('red')">Click to change color!</button>
app-child component -
@Input() color : any;
constructor(private cd : ChangeDetectorRef) { }
ngOnInit(): void {
console.log("Inside app- child component ngOnInit, color", this.color);
}
ngOnChanges(sc : SimpleChanges){
console.log("Inside app- child component ngOnChanges, color, sc", this.color, sc);
}
changeColor(color: any){
this.color = color;
this.cd.detectChanges();
}
Upvotes: 0
Views: 1085
Reputation: 154
ngOnChanges will work only when an input property in the child component is changed in the parent. You are changing it in your child component that is not going to trigger ngOnChanges.
Upvotes: 0