首页 > 解决方案 > 在检测到 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>

但这不是我的目标。

标签: angular

解决方案


为什么不检查更改检测时这两个值是否存在?

  ngOnChanges(changes: SimpleChanges){
    if(this.colorKit && this.seasonKitOptions) {
      this.updateCheckedSeasonKitRadioButton();
    }
  }

考虑到您的用例,您必须直接检查输入变量,而不是依赖于ngOnChanges参数changes,因为它会自行返回每个更改。


推荐阅读