本文翻译自:How to detect when an @Input() value changes in Angular?
I have a parent component ( CategoryComponent ), a child component ( videoListComponent ) and an ApiService. 我有一个父组件( CategoryComponent ),一个子组件( videoListComponent )和一个ApiService。
I have most of this working fine ie each component can access the json api and get its relevant data via observables. 我有大部分工作正常,即每个组件可以访问json api并通过observable获取其相关数据。
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()
. 目前视频列表组件只获取所有视频,我想将其过滤为特定类别中的视频,我通过@Input()
将categoryId传递给子项来实现这一点。
CategoryComponent.html 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). 这有效,当父CategoryComponent类改变时,categoryId值通过@Input()
传递,但我需要在VideoListComponent中检测到这一点,并通过APIService(使用新的categoryId)重新请求视频数组。
In AngularJS I would have done a $watch
on the variable. 在AngularJS中,我会对变量进行$watch
。 What is the best way to handle this? 处理这个问题的最佳方法是什么?
#1楼
参考:https://stackoom.com/question/2bqI0/如何检测Angular中-Input-值何时发生变化
#2楼
Use the ngOnChanges()
lifecycle method in your compo