Angular 检测到2个更改后调用函数
这是我的代码:Angular 检测到2个更改后调用函数,angular,Angular,这是我的代码: @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() seas
@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
的值和seaseKitOptions
问题是这两个值没有同时绑定到此组件,因此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
,因为它会自行返回每个更改