Angular 切换时如何避免ExpressionChangedTerithasBeenCheckedError

Angular 切换时如何避免ExpressionChangedTerithasBeenCheckedError,angular,Angular,在Angular 4项目中,我希望根据切换按钮的值显示我的2个表中的一个,如果为false,我显示第一个表,如果为true,我显示第二个表 我在一个div中使用priming datatable,如下所示: <div *ngIf="checked"> <p-dataTable [value]="models" [rows]="10"[paginator]="true".... </div> 当打开启动对话框时,我得到了这个expressionChangedT

在Angular 4项目中,我希望根据切换按钮的值显示我的2个表中的一个,如果为false,我显示第一个表,如果为true,我显示第二个表

我在一个div中使用priming datatable,如下所示:

<div *ngIf="checked">
  <p-dataTable [value]="models" [rows]="10"[paginator]="true"....
</div>


当打开启动对话框时,我得到了这个
expressionChangedTerithasBeenCheckedError
,特别是当下拉菜单或单选按钮是第一个抓住焦点的组件时。从这里的这个线程:

…它看起来像是一个启动错误,而不仅仅是人们使用启动错误

我找到了一个我并不热衷的解决办法,但现在看来它能帮我完成工作:

// Patches for PrimeNG focus bugs.
import { Dropdown, RadioButton } from 'primeng/primeng';

const originalDropdownOnInputFocus = Dropdown.prototype.onInputFocus;
Dropdown.prototype.onInputFocus = function(event: any): void {
  setTimeout(() => {
    originalDropdownOnInputFocus.call(this, event);
  });
};

const originalRadioButtonOnFocus = RadioButton.prototype.onFocus;
RadioButton.prototype.onFocus = function(event: any): void {
  setTimeout(() => {
    originalRadioButtonOnFocus.call(this, event);
  });
};
这并不是一个彻底的修复,它只是修复了我在自己的应用程序中遇到的具体问题,重点是一个p-dropdown和一个p-radioButton。希望可以遵循此模式来修复其他bug


当然,我会急切地等待一个真正的解决方案,以便我可以删除此解决方案。

我使用以下解决方案来避免类似问题。我在构造函数中添加了对
ChangeDetectorRef
服务的引用,并将其
detectChanges()
方法作为组件构造函数中的最后一个延迟调用:

import { ChangeDetectorRef } from '@angular/core';
....
constructor(....,
    private cdr: ChangeDetectorRef) {
    ....
    setInterval(() => {
      this.cdr.detectChanges();
    }, 1000);
  }
这已经奏效了几次。如果错误没有出现,您可能必须调试代码并找到错误发生的位置,然后调用detect changes方法。例如,如果您知道错误发生在
yourMethod()
中的某个特定位置,那么您可能需要修改该方法,如下所示:

yourMethod(param):returnType {
    ....
    //spot at which the error occurs
    setInterval(() => {
      this.cdr.detectChanges();
     }, 10);
    ....
}

我看不出这个代码有什么错误。是否有关于导致错误的代码的更多信息?能否使用组件类更新您的问题?@llqadude updated请删除重现问题不需要的代码。问题不在您的模板中,在您的组件中,我在我的代码中解决了这个问题,在我准备将数据设置到我的模板时添加了一个小超时
setTimeout(()=>{/**my code*/},300)
import { ChangeDetectorRef } from '@angular/core';
....
constructor(....,
    private cdr: ChangeDetectorRef) {
    ....
    setInterval(() => {
      this.cdr.detectChanges();
    }, 1000);
  }
yourMethod(param):returnType {
    ....
    //spot at which the error occurs
    setInterval(() => {
      this.cdr.detectChanges();
     }, 10);
    ....
}