How to detect when an @Input() value changes in Angular?

Forums AngularHow to detect when an @Input() value changes in Angular?
Staff asked 7 months ago

Answers (1)

Add Answer
monika gabani Marked As Accepted
Staff answered 7 months ago

There 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.

Subscribe

Select Categories