Prevent clicking outside the bootstrap modal in Angular 4 from closing the modal

Just starting out with angular4 and incorporating bootstrap modal into my project. I want the modal to close when clicking outside of it. Here's the code snippet:

//in html

<div bsModal #noticeModal="bs-modal" class="modal fade" tabindex="-1" role="dialog" 
    aria-labelledby="myLargeModalLabel"
    aria-hidden="true">

    <div class="modal-dialog modal-md">
        <div class="modal-content">
              Hello World
        </div>
    </div>
</div>

// in ts code

@ViewChild('noticeModal') public noticeModal: ModalDirective;

ngAfterViewInit() {
   this.noticeModal.show();
};

Answer №1

Here is a handy HTML configuration that may assist with your issue:

<div bsModal #noticeModal="bs-modal" class="modal fade" tabindex="-1" role="dialog" 
    [config]="{backdrop: 'static',  keyboard: false}" 
    aria-labelledby="myLargeModalLabel"
    aria-hidden="true>

    <div class="modal-dialog modal-md">
        <div class="modal-content">
              Hello World
        </div>
    </div>
</div>

Answer №2

When utilizing a button to trigger the opening of a popup, ensure to apply the following configuration to the button:

<button data-target="#myModal" data-toggle="modal" 
data-backdrop="static" 
data-keyboard="false">

Answer №3

This method worked perfectly for me when I included

{backdrop: 'static', keyboard: false}
while calling the modal like this -->
$('#myModal').modal({backdrop: 'static', keyboard: false})

I found that I didn't need to include bsModal in the <div> or any directive modules for it to work.

A clearer solution is outlined below: HTML:

 <div #crudModal class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-md">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span>
        </button>
        <h4 class="modal-title" id="myModalLabel">Modal Title</h4>
      </div>
      <div class="modal-body">        
      </div>
      <div class="modal-footer">       
      </div>
    </div>
  </div>
</div>

In TypeScript:

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';

@ViewChild('crudModal') crudModal: ElementRef;

openModal() {
    $(this.crudModal.nativeElement).modal({backdrop: 'static', keyboard: false});
}

I hope this explanation helps you with your implementation.

Answer №4

By the way, if you opt for using the component approach with bsModal through BsModalService, you can easily configure: ignoreBackdropClick = false (to ignore backdrop clicks), as explained in the Angular Bootstrap API reference.

YourComponent.ts

constructor(private bsModalService: BsModalService) {}

const bsModal = this.bsModalService.show(YourModalComponent, {
    class: 'modal-dialog-centered modal-md',
    ignoreBackdropClick: true
});

P.S. It's advisable to follow this approach rather than embedding it directly in your HTML template. Consider the benefits of reusability 😉

Answer №5

Implement the backdrop: 'static' parameter, which can be found in the detailed documentation on this page.

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

Tips for resolving the error message "Nextjs with Typescript: 'describe' is not defined"

I am facing some obstacles while trying to compile my Nextjs project for production. Here is the list of errors that I encountered: ./components/Layout/Header/Header.test.tsx 6:1 Error: 'describe' is not defined. no-undef 7:20 Error: 'jes ...

Discover the Hassle-Free Approach to Triggering Angular Material Menu with ViewChild and MatMenuTrigger

Is there a way to programmatically open an Angular Material menu using a Template Reference Variable on a button trigger that is accessed in the component through ViewChild? I want the menu to open when the mouse hovers over it, instead of just clicking i ...

Having trouble inserting the current time into Firebase Firestore

Currently, I am looking to use the current time as an input in Firebase Firestore (timestamp). Initially, when using the code snippet below: today: number = Date.now(); everything appeared to function correctly. However, the time was only updated once, s ...

What is the reason behind Rxjs switchMap only emitting the final value from an of() observable source?

Here are two code snippets, one using map and the other using switchMap. The functionality of map is clear: of('foo', 'bar') .pipe(map((val) => sanitizer(val))) .subscribe((val) => console.log('value:', val)); func ...

Trigger Angular2 EventEmitter in child component to inform parent component

I am having trouble triggering an event from the child component to the parent component. @Component({ template:'<foo></foo>' }) export class ParentComponent{ onDoSomething($event){ //handling logic goes here } } @Compo ...

Steps for preloading a user prior to the page loading

Main Concern I currently have an Auth Provider set up in my application that wraps around the entire _app.tsx file. This allows me to utilize the "useAuth" hook and access the user object from any part of the app. However, I am facing an issue when using ...

What is the best way to hand off this object to the concatMap mapping function?

I'm currently in the process of developing a custom Angular2 module specifically designed for caching images. Within this module, I am utilizing a provider service that returns Observables of loaded resources - either synchronously if they are already ...

Using the `document.querySelector` method to target the `.mat-progress-bar-fill::after` element

Is there a way to dynamically adjust the fill value of an Angular Material Progress Bar? In CSS, I can achieve this with: ::ng-deep .mat-progress-bar-fill::after { background-color: red; } However, since the value needs to be dynamic, I am unable to do ...

What is the best way to pass a CSS root constant to a separate CSS file?

In my Angular test project, I'm experimenting with using the same colors repeatedly. To achieve this, I created a constants.css file where I defined all my root constants, which currently consist of colors. However, I've hit a roadblock when atte ...

Extracting the "defined" type from a TypeScript property during runtime

My current task Presently, I am iterating through the keys of an object and transferring their values to another object. interface From { [key: string]: string; } let from: From = { prop1: "foo", prop2: "23", }; interface To { [key: str ...

Using angular 7 to apply a dynamic CSS class on a span element

I want to dynamically change the CSS class of a span element in an ngx datatable based on the value. Here is my HTML code: <ngx-datatable #orderinvoice class="bootstrap" [rows]="invoiceSource" [headerHeight]="50" [footerHeight]="50" [rowHe ...

ngc encountering issues when compiling project with untyped third-party libraries

Utilizing a third-party library without defined types, the project is being developed using Angular CLI (version 1.0.0-beta.29) and the library is declared in typings.d.ts. In this instance: declare module ‘xml2js-es6-promise’; The project compiles an ...

The Select element in Next.js needs to have an accessible name - it must have a title attribute for improved accessibility

Just starting out with Next.js and Typescript. I'm in the process of rebuilding an app using Next.js, but I've hit a roadblock when trying to split pages and components. The error message that keeps popping up is "Select element must have an acce ...

The art of integrating partial rendering into a template

I'm currently working on a project using Angular 2 and I need to display a partial inside a template without having to create a new component. Is this doable? import {Component} from 'angular2/core'; import {RouteConfig, ROUTER_DIRECTIVES} ...

Nested HTTP requests in Angular using RxJS: Triggering component update after completion of the first HTTP request

I have a requirement to make two http requests sequentially. The values retrieved from the first call will be used in the second call. Additionally, I need to update my component once the first http request is completed and also update it once the second ...

Error Encountered: ExpressionChangedAfterItHasBeenCheckedError in Shared Service

Why am I receiving a warning in the console even though everything seems to be functioning correctly in Angular? How can this issue be resolved? You can find the StackBlitz here I understand that one possible solution is to use parent-child communication ...

Angular 6 - Defining two components with several modules nested within each other

There are two components, C1 and C2. Each component has its own module file. How can I declare C1 in C2 in Angular 6? // Module 1 @NgModule({ imports: [], exports: [], declarations: [ ComponentX, ComponentY ], providers: [] }) // Module 2 @NgModule ...

Are undefined Static Properties an Issue in Mocked Classes? (Jest)

Currently, I am facing a challenge in mocking a class that includes a static property. jest.mock("../../src/logger/index"); import { Logger } from "../../src/logger/index"; // .. const LoggerMock = Logger as jest.MockedClass<typeof ...

Experiencing unfamiliar typescript glitches while attempting to compile a turborepo initiative

I have been utilizing the turborepo-template for my project. Initially, everything was running smoothly until TypeScript suddenly started displaying peculiar errors. ../../packages/fork-me/src/client/star-me/star-me.tsx:19:4 nextjs-example:build: Type erro ...

Angular Back button event not triggering

I'm attempting to redirect the user to a specific URL when they click the back button in their browser. Here is the code snippet: constructor(private router: Router,private location: PlatformLocation) { let eventUrl = window.sessionSt ...