ExpressionChangedAfterItHasBeenCheckedError未定义输入参数

时间:2019-06-18 12:15:18

标签: angular

绕圈讨论如何解决此问题。阅读随处可见的两个博客。了解原因,但不管我尝试什么,该错误都不会消失。错误与输入参数有关。当组件加载时,它是未定义的,然后获得正确的值。

我尝试使用:

  • 子组件中的各种生命周期挂钩都没有运气-ngOnit,
  • ngAfterViewChecked,ngAfterViewInit等
  • 尝试使用计时器
  • 在子组件中尝试使用ChangeDetectorRef
  • 尝试使用* ngIf =“ ComponentName”
  • EventEmitter设为true以允许异步

我仍然收到错误消息。有人可以看看我在做什么错吗。

错误消息

Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'AreaName: undefined'. Current value: 'AreaName: dashboard'. It seems like the view has been created after its parent and its children have been dirty checked. Has it been created in a change detection hook ?

父组件ts文件。

export class Dashboard {
  public ComponentName: string = "dashboard";
  private showContent: boolean = false;

  constructor() {}

  public displayMethod(): void {}

  public CanAccess(canAccess : boolean) : boolean {
    return this.showContent = canAccess;
  }
}

父组件HTML

<div class="content-area" >
   <h3>This is dashboard information</h3> 
</div>

<no-access [AreaName]="ComponentName" (AllowedAccess)="CanAccess($event)"></no-access> 

子组件ts

export class NoAccess implements OnInit {

    @Input() AreaName: string;
    @Output() AllowedAccess = new EventEmitter<boolean>(true);
    public showSubContent: boolean;

    constructor(private authService : AuthenticationService) {}

    ngOnInit(): void {
      setTimeout(() => {
        this.showSubContent = this.authService.CanRead(this.AreaName, null);
        this.AllowedAccess.emit(false);
      });
    }
  }

1 个答案:

答案 0 :(得分:0)

尝试:

export class Dashboard {
  public ComponentName: string = "dashboard";
  private showContent: boolean = false;

  constructor(private cd: ChangeDetectorRef) {
  }

  ngAfterViewInit() {
      this.cd.detectChanges();
  }

  public displayMethod(): void {}

  public CanAccess(canAccess : boolean) : boolean {
    return this.showContent = canAccess;
  }
}

这不是https://blog.angularindepth.com/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error-e3fd9ce7dbb4#c2ba所述的最佳解决方案,但它应该可以工作。