How to create a separate modal component in Angular without relying on ng-modal

I am facing an issue with ComponentB, which contains HTML code for a Bootstrap modal. I want to open ComponentB from ComponentA.

Although the component is getting loaded when inspected, the popup modal does not appear on the UI.

<app-root>
  <app-a>
    <app-b></app-b>
  </app-a>
</app-root>

NOTE: There is no CSS applied to either of the components.

ComponentA.html:

<button (click)="popup()">Open</button>
<app-b *ngIf="openModal" [openModal]="true" ></app-b>

ComponentA.ts:

 popup(){
    this.openModal = true;
}

componentB.html:

<div *ngIf="openModal" id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Modal Header</h4>
      </div>
      <div class="modal-body">
        <p>Some text in the modal.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

componetb.ts:

@Input('openModal') openModal : boolean

Thank you for your help!

Answer №1

If you want to display a modal, remember to include the show and d-block classes.

In your componentB.html, update your modal div as follows:

<div *ngIf="openModal" id="myModal" class="modal fade show d-block" role="dialog">

Here is a sample on stackblitz

However,
It is recommended to use ngx-bootstrap or refer to the official Bootstrap documentation for proper guidance on manipulating classes in modals.

Answer №2

Transform a regular component into a modal by creating a custom component, such as ModalComponent. In the constructor, remember to include the variable:

public activeModal: NgbActiveModal

To close an open Modal, use the following command: this.activeModal.close(). Within the calling or parent component, declare two variables: a reference to the modal component modalRef: NgbModalRef, and in the constructor, add: private modalService: NgbModal. To invoke the modal component, utilize:

this.modalRef = this.modalService.open(ModalComponent);
. You can also pass any necessary variables to the Modal component like so:
this.modalRef.componentInstance.variable = variableContent;

Remember to include the Modal component in the entryComponents Array within the app.module file:

entryComponents: [ModalComponent]

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

The functionality of d3 transition is currently non-existent

I've encountered an issue with my D3 code. const hexagon = this.hexagonSVG.append('path') .attr('id', 'active') .attr('d', lineGenerator(<any>hexagonData)) .attr('stroke', 'url(#gradi ...

Redirect to a new page following a toastr notification in an Angular application

Looking for a way to automatically navigate to another page after a toastr notification disappears. showToasterWarning(){ this.notifyService.showWarning("No Data Found for this Date!", ""); } The notifyService is responsible ...

Problem with Packaging Angular and Spring Boot Applications

My current project structure consists of a spring boot angular project +--app-ui |--+--src |--+--dist |--app-backend |--+--src |--+--+--main |--+--+--+--resources |--+--+--+--+--static |--+--+--+--java The app-ui directory contains the Angular 6 code, wh ...

A guide to updating a table in Angular using an API response

My form allows me to select events from a drop-down list and choose a date. Depending on the selected date, it retrieves the number of events that occurred on that specific date. If I select an event and a date where events took place, the "All Events" sec ...

IntelliJ is unable to locate the scss import when using the includePaths option in stylePreprocessorOptions

Having trouble with IntelliJ 2019.2.2 Ultimate not detecting scss imports from stylePreprocessorOptions - includePaths Here is the directory structure: https://i.stack.imgur.com/SQEDT.png In my angular.json file, I have specified: "stylePreprocessorOpt ...

Using method parameters to pass multiple observer values

I am attempting to implement the following functionality: this.httpService.createSomething( this.userObserver.getFullName().subscribe(), this.userObserver.getPhoneNumber().subscribe(), this.userObserver.getEmailAddress().subscribe(), ).subscrib ...

Error: "the cart variable in the ctx object has not been defined"

A project I'm currently working on involves a pizza ordering app, and my current focus is on implementing the Cart feature. Each user has their own cart, which includes specific details outlined in cart.ts import { CartItem } from './cartitem&a ...

Show varying mat-options based on the selected value of another mat-select

When selecting a continent from the first mat-select, only the countries belonging to that continent should appear in the second mat-select options. For example, if Asia is chosen as the continent, only Asian countries should be displayed. <div class=&q ...

Angular: handling asynchronous errors when no promise is utilized within a subscription

I am currently working with a material design table and have created custom functions to load the data and extract objects from a JSON array object. Here is a snippet of the code I am using: public getDocumentList() { return this.http.get(this.getDocu ...

Angular 2 and Strophe XMPP Integration

I am currently looking to develop a service for the Strophe.JS XMPP library within an Angular2 project. This service will handle the opening and closing of connections, as well as include a message handler. I have successfully implemented this in a .Net MV ...

As I attempted to install TypeScript on my MacBook Pro M2, I encountered errors after entering a command. What steps should I take next to resolve this issue?

npm install typescript Encountered an error with code EEXIST Error while trying to create a directory Issue with the path /Users/ketaki_2004./.npm/_cacache/content-v2/sha512/af/ce EEXIST error number - directory already exists Failed to fetch data fro ...

In Ionic 2, any modifications made to the data model will only be reflected in the user interface after there is

Q) Why does my data seem to magically appear on the UI after interacting with it, even though I have made changes in the backend? For instance, when fetching and updating data bound to a list, such as: this._LocalStorageService.getClients().then( (data ...

Create an Angular library that incorporates a TypeScript dependency into the compilation process

Within my Angular lib, residing in an Nx workspace... The lib relies on another local lib for shared TypeScript code. The path to the shared lib is set in the tsconfig paths configuration: "paths": { "@myOrg/sharedLib": ["lib ...

Leverage the event handler within a React Component when working with TSX tags

Is there a way to expose an event handler that is defined within a React Component in an HTML-like tag? For example: <MyComp param1="abc" param2="def" onDoSomething={this.someMethod} /> I am trying to define the onDoSomething event, but currently I ...

Losing scope of "this" when accessing an Angular2 app through the window

My Angular2 app has exposed certain methods to code running outside of ng2. However, the issue arises when calling these methods outside of ng2 as the context of this is different compared to when called inside. Take a look at this link to see what exactl ...

Implement dynamic routerLink binding with Angular 11

Having a value containing routerLink and queryParams, I am attempting to bind it in the HTML. anchorValue : string = `<a [routerLink]="['../category/new ']" [queryParams]="{ query: 'category' }" routerLinkActive = ...

Conduct surveillance on the service function call within the constructor

I am currently facing a challenge with trying to monitor a service function call that is executed in the constructor. The test is straightforward, simply aiming to confirm that the function call is indeed made. beforeEach(async(() => { TestBed.con ...

Angular click switch Component keeps track of its previous state

I recently developed an Angular component that consists of a button and an icon. One key requirement is for each instance of this component to retain its own status. For example, let's say we have three instances in the app.component.html: <app-v ...

Can a string array be transformed into a union type of string literals?

Can we transform this code snippet into something like the following? const array = ['a', 'b', 'c']; // this will change dynamically, may sometimes be ['a', 'e', 'f'] const readonlyArray = arr ...

Only the (click) event is functional in Angular, while the (blur), (focus), and (focusout) events are not functioning

I have a unique HTML element as shown below <div (hover)="onHover()" (double-click)="onDoubleClick()" (resize)="resize()" (dragend)="dragEnd()"> These 4 functions are designed to display information onHover ...