Angular4/ngrx - ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked

Angular4/ngrx - ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked

在我的 angular 代码中,管理页面列出了 data-table 组件中的项目,单击其中一个数据项目后,admin-right 组件将打开并显示与单击的项目。

点击后出现此错误:

ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'false'. Current value: 'true'.
    at viewDebugError (core.es5.js:8434)
    at expressionChangedAfterItHasBeenCheckedError (core.es5.js:8412)
    at checkBindingNoChanges (core.es5.js:8576)
    at checkNoChangesNodeInline (core.es5.js:12448)
    at checkNoChangesNode (core.es5.js:12422)
    at debugCheckNoChangesNode (core.es5.js:13202)
    at debugCheckDirectivesFn (core.es5.js:13104)
    at Object.eval [as updateDirectives] (AdminComponent.html:21)
    at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:13086)
    at checkNoChangesView (core.es5.js:12242)

我在创建具有管理员权限的子组件后开始出现错误


admin.component.html:

<data-table [table]='table' [data]="data" (onSelect)="onItemSelect($event)"></data-table>

<admin-right *ngIf="showRight"
[item]="item"
[rightContent]="rightContent"></admin-right>

数据-table.component.ts:

@Component({
 ...
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class DataTableComponent implements OnInit {

  constructor(
    private cdRef:ChangeDetectorRef
  ) { } 
  ngOnInit() {
    this.cdRef.detectChanges();
  }

right.component.ts:

@Component({
 ....
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class RightComponent implements OnInit {

  @Input()  item;
  @Input()  rightContent;

  constructor( private cdRef:ChangeDetectorRef) { }

  ngOnInit() {
    this.cdRef.detectChanges();
  }

此错误是由于在 Angular 的生命周期中检查了一个变量,并且您试图在生命周期结束后更改它。

这种情况很常见,通常在生产模式下不会重现该错误。

如果您想更正它,要么不更改变量的值,要么使用超时来处理点击 setTimeout(() => {/* what you do after the user clicked here */})