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 AngularJS I would have done a $watch
on the variable. What is the best way to handle this?
please try using this method. Hope this helps
There's an example in the guide:
https://angular.io/guide/component-interaction#intercept-input-property-changes-with-ngonchanges
Use the
ngOnChanges()
lifecycle method in your component.Here are the Docs.
I was getting errors in the console as well as the compiler and IDE when using the
SimpleChanges
type in the function signature. To prevent the errors, use theany
keyword in the signature instead.EDIT:
As Jon pointed out below, you can use the
SimpleChanges
signature when using bracket notation rather than dot notation.You can also , have an observable which triggers on changes in the parent component(CategoryComponent) and do what you want to do in the subscribtion in the child component. ( videoListComponent)
The safest bet is to go with a shared service instead of a
@Input
parameter. Also,@Input
parameter does not detect changes in complex nested object type.A simple example service is as follows:
You can use a similar implementation in other components and all your compoments will share the same shared values.