How to detect @input value changes in Angular

Angular provides several mechanisms to detect changes in a component. One common scenario is detecting changes to @Input bindings, which are used to pass data from a parent component to a child component. In this guide, we’ll explore multiple ways to detect changes in Angular components and respond accordingly.

1. Using ngOnChanges Lifecycle Hook

The ngOnChanges hook is a lifecycle hook that is called whenever the input properties of a component change. It receives a SimpleChanges object containing the previous and current values of the input properties.

Let’s create a simple example to demonstrate this:

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

@Component({
  selector: 'app-child',
  template: '<p>{{ inputValue }}</p>',
})
export class ChildComponent implements OnChanges {
  @Input() inputValue: string;

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

In this example, the ngOnChanges method is triggered whenever the inputValue changes. You can perform custom logic based on the changes.

2. Using Property Setter for @Input

You can also use a property setter for an @Input property. This allows you to execute custom logic whenever the property is updated:

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

@Component({
  selector: 'app-child',
  template: '<p>{{ inputValue }}</p>',
})
export class ChildComponent {
  private _inputValue: string;

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

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

In this example, the set block of the inputValue property is executed whenever the value changes, allowing you to perform custom actions.

3. Using ngOnChanges in Parent Component

Sometimes, you may want to detect changes to @Input properties in the parent component. In this case, you can leverage the ngOnChanges lifecycle hook in the parent component:

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

@Component({
  selector: 'app-parent',
  template: `
    <app-child [inputValue]="parentValue"></app-child>
  `,
})
export class ParentComponent implements OnChanges {
  @Input() parentValue: string;

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.parentValue) {
      console.log('Parent value changed:', changes.parentValue.currentValue);
    }
  }
}

By using the ngOnChanges hook in the parent component, you can respond to changes in the child component’s @Input properties.

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads

CodeGuru