angular - 在检测到 2 个更改后调用函数
问题描述
这是我的代码:
@Component({
selector: 'app-team-seaon-kit',
templateUrl: './team-seaon-kit.component.html',
styleUrls: ['./team-seaon-kit.component.css']
})
export class TeamSeaonKitComponent implements OnInit {
@Input() colorKit;
@Input() seasonKitOptions;
ngOnChanges(changes: SimpleChanges){
if(changes.colorKit && changes.colorKit.currentValue !== undefined && changes.seasonKitOptions && changes.seasonKitOptions.currentValue !== undefined){
this.updateCheckedSeasonKitRadioButton();
}
}
}
我想调用函数updateCheckedSeasonKitRadioButton()
,一旦我有了 的值colorKit
和 的值seasonKitOptions
问题是这两个值没有同时绑定到这个组件,所以我的 If 语句中的条件永远不会被验证。
这就是我将这两个值从父组件绑定到子组件的方式:
<app-team-seaon-kit [(colorKit)]="homeColorKit" [seasonKitOptions]="homeTeamJersey.seasonKitOptions" [team]="homeTeamJersey"></app-team-seaon-kit>
<app-team-seaon-kit [(colorKit)]="awayColorKit" [seasonKitOptions]="awayTeamJersey.seasonKitOptions" [team]="awayTeamJersey"></app-team-seaon-kit>
我想实现这项工作的一种方法是将两个变量绑定到一个对象中,如下所示:
<app-team-seaon-kit [(colorKit)]="'colorKit':awayColorKit,'seasonKit':awayTeamJersey.seasonKitOptions" [team]="awayTeamJersey"></app-team-seaon-kit>
但这不是我的目标。
解决方案
为什么不检查更改检测时这两个值是否存在?
ngOnChanges(changes: SimpleChanges){
if(this.colorKit && this.seasonKitOptions) {
this.updateCheckedSeasonKitRadioButton();
}
}
考虑到您的用例,您必须直接检查输入变量,而不是依赖于ngOnChanges
参数changes
,因为它会自行返回每个更改。
推荐阅读
- excel - 如何用密码汇总文件夹中的excel文件
- python - 如何转换张量流模型并加载为 tfds
- java - 在登录测试中未在 SecurityContext 中找到 Authentication 对象
- java - 将数组的特定元素从一个数组移动到另一个不同大小的数组
- javascript - 如何使用 javascript 在 DOM 中添加 laravel 组件
- flutter - 如何在应用程序中显示数据列表?
- node.js - 如何在获取模块获取流中捕获无效的 url 错误?
- unity3d - ArgumentException:无法创建没有有效负载数据的数据处理程序
- c++ - C++ 不能使用带有类成员的模板模板类
- python - 我的麦克风不适用于谷歌识别器