Methods to close the currently active ngx-modal when a new modal is triggered within the same Angular 8 component

I am currently working on developing a versatile modal component that has the ability to be called from within the same modal itself.

Is there any way to configure the component and modal in such a manner that when the reusable component is triggered, it automatically closes any previous instances?

You can find my project on Stackblitz through the following link:

https://stackblitz.com/edit/angular-nested-component-modal-ngx-bootstrap-n

Answer №1

I suggest implementing a single modal...

Let me provide you with the step-by-step approach

  1. Add the modal to the main application component
  2. Create a service that will handle communication when the user wants to open a new modal
  3. From each button in different components, call the service to trigger the modal

Now, we can start by defining our Service

my.service.ts

import { Injectable } from "@angular/core";
import { BehaviorSubject, Subject } from "rxjs";

interface IModalParams {
  component: any;
  config?: any;
  title?: any;
}
@Injectable()
export class MyService {
  private isModalOpen$ = new BehaviorSubject(false);
  private component;
  private config;
  private title;

  public showModal({ component, config, title }: IModalParams) {
    this.component = component;
    this.config = config;
    this.title = title;
    this.isModalOpen$.next(true);
  }
}

In the above code snippet, we define a method called showModal which takes in parameters for the component, configuration, and title of the modal.

We also have a BehaviorSubject named isModalOpen$, which allows subscribing properties to be notified whenever a user opens a new modal.

app.component.ts

  ngOnInit() {
    this.myService.isModalOpen$.pipe(
      tap(() => this.modalRef?.hide()),
      filter(isOpen => isOpen)
    ).subscribe({
      next: () => {
        const {component, config, title} = this.myService
          this.modalRef = this.modalService.show(component, config);
          if(title) {
            this.modalRef.content.title = title; 
          }
      }
    })
  }

In the above code snippet, we subscribe to isModalOpen$ and handle the opening or closing of the modal component.

any-other.component.ts

 this.myService.showModal({
     component: ModalContentComponent,
     config: {
      ignoreBackdropClick: false
    },
    title: "Modal with component"
   })
  }

In other components, you can utilize the showModal method as demonstrated in the example above.

Check out a demo here

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

What is the best way to verify that I am receiving the 'jwt' token in my code?

Trying to understand the data held by the jwt token in my next.js app, but encountering an error message saying error: jwt must be provided. Here's the code snippet causing the issue: import { NextRequest } from "next/server" ...

Is there a way to easily toggle a Material Checkbox in Angular with just one click?

Issue with Checkbox Functionality: In a Material Dialog Component, I have implemented several Material Checkboxes to serve as column filters for a table: <h1 mat-dialog-title>Filter</h1> <div mat-dialog-content> <ng-container *ng ...

The Vue CLI project, using Typescript, is facing challenges with building and running Mocha tests

My Vue 2 project, created using Vue CLi, is encountering numerous errors. While it compiles fine for development purposes, running unit tests or building for production results in a cascade of issues. Displayed below are some sample errors, along with sni ...

Sharing an application variable across all components in Angular - Tips and Tricks

I am currently working on a project using Angular7 for the frontend and Flask for the backend. My goal is to subscribe to a service, retrieve the data it returns, save it as an object type variable within my main AppComponent, and then access this variable ...

When you click, you will be directed to the specific details of the object

I have a recipe component that displays a list of recipes from my database and a recipe-detail component that should show the details of a selected recipe. What I aim to achieve is that when someone clicks on a recipe name, they are routed to the recipe-de ...

Is Angular2 the Perfect Fit for Custom HTML Webresources in Dynamics CRM 2016?

Has anyone experimented with integrating Angular2 for custom webresource development in Dynamics CRM 2016? I searched for resources but only came across tutorials on using AngularJS, such as this one ...

The method to permit a single special character to appear multiple times in a regular expression

I am currently working on developing a REGEX pattern that specifically allows alphanumeric characters along with one special character that can be repeated multiple times. The permitted special characters include ()-_,.$. For instance: abc_def is conside ...

The Angular ng serve command seems to be malfunctioning

Whenever I try to run ng serve, I keep getting this error: module.js:540 throw err; ^ Error: Cannot find module '@angular-devkit/core' at Function.Module._resolveFilename (module.js:538:15) at Function.Module._load (module.js:46 ...

Obtain a value that is not defined

Good day, I am encountering an issue with my data not accepting an undefined value. Below is the code snippet: interface IModalContatos { dados: IContatos; onSave(dados: IContatos): void; onClose(): void; } When passing this data to my modal, I rece ...

What is the best way to retrieve the value from a Material UI textfield after hitting the enter key

Having trouble retrieving input values with the provided code. Attempted using onKeyUp, onKeyDown, and onKeyPress, but none of them returned the value as desired. Typically, I would use the onChange property to get the value, but it triggers for every ne ...

Leveraging Window Object in Custom Hooks with NextJS

ReferenceError: window is not defined This issue arises on the server side when NextJS attempts to render the page. However, it is possible to utilize window within the useEffect hook by following the guidance provided here. I am seeking advice on creati ...

Validation of email forms in Angular 5

I have encountered a challenge that I need help with: Using Angular 5 - template driven form In my template, there is an input field with the type email. Here's an example: <input type="email" [(ngModel)]="model.email" #email="ngModel" email /> ...

Efficiently configuring Angular 2 with ng-bootstrap

Hi there, I am currently diving into the world of Angular and Bootstrap, while also exploring node js. My goal is to create a solid foundation using the webpack starter kit available at this link: https://github.com/AngularClass/angular2-webpack-starter ...

Steps for initiating an Angular 4 project

While most developers have moved on to Angular 5, I was tasked with creating a project using Angular 4. After conducting research for several days, I discovered that downgrading the Angular CLI would allow me to accomplish this. By following this approach, ...

Leverage elements from nearby npm repository when building an Angular 2 application

After developing a generic chart component using d3 and Angular 2, I decided to share it by publishing it in a local npm repository. This way, anyone can easily incorporate the chart component into their Angular project by simply running the npm install my ...

Utilizing the power of dojo/text! directly within a TypeScript class

I have encountered examples suggesting the possibility of achieving this, but my attempts have been unsuccessful. Working with Typescript 2.7.2 in our project where numerous extensions of dijit._Widget and dijit._TemplatedMixin are written in JavaScript, w ...

When using TypeORM's findOneBy method, if the search result

In order for the entity to have both identifiers, I require it to possess the Id and the _id export class ScriptSequencesExecutionEntity { @PrimaryGeneratedColumn({ name: 'id' }) _id!: string; @ObjectIdColumn() id: number; @AutoMap() ...

What is the best way to iterate over an Angular HTTP Response?

As a newcomer to Angular, I am working on mastering the process of uploading files and calling an API for validation. The API responds with a list of JSON validation errors based on specific file values. I am currently struggling to iterate through these ...

Can Observable subscriptions in Angular be tested?

I'm a newcomer to angular and I'm currently working on creating unit tests for the function below. HomeComponent.ts ngOnInit() { this.msalBroadcastService.inProgress$ .pipe( filter((status: InteractionStatus) => status === ...

NPM packages: Providing a comprehensive assets and images delivery solution package

After creating a custom (angular2) npm package and uploading it to my personal registry, I encountered an issue with delivering the icons along with the component. The component should display an icon by using the following template: <span [class]="& ...