如何检测Angular中@Input()值何时发生变化?

本文翻译自: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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值