简体   繁体   中英

Uncaught Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked

Uncaught Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngIf: false'. Current value: 'ngIf:

I have been trying to get updated value on clicking button after going to several sub pages with in the same component, YES and NO value does not update(Only on the current page it works), though I can see it through console log in my method. Below is my code. and I tried below URL

ngIf - Expression has changed after it was checked

  constructor(
  ) {

  }
 getAssessBtn1(value: any) {    
    this.assesseeValidation = false;
    if (value == 'Yes') {
      this.showAssessBtn1 = true;
      this.showAssessCondition1 = false;
    } else {
      this.showAssessBtn1 = false;
    }
  } 

I was trying with ngAfterViewChecked, how can I use the method getAssessBtn1(value: any) inside it.

HTML :

<button data-auto-id="AdultTravellersAssess" *ngIf="showAssessBtn1 
                          class="btn btn-secondary assess-btn custom-theme-group-two"
                          (click)="test()">
                    Access
              

You can use ChangeDetectionRef for triggering change detection event right after changing the showAssessBtn or showAssesCondition1 .

// inject the changeDetectionRef into your component with
constructor(private cd: ChangeDetectionRef) {}


// in the getAssessBtn1 method trigger change detection
getAssessBtn1(value: any) {
 this.assesseeValidation = false;
 if (value == 'Yes') {
   this.showAssessBtn1 = true;
   this.showAssessCondition1 = false;
 } else {
   this.showAssessBtn1 = false;
 }
 this.cd.detectChanges();
}

With this approach, angular will not complain about expression changed after value is checked. Because you are re-triggering the change detection event when you set your expression to another value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM