What is the best method to trigger a bootstrap modal window from a separate component in Angular 8?

I have successfully implemented a bootstrap modal window that opens on a button click. However, I am now facing difficulty in opening the same modal window from a different component. Below is the code I have tried:

<section>
    <button type="button" class="btn btn-primary" (click)="openModal()">Sign In</button>
    
    <div id="signInModal" class="modal fade m-5" role="dialog"
        aria-labelledby="dialog-sizes-name2" data-backdrop="static">
        <div class="modal-dialog modal-md">
            <div class="modal-content">
                <div class="modal-header">
                    <h6 class="circularBold signUpHeading">Sign In</h6>
                    <button type="button" class="close" aria-label="Close" data-dismiss="modal">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form [formGroup]="signInForm">    
                            <div class="mt-4">
                                <button type="button" class="btn buttons nextBtn circularBold w-100" (click)="login()">Log in</button>
                                <p class="black2E circularBook mt-4 font-size12">Don't have an account?
                                    <a href="" class="circularMedium">Sign up</a>
                                </p>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</section>

TS

  openModal() {
    $('#signInModal').modal('show');
  }

Code from another component

modalRef: BsModalRef;
 constructor(
    private modalService: BsModalService
  ) { }

   join(){
        this.modalRef = this.modalService.show(SigninComponent);
   }

Any assistance on this issue would be highly appreciated.

Thank you in advance!

Answer №1

Upon further examination of your attempt to display the dialog, it is clear that you are utilizing ngx-bootstrap

In line with @MikeOne's advice, Avoid using JQuery in an angular application. Angular is sufficient for binding your view to the model.

The Issue

After attempting to replicate your code, I have found that enclosing your content within the following code snippet appears to be causing the dialog not to appear:

<section>
    <button type="button" class="btn btn-primary" (click)="openModal()">Sign In</button>
    
    <div id="signInModal" class="modal fade m-5" role="dialog"
        aria-labelledby="dialog-sizes-name2" data-backdrop="static">
        <div class="modal-dialog modal-md">

          <!-- Other Stuff here -->
        </div>
    </div>
</section>

Resolution

Within your LoginComponent, simply include the following:

<div class="modal-content">
    <div class="modal-header">
        <h6 class="circularBold signUpHeading">Sign In</h6>
        <button
            type="button"
            class="close"
            aria-label="Close"
            data-dismiss="modal"
          >
            <span aria-hidden="true"gt;&times;</span>
          </button>
    </div>
    <div class="modal-body">
        <form [formGroup]="signInForm">
            <div class="mt-4">
                <button
                type="button"
                class="btn buttons nextBtn circularBold w-100"
                (click)="login()"
              >
                Log in
              </button>
                <p class="black2E circularBook mt-4 font-size12">
                    Don't have an account?
                    <a href="" class="circularMedium">Sign up</a>
                </p>
            </div>
        </form>
    </div>
</div>

View this solution on stackblitz

Answer №2

It is recommended to utilize ngx-bootstrap

To add ngx-bootstrap, use the following command:

ng add ngx-bootstrap  --component modals

Ensure you import ModalModule in your app.module.ts like this:

import { ModalModule } from 'ngx-bootstrap/modal';

@NgModule({
  imports: [ModalModule.forRoot(),...]
})
export class AppModule(){}

To create a basic template, your parent.component.ts file should have the following setup

import { Component, TemplateRef } from '@angular/core';
import { BsModalService, BsModalRef } from 'ngx-bootstrap/modal';
import { TemplateComponent } from './template/template.component';
 
@Component({
  selector: 'app-parent',
  templateUrl: './app.component.html'
})
export class ParentComponent {
  modalRef: BsModalRef;
  constructor(private modalService: BsModalService) {}

 // The TemplateComponent contains the modal content. Another component named "TemplateComponent" has been created for this purpose.

  openModal() {
    this.modalRef = this.modalService.show(TemplateComponent);
  }
}

In the Template component, the template.component.ts file should be set up as follows

    import { Component } from '@angular/core';
    import { BsModalRef } from 'ngx-bootstrap/modal';
@Component({
    selector: 'app-template',
    templateUrl: './template.component.html'
})
export class TemplateComponent implements OnInit {
    constructor(public modalRef: BsModalRef) { }
ngOnInit(){}
}

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 Directive hinges on the use of a template

I am exploring a more web-component approach to using Angular. As part of this, I have developed an http-request directive with url and response attributes. The implementation is successful, but I find that my directive relies on a template unnecessarily. ...

The Express.js main router is functioning properly, however, the other routers connected to it are experiencing

I'm encountering an issue with my routers. The main route /weather is working fine, but other routes connected to it are not functioning properly. app.js const express = require('express'); const weatherRoute = require('./back/routes/w ...

Flow the child process output as it streams

I have a unique custom command line tool implemented in Python which uses the "print" statement to display its output. To interact with this tool from Node.js, I spawn a child process and send commands to it using the child.stdin.write method. Below is an ...

Problem with onblur and onchange events not being triggered in input tag

After encountering this issue, I came to the realization that the events onblur and onchange function properly. However, I noticed that if your page contains only ONE <input type="text" onblur="loadXMLDoc()"> Change Content</input> The behav ...

Trouble with importing React JSX from a separate file when working with Typescript

This problem bears some resemblance to How to import React JSX correctly from a separate file in Typescript 1.6. Everything seems to be working smoothly when all the code is contained within a single file. However, as soon as I move the component to anoth ...

What is the proper way to invoke a child method after converting an object from a parent class to a child class?

When we have a subclass B that overrides a method from its superclass A in TypeScript, why does calling the method on an instance of A result in the parent class's implementation being called? In TypeScript, consider a class called Drug with properti ...

"Experiencing sluggish performance with VSCode while using TypeScript and Styled Components

My experience with vscode's type-checking is frustratingly slow, especially when I am using styled components. I have tried searching for a solution multiple times, but have only come across similar issues on GitHub. I attempted to read and understa ...

Developing a versatile table component for integration

My frontend app heavily utilizes tables in its components, so I decided to create a generic component for tables. Initially, I defined a model for each cell within the table: export class MemberTable { public content: string; public type: string; // ...

Encountering an unexpected token in Javascript when using conditionals

I am currently attempting to integrate a JavaScript condition within a listed order, containing two radio buttons that need to be checked in order to progress to the following list based on the selection. <li data-input-trigger> <label class="fs- ...

Display a comprehensive inventory of all bot commands within a designated category

When a user executes a command, I have various commands categorized and would like to present them accordingly. For instance, consider the following command: const Discord = require('discord.js') const { MessageEmbed } = require('discord.js& ...

The jQuery keyup event initiates multiple times, increasing exponentially with each trigger

I recently added a search bar with auto-complete functionality to my website. The search bar queries the database for elements that begin with the text entered by the user as they type. Although it works well, I noticed that every time the user inputs ano ...

AngularJS not compatible with Splice functionality

Currently, I am working on a form for an Items list that allows users to add, edit, and delete items. While the add and edit functionalities are working correctly, I am facing some issues with the delete functionality. Below is a snippet of my code that i ...

What is the advantage of not importing related modules?

As a newcomer to React, please excuse any novice questions I may have. I am currently utilizing npx create-react-app to develop a React app, but I'm unsure of the inner workings: Q1-If I were to throw an error in a component like so: import React, { ...

Aligning Content in the Middle of a Bootstrap Row

I'm struggling to horizontally center the content in the "row" class div. I've attempted using justify-content-center and other variations. <div class="container"> <div class="row"> <div class="col-md-4 portfolio-item ...

Tips for adjusting the language settings on a date picker

Is there a way to change the language from English to French when selecting a month? I believe I need to configure something in the core.module.ts. How can I achieve this? https://i.sstatic.net/Cpl08.png @NgModule({ declarations: [], imports: [ Co ...

What is the best way to programmatically disable a button in JavaScript or jQuery when all the checkboxes in a grid are either disabled or unchecked?

In my grid, one column contains checkboxes. I need to implement a feature where a button is disabled if all the checkboxes are unticked. How can I achieve this using JavaScript or jQuery? .Aspx File <asp:TemplateField HeaderText="Cancel SO Line Item"& ...

To enhance VS IntelliSense and type checking in react-intl's FormattedMessage component, assign an id that aligns with a custom TypeScript interface

Due to the limitations of react-localization in terms of date and number formats, as well as its heavy reliance on a single developer, our team made the decision to transition to react-intl for a more stable long-term solution. Check out the contributors ...

Synchronizing two navigation menus on a single-page application website

Let me start by saying that I specialize in back end development and am facing a specific challenge with building a website that includes two navigation menus. The main navigation menu features links like Home, while the sub-navigation menu includes option ...

Troubleshooting Issues with Form Inputs in JS/Angular Using Places API and document.getElementById Method

I have integrated the Google Places API to automatically populate locations/destinations into a form after a user searches. The auto-population works correctly, but I am facing an issue when trying to submit the form into my database – the object is alwa ...

How can I utilize React to pull information from the Google Taxonomy API?

Seeking assistance with React development, as I am a beginner and looking to retrieve data from this URL and organize it into a tree structure. I not only want to fetch the data but also display it in a tree format. My current code successfully retrieves t ...