Angular Modal not always showing properly

Viewed 509

We implemented a custom error-handling in our Angular 4 app, which overrides the default ErrorHandler and shows a modal with the error:

@Injectable()
export class GlobalErrorCatcherService implements ErrorHandler {
  constructor(private errorDispatcherService: ErrorDispatcherService) { }

  public handleError(error: Error) {
    this.errorDispatcherService.dispatchError(error);
  }
}

Skipping some steps, we then have a ErrorDisplayService, which gets the informations about the error and shows a NgbModal, which is a Component from the @ng-bootstrap framework:

@Injectable()
export class ErrorDisplayService {
  constructor(private modalService: NgbModal) {
  }

  public showError(errorInformation: ErrorInformation): void {
    const options = <NgbModalOptions>{
      backdrop: 'static',
      keyboard: true
    };

    const modalRef = this.modalService.open(ErrorDisplayContentComponent, options);
    const componentInstance = <ErrorDisplayContentComponent>modalRef.componentInstance;
    componentInstance.initialize(errorInformation);
  }
}

Unfortunately, this works only half of the time: The expected result is sometimes correct, for example:

enter image description here

But more often than not, what we get is something like that: enter image description here

All my tinkering didn't work so far and I couldn't pin down the problem. Are there further possibilities around I could try to make this work?

1 Answers

I decided to implement error handler in similar way and faced with the same problem. By using debugger, I found out that handleError() function is invoked by angular outside of Zone, so I assumed this could be a cause that NgbModalWindow is not rendered correctly.

My solution was to open modal inside angular zone. And that helped.

Try this:

  1. Inject into your ErrorHandler implementation NgZone. (private zone: NgZone into constructor) or with injector.
  2. Wrap your this.errorDispatcherService.dispatchError(error); into zone.run(() => this.errorDispatcherService.dispatchError(error));
Related