简体   繁体   中英

Angular 6: ExpressionChangedAfterItHasBeenCheckedError triggered from select drop-down event

What code changes can remedy the Error described below ?

Use-case

A drop-down input UI is protected from unintended selected value change via a modal. However, the event (click, focus or other), wired to the drop-down causes the ExpressionChangedAfterItHasBeenCheckedError, observed in Chrome console in dev mode.

Observed result

When drop-down is clicked, an ExpressionChangedAfterItHasBeenCheckedError is thrown (see console)

Expected result

When drop-down is clicked, a Modal opens without error

Demo

A link to demo in stackblitz

Notes

  • As described in "Everything you need to know about ExpressionChangedAfterItHasBeenCheckedError" here , I attempt to trigger change detection (see comments inside app.component.ts:48-49, marked as STEP-1 and STEP-2), but unsuccessfully (probably triggered not in the right place?)
  • The modal in the demo is not fully implemented for [OK] and [CANCEL] as it doesn't affect the Error
  • The code is simplified version of a larger app

What code changes can remedy the Error described below ?

The code like this should help you:

<select 
  [(ngModel)]="building.venueId"
  #ngModel="ngModel"
  ^^^^^^^^^^^^^^^^^^
  get hold of NgModel instance
  ...
  (click)="ngModel.control.markAsTouched(); confirmChangeItem(building.venueId)">
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
           and prepare FormControl to the changes

Forked Stackblitz

Update

I forgot to say that you can remove cdRef.detectChanges and microtask in this case so i'm glad to know you guessed it yourself

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