How to detect @input() bindings changes in Angular?

It is a short tutorial on how to detect when an @input changes.

@input is an angular decorator that helps us with property binding for an input.

So input name implies that it is input data passed to the component.

@input adds metadata to the angular component for property binding and allows the addition of it to the DOM element.

@input directive used in the following things

  • Passing data from child to parent or vice versa
  • Passing data as input to component

@input is a directive from the @angular/core module, So you have to import it to use in the Angular component.

Let’s declare a component input-binding.component.ts in Angular

And pass input data to this component.

For example

<input-binding data="Welcome Cloudhadoop"></input-binding>

How do detect @input changes in the Angular component?

There are multiple ways we can detect changes.

using ngOnChanges binding as one way of binding

ngOnChanges is a component lifecycle method, this will be called whenever data of input property is changed.

It accepts the SimpleChanges class which is from the @angular/core module. SimpleChanges holds currentValue,previousValue of input property

ngOnChanges(changes: SimpleChanges) :void {
}

Here is an example

import { Component, Input, OnInit, SimpleChanges } from "@angular/core";

@Component({
  selector: "input-binding",
  templateUrl: "./input-binding.component.html",
  styleUrls: ["./input-binding.component.css"],
})
export class InputBindingComponent implements OnInit {
  @Input() data: String;

  ngOnChanges(changes: SimpleChanges) {
    // get Current Value
    let currentVal = changes.data.currentValue;
    // get Previous Value
    let previousVal = changes.previousValue;
  }

  constructor() {}

  ngOnInit() {}
}

Html component

<h1>Input input-binding example</h1>

<div>{{data}}</div>

This component can be used in any other components or modules.

<input-binding data="Welcome user"></input-binding>

This approach is used when you have all changes can be detected with the ngOnChanges method, And it holds current and previous values which you can compare it

Input Property setter and getter methods

if you have simple one-input changes, We can use this approach And is simple to use this approach.

  • Provide input property which you have setter and getter for it

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

@Component({
  selector: 'input-binding',
  templateUrl: './input-binding.component.html',
  styleUrls: ['./input-binding.component.css']
})
export class InputBindingComponent implements OnInit {

  private _name: string;

  @Input() set name(value: string) {
    this._name = value;
  }

  get name(): string {
    return this._name;
  }

  constructor() {}

  ngOnInit() {}
}

The component can be used as seen below

<input-binding name="Welcome Cloudhadoop"></input-binding>