Opening and closing a default Bootstrap modal in Angular 2

Instead of using angular2-bootstrap or ng2-bs3-modal as recommended in the discussions on Angular 2 Bootstrap Modal and Angular 2.0 and Modal Dialog, I want to explore other options.

I understand how the Bootstrap modal opens and closes:

  • The display property switches between display: none; and display: block;
  • An attribute toggles on the div between aria-hidden="true" and aria-hidden="false"

My initial thought was to bind to the aria-hidden attribute like this: [aria-hidden]="true", but unfortunately, I found out that I cannot bind to aria-hidden because it is not a recognized property of the div element (note: attr.aria-hidden does not exist).

It is known that with jQuery, the Bootstrap modal can be controlled with $('#myModal').modal(), as highlighted in this question: How to open a Bootstrap modal window using jQuery?

So, my question is: Is there a TypeScript function that has a similar functionality to modal() in jQuery? Or, is there a way to bind a function or variable to aria-hidden?

Here is the snippet of my current html:

<div id="createAccountModal" class="modal fade customForm" role="dialog" [aria-hidden]="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4>Create account</h4>
            </div>
            <div class="modal-body">
               <p>Lorem ipsum</P>
            </div>
            <div class="modal-footer align-left">
                My custom footer
            </div>
        </div>
    </div>
</div

Answer №1

If you're looking to implement a modal in your Angular application, you can create a separate file called myModal.html with the following content:

<div class="modal-backdrop fade in" [style.display]="showModal ? 'block' : 'none'"></div>
  <div class="modal" tabindex="-1" role="dialog" style="display: block" [style.display]="showModal ? 'block' : 'none'">
     <div class="modal-dialog">
        <div class="modal-popup">
          <div class="popup-title">
            <span>{{title}} </span>
            <i class="icon-cancel fr" data-dismiss="modal" aria-label="Close" (click)="cancelAction()"></i>
            <p *ngIf="subTitle">{{subTitle}}</p>
          </div>
        <ng-content></ng-content>
      </div>
  </div>
</div>

Next, create a corresponding TypeScript file named myModal.component.ts:

import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core';

const template: string = require('./myModal.html');

@Component({
   selector: 'modal',
   template
})

export class Modal implements OnInit {
  // Include necessary Input and Output properties here
  
  constructor() {}

  // Implement necessary methods for showing, hiding, and handling actions
  
}

// Define ModalAction and ModalResult interfaces
export enum ModalAction { POSITIVE, CANCEL }

export interface ModalResult {
  action: ModalAction;
}

Lastly, create a reusable module for the modal component so you can easily use it anywhere in your application. Here's an example of how you can utilize the modal:

<modal #deleteUserModal id="deleteUser"
   [show-modal]="isModalOpen"
   [title]="'Delete'"
   >
  <div class="popup-content">
    <p>Are you sure you want to delete the user permanently?</p>
  </div>
  <div class="popup-footer">
    <button class="btn cancel"  aria-label="Close" (click)="deleteUserModal.hide()">
        Cancel
    </button>
    <button type="button" class="btn btn-primary" (click)="deleteSelectedUser(deleteUserModal)" aria-label="Close">
        Delete
    </button>
  </div>
</modal>

Feel free to enhance this modal component further based on your specific requirements!

Answer №2

If your modal includes a cancel button (if not, create a hidden close button), you have the option to simulate a click event on this button to close your form. Within your component, make sure to incorporate a ViewChild.

export class HelloComponent implements OnInit {

@ViewChild('fileInput') fileInput:ElementRef;

In your close button, remember to add #fileInput.

<button class="btn btn-danger" #fileInput id="delete-node" name="button" data-dismiss="modal" type="submit">Cancelar</button>

When you need to close the modal programmatically, simply trigger a click event on the close button.

this.fileInput.nativeElement.click();

The same concept can be applied for opening the modal as well.

Answer №3

Well, it seems that there's no necessity to explicitly bind to aria-hidden, even though it might be feasible.

The information presented in this response was sourced from a discussion about Angular 2.0 and Modal Dialog (albeit with only 9 upvotes).

By incorporating

<div id="createAccountModal" class="modal fade customForm" role="dialog" [ngClass]="{'in': visibleAnimate}"
       [ngStyle]="{'display': visible ? 'block' : 'none', 'opacity': visibleAnimate ? 1 : 0}">

into my codebase, and attaching a (click) event handler to a button to control the toggling of the visible and visibleAnimate variables met my requirements perfectly.

Answer №4

Why not try utilizing ng-window? It provides developers with the ability to easily open and manage multiple windows within single-page applications without the need for jQuery or Bootstrap.

https://i.sstatic.net/f2ehJ.gif

Available Configuration Options:

  • Maximize window
  • Minimize window
  • Custom size
  • Custom position
  • Ability to drag the window
  • Option to block the parent window
  • Option to center the window
  • Pass values to child windows
  • Pass values from child windows to parent window
  • Listen for closing child windows in the parent window
  • Custom listener for resize events
  • Open with maximum size
  • Enable or disable window resizing
  • Enable or disable maximization
  • Enable or disable minimization

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

Encountering issues with `Partial<this['someProperty']>` usage in TypeScript

Provided class A { props: { bool?: boolean, test: string } = { test: 'a' }; setProps(newPropertiesr: Partial<this['props']>) { } a() { this.setProps({ bool: fals ...

Unable to integrate BokehJS with Angular8

Here is the error log that appeared in the browser: AppComponent.html:1 ERROR TypeError: FlatBush is not a constructor at new SpatialIndex (vendor.js:90501) at AnnularWedgeView.push../node_modules/bokehjs/build/js/lib/models/glyphs/xy_glyph.js.XYG ...

Extracting a value from a datetimepicker in Angular 6

Currently employing a datetimepicker within Angular. Once the datetime is chosen, how can I retrieve that value and display it in the paragraph element below? <dl-date-time-picker minuteStep="15" ></dl-date-time-picker> <p class="text-sec ...

Empty array being returned by Mongoose after calling the populate() function

I've been struggling for the past 3-4 hours, banging my head against the wall and scouring countless articles here on StackOverflow, but I just can't seem to get my response to populate an array correctly. I'm working with Express.js, Typesc ...

Tips for customizing the appearance of a label when a MUI Radio Button is selected

Hello everyone, I am attempting to customize the label text color of a radio button to turn blue when selected. https://i.stack.imgur.com/btSc2.jpg HERE IS THE CODE FOR MY MUI BUTTON SO FAR import * as React from "react"; import Radio from &quo ...

Add an asterisk before each line of comment when working in a TypeScript file using the VS Code IDE

Within my VS Code workspace, I am using the Typescript language and would like to format my comments across multiple lines with a specific style (look out for the star character) /** *@desc any text * any text */ However, when I attempt to write a comm ...

The variable "theme" is referenced prior to being initialized

https://i.stack.imgur.com/QL0pa.png One of the variables in my code, theme, is set to be assigned a value from a for loop: let theme: Theme for (const themeObj of themeList) { const [muiThemeName, muiTheme] = Object.entries(themeObj)[0]!; if (muiThem ...

What is the best way to create a routerlink that is both single-clickable and double-clickable within an

There have been numerous instances where a similar question has been raised, but I am unable to make this work. Despite looking at various answers such as this one on Stack Overflow that don't seem to work for most users. While this may not be specifi ...

I'm having trouble configuring the header in my Node/Express route

Using Node and the Express framework for my backend, along with React for my frontend, all coded in Typescript. The elastic search client is responsible for fetching data on the backend, but I don't believe that's where the issue lies. I'm ...

Having trouble utilizing a JavaScript file within TypeScript

I am currently exploring the integration of Three.js into an Angular application. Following the documentation, I imported Three.js using the following line: import * as THREE from 'three'; In addition, I installed the types for Three.js with th ...

Implement Bootstrap into Asp.Net Core 6 for the scaffolded Identity _Layout.cshtml

In my development environment using VS2022 Preview, I have set up a Single Page Application with Angular and the default project provided by VS2022. To customize the appearance of the Identity pages, I decided to override Bootstrap with a style from Bootsw ...

Can we determine the type signature of useCallback for an event handler by inference?

Currently, I am working with TypeScript and React to implement a callback function using an arrow function on a Material UI <Select> component: import React from 'react'; import MenuItem from '@material-ui/core/MenuItem'; import ...

A blank canvas emerges upon utilizing the Angular-Bootstrap Carousel feature

This is my first experience using Angular with Bootstrap's carousel component, and I'm encountering a peculiar issue where a white slide appears before each transition (refer to the GIF below). Despite following the setup instructions on ng-boots ...

Conceal API request details on the network tab

I am currently working on an application built with Angular 10. I was wondering if there is a way to encrypt the request parameters or hide sensitive data. The issue is that anyone who can view the URL has access to both the Bearer token and the request pa ...

Issue: Module '@angular/compiler' not found

After downloading an angular template, I encountered an issue while running "ng serve": Cannot find module '@angular/compiler' Error: Cannot find module '@angular/compiler' ... I tried various solutions found on the internet, incl ...

Ionic is encountering a problem with module build, specifically an error related to the absence of a file or directory

Using Ionic has led to encountering the following error message: Runtime Error Uncaught (in promise): Error: Module build failed: Error: ENOENT: no such file or directory, open '/Users/richardmarais/Development/ionic/theWhoZoo/src/pages/model/r ...

Tips for deactivating the matMenuTrigger when the mat menu does not display any menu items

How can I dynamically disable the mat menu trigger when no items are rendered due to ngIf conditions in the mat-menu? <button mat-button [matMenuTriggerFor]="menu" [disabled]="disableTrigger" > Trigger </button> <mat-menu #menu ...

Ways to verify the functionality of a function utilizing a Subscription that yields no return value

I'm working with a TypeScript ModelService that has an edit function: edit(model: Model): Observable<Model> { const body = JSON.stringify(model); return this.http.put(`/models/edit/${model.id}`, body)); } Additionally, there is a TypeScrip ...

The best practices for utilizing ES6 Modules syntax in TypeScript files within a NextJS environment

The issue appears to be trapped in a loop: package.json is missing type: "module". This results in an error when trying to use modules in TypeScript files: An error occurred while running the seed command: /Users/me/code/me/prisma-learning/grap ...

How to use Angular template syntax to assign an async array to multiple variables

When working in JS, there is a clever method for assigning values from an array to new variables with ease: let [a, b, c] = [1, 2, 3]; // a = 1, b = 2, c = 3 I started thinking about whether I could achieve a similar elegant solution using Angular's ...