Skip to content

Listen for changes of an @Input property in Angular

In Angular, you can use the @Input decorator to pass data from a parent component to a child component. When the input property changes in the parent component, Angular automatically updates the child component with the new value.

However, there are cases where you need to listen for changes to the input property in the child component. For example, you may want to perform some action when the input property changes or update the child component based on the new value.

In this article, we will explore how to listen for changes to an @Input property in an Angular component.

Using ngOnChanges lifecycle hook

Angular provides a lifecycle hook called ngOnChanges that is called whenever the input properties of a component change. You can implement this hook in the child component to listen for changes to the input property.

Here’s how you can use ngOnChanges to listen for changes to an @Input property:

import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `
    <p>Input value: {{ inputValue }}</p>
  `
})

export class ChildComponent implements OnChanges {
  @Input() inputValue: string;

  ngOnChanges(changes: SimpleChanges) {
    if (changes.inputValue) {
      console.log('Input value changed:', changes.inputValue.currentValue);
    }
  }
}

In the above example, we have a child component ChildComponent that has an @Input property inputValue. We implement the OnChanges interface and define the ngOnChanges method to listen for changes to the inputValue property. The ngOnChanges method receives a SimpleChanges object that contains the previous and current values of the input properties.

Using a setter method

Another way to listen for changes to an @Input property is to define a setter method for the input property. When the input property changes, Angular calls the setter method with the new value.

Here’s how you can define a setter method to listen for changes to an @Input property:

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `
    <p>Input value: {{ inputValue }}</p>
  `
})

export class ChildComponent {
  private _inputValue: string;

  @Input()
  set inputValue(value: string) {
    this._inputValue = value;
    console.log('Input value changed:', value);
  }

  get inputValue(): string {
    return this._inputValue;
  }
}

In the above example, we define a private property _inputValue to store the value of the input property. We define a setter method for the inputValue property that logs the new value when it changes. We also define a getter method to retrieve the value of the input property.

Conclusion

There are two approaches to listen for changes to an @Input property in an Angular component: