Angular 8 到 11 有什么变化导致 Child 到 Parent 通信抛出 ExpressionChangedAfterItHasBeenCheckedError

Did something change with Angular 8 to 11 to cause Child to Parent communication to throw ExpressionChangedAfterItHasBeenCheckedError

我想我应该学习我的技术,所以我正在添加到我的 Angular 11.x 应用程序。

出现这个错误(我确实在 Whosebug 上看到了其他问题和关于它的博客,但这些问题似乎是更复杂的事情)。

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'. Current value: 'Hello from the Child'.

Parent HTML :

 <app-child></app-child>
 Message from child : {{ ParentGettingChildMessage }}

Parent 组件代码:

import { Component, ViewChild, AfterViewInit} from '@angular/core';
import { ChildComponent } from 'src/app/child/child.component';
@Component({.... })

export class ParentComponent implements AfterViewInit {

   @ViewChild(ChildComponent) child;

   ParentGettingChildMessage: string;

   constructor() { }

   ngAfterViewInit(){
      this.ParentGettingChildMessage = this.child.message;
   }

}

Child 分量:

export classs ChildComponent implements OnInit {
    message = "Hello from the Child";
 .....
}
 

我找到它的博客似乎是用 Angular 8 in 2020 写的 - 从 Child 到 Parent 似乎是合理的通信方式供参考 > www 。 thirdrocktechkno。 com/blog/how-angular-components-communicate/

为什么会出现此错误?

有一个简单的解决方法。这仅在 angular 处于开发模式时发生。它通常在 angular 检查传递给子组件的值已更改时显示此错误。 This是一篇详尽的文章,深入讲述了它是如何发生的,你应该看看它。

ngAfterViewInit(){
     setTimeout(() => {
       this.ParentGettingChildMessage = this.child.message;
     })
      
   }