4

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
zaggi
  • 870
  • 1
  • 7
  • 24
  • 1
    I see two things about the `select` element that you may want to change. (1) You use `ngModel` and `[selected]`, use only `ngModel`. (2) Instead of processing the `(click)` event of the dropdown, I suggest using one-way binding with `[ngModel]` and handling `(ngModelChange)="processValueChange($event)"`, where you could do some checking before confirming the change. – ConnorsFan May 11 '18 at 20:01

1 Answers1

4

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

yurzui
  • 205,937
  • 32
  • 433
  • 399
  • Neat stackblitz [link] (https://stackblitz.com/edit/zaggi-angular-expressionchangedafterithasbeencheckederror-v2-fi) with unused Change detection and micro/macrotask code removed, based on the valuable inputs from @yurzui – zaggi May 18 '18 at 17:01
  • Thank you so much! I struggled with this for hours before finding this answer! – nevada_scout Jul 31 '18 at 14:01
  • I am very curious to know why this is even necessary. I have code that doesn't update the form, and merely opens a modal, and this error occurs unless I use the markAsTouched work around. – Richard Collette Oct 08 '19 at 18:12