How to programmatically close an Angular 5 Modal

In my current project, I am working with Angular 5.

One of the functionalities I have implemented is a modal window. The HTML structure for this modal looks like this:

<div class="add-popup modal fade" #noteModal id="noteModal" tabindex="-1" role="dialog" aria-labelledby="noteModal">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header gredient-bg">
        <ul class="card-actions icons right-top">
          <li>
            <a href="javascript:void(0)" class="text-white" data-dismiss="modal" aria-label="Close">
              <i class="ti-close"></i>
            </a>
          </li>
        </ul>
        <h4 class="modal-title text-center">Replace Note</h4>
      </div>
      <div class="modal-body">
        <div class="package_summary text-center">
          <p>Please upload a pdf file you want to replace with the existing one. This will replace <strong>{{notesToBeRelaced?.note?.title}}</strong>
          </p>
          <p-fileUpload mode='advanced' #replaceFile name="replace1[]" [url]="getReplaceUrl(notesToBeRelaced?.note?.itemId)" accept="application/pdf" maxFileSize="100000000" (onBeforeSend)="onBeforeSend($event)" (onProgress)="onProgress($event)" (onSelect)="onFileSelect($event)"
            (onUpload)="onReplaceNote($event)" chooseLabel="Select Note">

          </p-fileUpload>
        </div>

      </div>
    </div>
  </div>
</div>

This modal is used to perform certain tasks. Once these tasks are completed, I want to be able to programmatically close the modal using TypeScript.

To achieve this, I need to get a reference to the modal in my component:

 @ViewChild('noteModal')  noteModal: ElementRef;

After binding the necessary data, I attempt to close or hide the modal:

 onReplaceNote(event) {
    this.onReplaceDataBind(JSON.parse(event.xhr.response));
  }
 onReplaceDataBind(data) {
   this.uiNotes.forEach(uiNote => {
     if (uiNote.note.itemId == data.itemId) {
       uiNote.note.title = data.title;
     }
   });
   this.noteModal.nativeElement.hide();
 } 

Once a specific point is reached in the application flow, I call this line of code to close/hide the modal:

this.noteModal.nativeElement.hide();

Answer №1

I have tried this solution before, but I recommend giving it a go again for some suggestions,

For the HTML file, consider changing your code to the following:

<a  #closeModal class="text-white" data-dismiss="modal" aria-label="Close" (click)="hideModel();">
   <i class="ti-close"></i>
</a>

In Typescript,

@ViewChild('closeModal') private closeModal: ElementRef;
public hideModel() {
        this.closeModal.nativeElement.click();      
}

I believe this should resolve your issue. If you encounter any errors, please reach out.

Thank you,

Muthu

Answer №2

To effectively close the modal, you can utilize attr.data-dismiss within a button element; an example of this is shown below (Successfully tested on Angular 10):

<button type="button" class="btn btn-block btn-primary" [attr.data-dismiss]="<expression>" id="saveButton" (click)="action()">

In this code snippet, replace < expression > with the desired expression to be evaluated and use the method action() as the function to execute. For instance, for validating form authenticity using reactive forms:

<button type="button" class="btn btn-block btn-primary" [attr.data-dismiss]="Form.valid ? 'modal' : null" id="saveButton" (click)="saveMyModalInfo()">

The provided code will check the validity of the form; if it's not valid, data-dismiss will be set to null, otherwise, it will direct to the modal.

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

Is Angular 2 Really Suitable for Multi-Page Applications?

I am currently working on a multi-page app using Angular2 and have noticed that the load times are slower than desired when in development mode. While searching for solutions, I came across a thread on stackoverflow that explains how to set up Angular2 fo ...

Manipulate and send back information from Observable in Angular

Here is an example of a scenario where I have created a service to retrieve a list of properties. Within this service, I am utilizing the map function to manipulate the response and then returning the final array as an Observable. My question is: How can ...

Please click twice in order to log in to Angular 16

Whenever I attempt to log in, I face the issue of having to click twice. The first click does not work, but the second one does. Additionally, an error message pops up: TypeError: Cannot read properties of undefined (reading 'name'). I am unsure ...

The async and await functions do not necessarily wait for one another

I am working with Typescript and have the following code: import sql = require("mssql"); const config: sql.config = {.... } const connect = async() => { return new Promise((resolve, reject) => { new sql.ConnectionPool(config).connect((e ...

Experience the dynamic synergy of React and typescript combined, harnessing

I am currently utilizing ReactJS with TypeScript. I have been attempting to incorporate a CDN script inside one of my components. Both index.html and .tsx component // .tsx file const handleScript = () => { // There seems to be an issue as the pr ...

Enabling Event bus suggestions for Typescript: A step-by-step guide

Hello, I've encountered an issue while attempting to add types for the TinyEmitter library. Specifically, I need to define two methods. First: addEventListener(e: string, (...args: any[]) => void): void; Second: emit(e: string, ...args: any[]): vo ...

Arranging the output of a Typescript project

I'm currently advocating for Typescript to be implemented in our web application. Can anyone provide insight on the best method for structuring Javascript output files? Should they be excluded from source control? And when it comes to testing, is it p ...

Disabling FormArray on-the-fly in Angular

I have a scenario where I need to disable multiple checkboxes in a FormArray when the page loads. Despite my attempts to implement this, it hasn't been successful so far. Can someone provide guidance on how to achieve this? .ts file public myForm: Fo ...

Implement Angular backend API on Azure Cloud Platform

I successfully created a backend API that connects to SQL and is hosted on my Azure account. However, I am unsure of the steps needed to deploy this API on Azure and make it accessible so that I can connect my Angular app to its URL instead of using loca ...

Module lazily loaded fails to load in Internet Explorer 11

Encountering an issue in my Angular 7 application where two modules, txxxxx module and configuration module, are lazy loaded from the App Routing Module. The problem arises when attempting to navigate to the configuration module, as it throws an error stat ...

The TypeScript inference feature is not functioning correctly

Consider the following definitions- I am confused why TypeScript fails to infer the types correctly. If you have a solution, please share! Important Notes: * Ensure that the "Strict Null Check" option is enabled. * The code includes c ...

How can I silence the warnings about "defaultProps will be removed"?

I currently have a next.js codebase that is experiencing various bugs that require attention. The console is currently displaying the following warnings: Warning: ArrowLeftInline: Support for defaultProps will be removed from function components in a futur ...

How can we utilize Typescript to check if the intern 4 page has finished loading?

I've managed to set up a function in intern 4 using TypeScript that waits for the page to load. However, there are instances where it doesn't work and throws a TimeOutError even when I catch the error within the function. Can someone please take ...

Change TypeScript React calculator button to a different type

I am currently troubleshooting my TypeScript conversion for this calculator application. I defined a type called ButtonProps, but I am uncertain about setting the handleClick or children to anything other than 'any'. Furthermore, ...

What is causing Angular to consistently display the first object in the array on the child view, while the child .ts file correctly prints information from a different object?

Once a card of any object is clicked, the information of that specific object will be printed to the console. However, the child view will only display the details of the first object in the array it retrieves from. All pages are included below. A visual e ...

Tips for correctly decorating constructors in TypeScript

When a class is wrapped with a decorator, the superclasses lose access to that classes' properties. But why does this happen? I've got some code that demonstrates the issue: First, a decorator is created which replaces the constructor of a cla ...

Efficiently Parsing FormData in React with TypeScript for Improved Data Formatting

Recently, I've started working with React and Typescript and one of the challenges I'm facing is managing an editable table with default values that can be updated and submitted. The data format for the parameters is crucial as the fields and va ...

I am experiencing difficulties with TypeORM connecting to my Postgres database

Currently, I am utilizing Express, Postgres, and TypeORM for a small-scale website development project. However, I am encountering challenges when it comes to establishing a connection between TypeORM and my Postgres database. index.ts ( async ()=>{ ...

The value binding for input elements in Angular 4 remains static and does not reflect changes in the UI

Struggling with binding input to a value in angular 4? Take for example [value]="inputFrom". Sometimes it updates when I change inputFrom, other times it doesn't. How can I ensure the input always changes whenever inputFrom changes, not sporadically? ...

How can I ensure that PrimeNG is functioning properly?

I'm encountering some difficulties setting up PrimeNG correctly to utilize its rich text editor. Despite installing all the necessary components, it's still not functioning as expected. https://i.stack.imgur.com/4kdGf.png This is my package.jso ...