ExpressionChangedAfterItHasBeenCheckedError PrimeNG两个绑定到同一属性的单选按钮

时间:2019-10-03 13:44:05

标签: angular7 primeng

TLDR :将两个单选按钮绑定到相同的基础属性会导致无效行为和错误“ ExpressionChangedAfterItHasBeenCheckedError”

环境:Angular 7.3.8,PrimeNg 7.1.3

StackBlitz中的示例: https://stackblitz.com/edit/angular-primeng-playground-t7nmfx

最终,我了解这里发生了什么。单选按钮的两个实例相互干扰,试图设置初始状态,并且在设置一个或另一个实例时也相互干扰。但我看不出如何摆脱这一困境。显然,这是一个超级简化的示例,并且向我提供了屏幕布局,因此我无法将收音机移到选项卡之外。我真的需要他们两个。另外,我不确定这是否与PrimeNG相关。

HTML:

<p-tabView>
  <p-tabPanel header="today">
    <div>
      Temperature: {{tempToday}}
    </div>
    <div>
      Show in: 
      <p-radioButton name="groupname" [value]="1" [(ngModel)]="isCelcius"></p-radioButton> C
      <p-radioButton name="groupname" [value]="0" [(ngModel)]="isCelcius"></p-radioButton> F
    </div>
  </p-tabPanel>
  <p-tabPanel header="tomorrow">
    <div>
      Temperature: {{tempTomorrow}}
    </div>
    <div>
      Show in: 
      <p-radioButton name="groupname" [value]="1" [(ngModel)]="isCelcius"></p-radioButton> C
      <p-radioButton name="groupname" [value]="0" [(ngModel)]="isCelcius"></p-radioButton> F
    </div>
  </p-tabPanel>
</p-tabView>

组件:

  ngOnInit() {
    this.isCelcius = false;
    this.tempToday = 78;
    this.tempTodayInF = 78;
    this.tempTodayInC = 20;
    this.tempTomorrow = 80;
    this.tempTomorrowInF = 80;
    this.tempTomorrowInC = 21;
  }

public get isCelcius(): boolean {
  return this._isCelcius;
}

public set isCelcius(value: boolean ) {
  this._isCelcius = value;
  if(this._isCelcius) {
    this.tempTomorrow = this.tempTomorrowInC;
    this.tempToday = this.tempTomorrowInC;
  } else {
    this.tempTomorrow = this.tempTomorrowInF;
    this.tempToday = this.tempTodayInF;
  }
}

  private _isCelcius: boolean;
  public tempToday: number;
  public tempTomorrow: number;

  private tempTodayInF: number;
  private tempTodayInC: number;
  private tempTomorrowInF: number;
  private tempTomorrowInC: number;

1 个答案:

答案 0 :(得分:0)

如果有人遇到相同的问题,我将把它留在这里。

问题似乎并非如此。造成此问题的原因是单选按钮组名称重复。在两个选项卡中的任何一个中更改组名都可以解决此问题。

      <p-radioButton name="groupname1" [value]="1" [(ngModel)]="isCelcius"></p-radioButton> C
      <p-radioButton name="groupname1" [value]="0" [(ngModel)]="isCelcius"></p-radioButton> F