Jon Jon - 2 months ago 20
TypeScript Question

How to detect when an @Input() value changes in Angular2

I have a parent component (CategoryComponent), a child component (videoListComponent) and an ApiService.

I have most of this working fine i.e. each component can access the json api and get its relevant data via observables.

Currently video list component just gets all videos, I would like to filter this to just videos in a particular category, I achieved this by passing the categoryId to the child via @input().

CategoryComponent.html

<video-list *ngIf="category" [categoryId]="category.id"></video-list>


This works and when the parent CategoryComponent category changes then the categoryId value gets passed through via @input() but I then need to detect this in VideoListComponent and re-request the videos array via APIService (with the new categoryId).

In angular1 I would have done a $watch on the variable. What is the best way to handle this?

Answer

Use the ngOnChanges() lifecycle method in your component.

ngOnChanges is called right after the data-bound properties have been checked and before view and content children are checked if at least one of them has changed.

Here are the Docs.