Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExpressionChangedAfterItHasBeenCheckedError undefined input parameter

Tags:

angular

Going round in circles on how to fix this. Read the two blogs highlighted everywhere. Understand the reason but doesn't matter what i try, this error will not go away. The error is with the input parameter. When the component loads, it's undefined and then gets the correct value.

I've tried using:

  • various lifecycle hooks in the sub component with no luck - ngOnit,
  • ngAfterViewChecked, ngAfterViewInit etc.
  • Tried using a timer
  • Tried using ChangeDetectorRef in the sub component
  • Tried using *ngIf="ComponentName"
  • EventEmitter to true to allow async

I still get the error. Can someone please see what i am doing wrong please.

Error Message

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 ?

Parent Component ts file.

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

  constructor() {}

  public displayMethod(): void {}

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

Parent Component Html

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

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

SubComponent 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);
      });
    }
  }
like image 240
Snipered Avatar asked Sep 19 '26 17:09

Snipered


1 Answers

try this :

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;
  }
}

Not the best solution imho, as described here https://blog.angularindepth.com/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error-e3fd9ce7dbb4#c2ba, but it should work.

like image 148
Bernard Pagoaga Avatar answered Sep 22 '26 07:09

Bernard Pagoaga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!