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

Delete the browsing cache in Internet Explorer from an external source

Currently, I am working on developing an ASP.NET application using Visual Studio. However, a persistent issue I am facing is that every time I launch the application, Internet Explorer caches certain CSS and JS files. This forces me to manually clear the c ...

$set { "array.variable.value" :"newvalue"} utilize a different term besides "variable" or implement a new variable

When working with mongoose to store user data, one of the attributes is an array called items. In my additems.js file: const User = require('../models/User'); var array = user.items; array.indexOfObject = function (property, value) { ...

I am interested in developing a JavaScript program that can calculate multiples of 0.10

I am looking to let users input values that are multiples of 0.10, such as - 0.10, 0.20, 0.30....1.00, 1.10, 1.20...1.90, and so on. When a user enters a value in the text box, I have been checking the following validation: amount % 0.10 == 0 Is this a ...

Encountering a problem with AngularJS - receiving the [ng:areq] error, for more information visit http://errors.angularjs.org/1.3.2/ng/areq

While working on my CRUD angularApp, I encountered a strange error in Chrome dev tools. Here is the complete error message: error: [ng:areq] http://errors.angularjs.org/1.3.2/ng/areq?p0=DbController&p1=not%20a%20function%2C%20got%20string at angular.j ...

Tips on utilizing browser.getCurrentUrl() within a Protractor examination

I’ve been wrestling with these lines of Protractor code today: element(by.linkText("People")).click(); browser.waitForAngular(); var url = browser.getCurrentUrl(); ... It seems that getCurrentUrl always throws an error when placed after a waitF ...

What is the best way to convert a `readonly string[]` to a regular `string[]`?

My data setup is as follows (I am not declaring it as an enum because it is used in both TypeScript server code and non-TypeScript client code): import { enumType } from 'nexus'; export const TYPE_ENUM = Object.freeze({ H: 'H', S: ...

The base URL specified in the tsconfig file is causing the absolute path to malfunction

Displayed below is the layout of my folders on the left, along with a metro error in the terminal and my tsconfig.json configuration with baseUrl set to './src'. Additionally, I have included screenshots of my app.ts and MainTabs.ts for further c ...

Is it possible to merge these two scripts into a single one within Vue?

As a newcomer to VUE, I am faced with the task of modifying some existing code. Here is my dilemma: Within a single component, there are two script tags present. One of them contains an import for useStore from the vuex library. The other script tag incl ...

What is the method for defining distinct parameters for nested functions in AngularJS?

When using AngularJS, what happens when a parent function encapsulates a child function that includes parameters not present in the parent? In this scenario illustrated below with the green arrow representing the parent function without any parameters, an ...

Phonegap application functioning smoothly on computer, encountering issues on mobile device

Hey there! I recently developed a phonegap app that retrieves JSON data from a YQL link and presents it to the user. It works perfectly on Google Chrome desktop, but my client mentioned that it doesn't work on his Android 2.3 device. Could you help me ...

Is there a way to modify the window's location without having to reload it and without resorting to any sne

Initially, I believed that the hash hack was a necessity, but after observing the recent updates from Facebook, my perspective has shifted. The original hash hack (not certain if this is the correct term) involved changing location.hash to save a state in ...

Angular 2: A ready-made solution for developing interactive discussion features

Currently working on my Angular 2 application and looking to incorporate a discussion feature. Are there any pre-existing solutions available for this integration? ...

Error message indicates failure of switch case, resulting in invalid output of

My BMI calculator was working fine until I switched the conditionals to a switch statement for cleaner code. Now, the code is breaking and the result variable isn't being set properly for display. Do you have any ideas on what could be missing here? ...

What might be causing my Vue unit test to overlook a function?

I am in the process of creating unit tests for my component dateFormat.js using Jest. The focus is on testing the function formatDateGlobal. Here is an excerpt from the test: import DateFormat from '../dateFormat'; describe('dateFormat.js& ...

Obtaining the ID from a URL in node.js

As a newcomer to the world of Javascript and node.js, I am venturing into creating a REST API with URLs structured as follows: /user/{userId}/docs The goal is to extract the value of {userId}, which, for instance, in the URL /user/5/docs would be 5. Wh ...

Prevent entry into property in Ionic 2 course

I receive a dynamic translation file from a server periodically, and I'm unable to modify its format. When a new page is instantiated in my Ionic App, I assign the value from storage to this.translations. See the constructor below: constructor(stora ...

What could be causing the lack of updates for a watched object in vue?

Although there are many similar questions on this topic, mine has a unique twist. After delving into reactivity in depth, I feel like I have a solid grasp of the concept. However, one thing continues to baffle me: Summary: Why does a watched property det ...

Remove an array object in React Redux

I recently started using Redux and I’ve encountered a major issue. Whenever I try to remove an object from an array, the map function stops working. Do you have any tips or suggestions? reducer.js: const initialState = { storeState: { name: ...

Lists are not limited to only <li> elements and elements that support scripts (<script> and <template>)

While testing my webpage's accessibility in Google Chrome Lighthouse, I encountered the following error. I am aware of the significance of properly structured lists in enhancing webpage accessibility. It is perplexing for me to receive this error desp ...

Autocomplete search from a distance

I am currently learning Angular and trying to create an autocomplete form with content that is filtered on the back-end. I have defined a class and Interface for Terminal: export class Terminal { constructor( public id: number, public name: ...