In Angular, when a modal called from a service is displayed, it appears as page content instead of a modal

I'm developing a universal error handling system to display a Bootstrap modal dialog with error details. This is my current configuration:

https://i.sstatic.net/LSBeu.png

The error modal component contains an open() method, and its template includes a button (for debugging) that triggers the open() function successfully. The modal displays correctly with the assigned text.

ErrorModalComponent code:

import { Component, ViewChild, TemplateRef } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';

import { GlobalErrorHandler } from './global-error-handler.service';

@Component({
  selector: 'app-error-modal',
  templateUrl: './error-modal.component.html',
  styles: []
})
export class ErrorModalComponent {

  private _message: string;

  @ViewChild('content') _modalTemplate: TemplateRef<any>;

  constructor(private _modalService: NgbModal, private _globalErrorHandler: GlobalErrorHandler) {
    this._globalErrorHandler.errorEventSource$.subscribe(errorMessage => {
      this._message = errorMessage.toString();
      this.open();
    });
  }

  open() {
    this._modalService.open(this._modalTemplate);
    this._message = "A change test";
  }

  public get message(): string {
    return this._message;
  }
}

ErrorModalComponent html:

<button class="btn btn-info" (click)="open()">Show Modal</button>
<ng-template #content let-c="close" let-d="dismiss">
  <div class="modal-content">
    <div class="modal-header">
      <h4 class="modal-title">It's not you, it's me: unhandled error</h4>
      <button type="button" class="close" aria-label="Close" (click)="d('Cross click')" data-dismiss="modal">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
    <div class="modal-body">
      <p>We are sorry but something has slipped by and we have an uncontrolled error.</p>
      <p>A notification has been sent to us and we will process it soon.</p>
      <p>{{message}}</p>
    </div>
    <div class="modal-footer">
      <div class="col-4">
        <button type="button" class="btn btn-danger btn-block" (click)="c('Close click')" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</ng-template>

GlobalErrorHandler code:

import { ErrorHandler,  Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {

  private errorEventSource = new Subject<string>();
  errorEventSource$ = this.errorEventSource.asObservable();

  handleError(error: any) {
    this.errorEventSource.next(error);
  }
 }

When I intentionally create an exception in the code, the event is triggered, the open method is called, but the modal does not display correctly and the connected text is missing. It shows up at the bottom of the page as disabled, making it impossible to interact with anything.

I am puzzled by this inconsistency when calling the same method from different locations. Any suggestions?

This is how the modal appears after clicking the button:

https://i.sstatic.net/dnMhp.png

And this is the appearance of the modal after triggering an exception:

https://i.sstatic.net/7CGrW.png

Answer №1

I encountered a similar issue, but my situation had a few differences in the setup. I was facing issues with a globalErrorHandler containing an "handleError" function, which seemed to be executing outside of the Angular zone.

To resolve this, I made use of the ngbModal within zone.runGuarded.

this.zone.runGuarded(() => {
        this.modalService = this.injector.get(NgbModal);
        const modalRef = this.modalService.open(ErrorComponent);
        modalRef.componentInstance.errorMessage = error.message;
        modalRef.componentInstance.stack = error.stack;
    });

It's important to ensure that you inject NgZone in the constructor:

private zone: NgZone

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues with Vercel's JavaScript Environment Variables Accessibility

I am encountering an issue trying to access environment variables on Vercel using JavaScript (TypeScript). Despite setting them under /settings/environment-variables, I receive undefined when attempting to access them with process.env.TURSO_DATABASE_URL du ...

Tips for accessing a URL page in Ionic 3 without using the ionic-native plugin

Is there a method to open a specific page when a particular URL is accessed by the browser, without relying on ionic-native for deep linking? This functionality would be beneficial both for the app itself and for development purposes. For instance, can h ...

I'm attempting to align the card in the center, but it's not cooperating

I am currently developing a React application where I am attempting to align the blocks in the center using justify content center, but unfortunately it is not functioning as expected. I have tried using justify-content-center and center-block classes, but ...

Error encountered in WebGrease.dll following the upgrade to Bootstrap 5 for MVC

Recently, I encountered an issue where updating to Bootstrap v5.0.2 caused a NullReferenceException in WebGrease.dll, while previous versions (v3 and v4) worked without any problems. Here is the code snippet from the shared layout: @Scripts.Render("~ ...

Generating JavaScript files automatically upon initiating the npm start command

As I develop an Angular2 app with typescript, I encounter a situation where running npm start results in all .ts files being compiled into javascript files and saved in the directory. Is there a way to disable this automatic compilation? The contents of m ...

Challenges with Loading JSON Dynamically in Next.js using an NPM Package

In my TypeScript project, I have implemented a functionality where a json configuration file is dynamically loaded based on an enum value passed as a parameter to the getInstance function in my PlatformConfigurationFactory file. public static async getIn ...

I encountered an error while attempting to create an npm package from a forked repository on GitHub

Check out this GitHub repository: https://github.com/jasonhodges/ngx-gist Upon running the package command, I encounter an error: rimraf dist && tsc -p tsconfig-esm.json && rollup -c rollup.config.js dist/ngx-gist.module.js > dist/ngx- ...

In a localhost environment, the function canMakePayment() consistently returns a null value

I'm having trouble displaying the 'Pay' Button as paymentRequest.canMakePayment() always returns null. I am running this code on my LOCALHOST in Chrome (version 73.0.3683.75) and have already saved the card details in Chrome. import { Compo ...

Transforming JavaScript into TypeScript - school project

After researching similar questions and answers, it appears that any valid JavaScript code can also be considered TypeScript? If this is true: const express = require('express'); const bodyParser = require('body-parser'); const ...

Linking arrays through a foreign identifier in Angular TypeScript

I have a collection of JSON objects stored in the InMemoryDataService (mock server) and services.ts file. These objects contain various elements that I want to display on an HTML page by replacing productId and shopId with product.name and shop.name resp ...

Synchronizing Events across Two JavaScript Applications

In my game app (using Electron) and web app (testing on Android Chrome), they communicate through a websocket server to coordinate a countdown. I've noticed that in environments with low latency, the synchronization is fine. However, when there is mor ...

Transmit information to firebase using HttpClient

Seeking assistance on updating Firebase data (Realtime Database) in a specific table without overwriting it. The current code I have is causing the table [TB_MyProfile_Composite] to be overwritten instead of updated. Here is the code snippet for updating ...

Tips for determining if a class has been declared in Typescript

When it comes to checking if a class (or any other element) exists in the global scope, Javascript offers a convenient method: typeof SomeUndeclaredOne === 'undefined' However, this approach doesn't translate well into TypeScript as it trig ...

A guide on harnessing the power of Jest when integrating it with vuex-module-decor

In my Typescript-written Vue component, I am facing an issue while trying to write a unit test using vue-test-utils and jest. The problem arises when injecting the vuex store that was created with vuex-module-decorators. Below is a snippet from my Vue com ...

An issue has occurred: function() is not a valid function

Issue: core.mjs:10132 ERROR TypeError: block.getDepartment is not a function at FirebaseService.mapDatabaseToBlock (firebase.service.ts:54:30) at firebase.service.ts:45:60 at Array.map (<anonymous>) at firebase.service.ts:45:42 at ...

custom form control component combined with an issue

Trying to develop a custom MatFormFieldControl with ControlValueAccessor implementation. Starting off with a familiar scenario: password form. The objective is to design a form field that takes a single string input, but contains its own internal form fo ...

When a React component written in TypeScript attempts to access its state, the object becomes

Throughout my app, I've been consistently using a basic color class: const Color = { [...] cardBackground: '#f8f8f8', sidebarBackground: '#eeeeee', viewportBackground: '#D8D8D8', [...] } export defau ...

I am looking for a way to save a webpage as .html/.png format after entering text in the text box. Here is the code I have

Is it possible to download a webpage as .html/.png after inputting text in the text box? Here is my code: <div class="container"> <form> <div class="form-group"> <label for="link">Paste Website Link Below</label> ...

Integrate guidelines into JSON stringify

I am working with a class called OrderParameterInfo: class OrderParameterInfo { Name: string; Value: string; My goal is to create a JSON string. When I use JSON.stringify(OrderParameterInfo("foo_name", "foo_value")), it generates {&quo ...

Import a JSON file into Angular 8 and parse its contents

My code is intended to read and upload a JSON file (ARM template), but I am encountering an issue where this.updateObj appears as undefined in the console.log. Below is my code: onChange(fileList: FileList): void { var file = fileList[0]; var fileR ...