ng-bootstrap ModalService and the Expression Changed After It Has Been Checked Error

Abou Kone
Code d'Ivoire
Published in
2 min readApr 26, 2018

--

If you use the ng-bootstrap library and its modal service, in the specific scenario of within a form, you might run into an error similar to :

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ng-untouched: true'. Current value: 'ng-untouched: false'.
at viewDebugError (core.js:9775)
at expressionChangedAfterItHasBeenCheckedError (core.js:9753)
at checkBindingNoChanges (core.js:9920)
at checkNoChangesNodeInline (core.js:13968)
at checkNoChangesNode (core.js:13942)
at debugCheckNoChangesNode (core.js:14771)
at debugCheckRenderNodeFn (core.js:14711)
at Object.eval [as updateRenderer] (service-configuration-form.component.html:1)
at Object.debugUpdateRenderer [as updateRender

My specific error was related to displaying a confirmation modal after toggling a checkbox. I added a click handler function in my component that calls event.preventDefault() before using modal.open(). I Initially though the error was related to missing change detection within my form since I was manually handling the change of value for the checkbox but that did not turn out to be the issue. As it turns out as explained here, the issue in my particular case is related to two issues:

  • The Angular form directives have bindings that update synchronously based on focus change
  • The modal brings focus to the window (required by accessibility)

The fix requires in my particular case was to trigger the blur event on the checkbox input manually before stopping the event propagation as in:

// HTML
<input type="checkbox" formControlName="active" (click)="onClick($event)">
// ComponentonClick(event){ event.srcElement.blur();
event.preventDefault();
this.modal.open(this.modalOptions);
...
}

Some other cases required calling your modal from within a setTimeout but that did not turn out to be the case for me.

I am CTO at AKIL Technologies, an Abidjan, Ivory Coast tech startup where I lead a team of Angular and React devs ready to contribute on interesting projects. Give us a toot if you need to beef up your front end teams!

--

--

Abou Kone
Code d'Ivoire

Chief Mercenary @akiltechnologies. @codedivoire founder. African Tech is on my mind.