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.