Categories
Angular Answers

How to detect changes in an array from an @input property with Angular?

Spread the love

Sometimes, we want to detect changes in an array from an @input property with Angular.

In this article, we’ll look at how to detect changes in an array from an @input property with Angular.

How to detect changes in an array from an @input property with Angular?

To detect changes in an array from an @input property with Angular, we can get the latest value in the ngDoCheck method.

For instance, we write

//...
export class AppComponent implements OnInit {
  constructor(private iterableDiffers: IterableDiffers) {
    this.iterableDiffer = iterableDiffers.find([]).create(null);
  }

  ngDoCheck() {
    const changes = this.iterableDiffer.diff(this.inputArray);
    if (changes) {
      console.log("Changes detected!");
    }
  }
  //...
}

to inject the IterableDiffers dependency into our component.

Then we write this.iterableDiffer.diff(this.inputArray) to check if there’re any changes.

If changes is defined, then there’re changes.

Conclusion

To detect changes in an array from an @input property with Angular, we can get the latest value in the ngDoCheck method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *