How to detect when an @Input() value changes in Angular?
Answers (1)
Add AnswerThere are two ways to detect changes when @Input value changed.
Using NgOnChanges() lifecycle hook method:
export class SelectedPlayerComponent implements OnChanges { @Input() player: Player; ngOnChanges(changes: SimpleChanges) { console.log(changes.player.currentValue); } }
ngOnChanges
is called by Angular as the component is instantiated.
you can also use an input property setter as follows:
export class SelectedPlayerComponent { private _selected: Player; @Input() set player(value: Player) { this._selected = value; } get player(): Player { return this._selected; } }
Here’s the output for you with the set and get implemented, notice how the get simply returns the this._selected
private property.