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

March 26, 2022 No comments Angular Input change

1. Introduction

In this tutorial, we are going to present ways of detecting when an Input() value changes in a component in Angular 2+.

2. Ways to detect when an Input() value changes

  • Using ngOnChanges(changes: SimpleChanges) lifecycle method:
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: []
})
export class ChildComponent implements OnChanges {

  @Input()
  value: string;

  ngOnChanges(changes: SimpleChanges): void {
    doSomething(changes.value.currentValue);
  }

  doSomething(val: string): void {
    console.log(val);
  }
}
  • Using input property setter @Input() set value(value: string):
import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: []
})
export class ChildComponent {

  private _value: string;

  @Input() set value(value: string) {
    this._value = value;
    this.doSomething();
  }

  get value(): string {
    return this._value;
  }

  doSomething(): void {
    console.log(this._value);
  }
}

The first approach requires that our component will implement OnChanges interface. The ngOnChange() method will get all changes for all the Input() values. We are also able to compare the current and previous values of the input. It should be useful when our component has more than one Input().

When we want to check if a particular Input() value changes, then using property setter seems to be a simpler solution. But, keep in mind that in this approach you will not be able to compare the actual and previous value of the input.

3. More about Input() decorator

The @Input() decorator marks the field in the Angular component as an input property. That property is bound to a DOM property in the HTML template.

Input() decorators are used for sharing data between a parent component and one or more child components.

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

@Component({
  selector: 'app-child',
  templateUrl: `
    First name: {{firstName}}
    Last name: {{lastName}}
  `,
  styleUrls: []
})
export class ChildComponent {

  @Input()
  firstName: string;

  @Input()
  lastName: string;
}


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

@Component({
  selector: 'app-parent',
  templateUrl: `
    <app-child firstName='John' lastName='Doe'></app-child>
  `,
  styleUrls: []
})
export class ParentComponent {
}

4. Conclusion

In this article, we presented several ways of detecting Input() value changes in Angular. We also described a bit the Input() decorator.

{{ message }}

{{ 'Comments are closed.' | trans }}