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

Retrieve the values of private variables within a defined function

While experimenting with typescript, I have encountered an issue that I can't seem to resolve. My project involves using Angular, so I will present my problem within that context. Here is a snippet of my code: class PersonCtrl{ private $scope: I ...

The term 'EmployeeContext' is being utilized as a namespace in this scenario, although it actually pertains to a type.ts(2702)

<EmployeeContext.Provider> value={addEmployee, DefaultData, sortedEmployees, deleteEmployee, updateEmployee} {props.children}; </EmployeeContext.Provider> I am currently facing an issue mentioned in the title. Could anyone lend a hand? ...

What is the best way to organize information in a table based on the date

This is my data table https://i.stack.imgur.com/1DNlj.png in the displayed table, the registration dates are sorted with the oldest date at the top. However, I aim to have the newest data displayed first. Below is the code snippet I am using: this.dataSo ...

How to implement SVG in React with the image source as a parameter?

I've been working on a React component in NextJS that displays an image inside a hexagon. The issue I'm facing is that when I try to use multiple instances of this component with different images in the HexagonWall, all hexagons end up displaying ...

Closing an Angular Modal Service from External Elements - Learn the Techniques

This is the official angular-modal-service Github page. If you're looking for some examples, check out the angular-modal-service examples here. For my current project, I am working on developing a "Custom Modal" without relying on Bootstrap. Here&ap ...

Can all intervals set within NGZone be cleared?

Within my Angular2 component, I have a custom 3rd party JQuery plugin that is initialized in the OnInit event. Unfortunately, this 3rd party library uses setIntervals extensively. This poses a problem when navigating away from the view as the intervals rem ...

What is the best way to group an array based on a dynamic key?

My goal is to group values in an array by a given ID. I've attempted a method for this, but it's not working for dynamic keys. Here is the current array: let employees = [{"employeeDetail": [{"empID": "XXYYZZ11"," ...

Utilizing a loaded variable containing data from an external API request within the useEffect() hook of a React component

Essentially, I have an API request within the useEffect() hook to fetch all "notebooks" before the page renders, allowing me to display them. useEffect(() => { getIdToken().then((idToken) => { const data = getAllNotebooks(idToken); ...

Encountering errors in Visual Studio when trying to work with node_modules directories that have a tsconfig

In my current project, there is a tsconfig.json file located in the root directory. Strangely, Visual Studio keeps throwing errors related to other instances of tsconfig.json found in different packages, as shown below: https://i.sstatic.net/T7Co2.png Ev ...

Adding TH into a TABLE in Angular 2 by verifying TD elements

I am seeking a way to automatically generate thead and th, using td in the template : <Datatable> <tr #lineSelected *ngFor="let subscription of results"> <td nameColumn="Nom">{{subscription.name}}</td> <td n ...

Mongoose fails to add an object to an array

I am facing an issue with my express application where comments are not being inserted into posts. Even though there are no errors displayed, the comments are not being added when posting via Postman. I have tried various solutions like this and this, but ...

Implementing real-time search functionality using API calls in Angular

Seeking guidance on implementing Typeahead for a global search feature in my app. When users type, it should call an API and display results in a drop-down menu. I am a beginner in Angular and Typescript, so any working examples with code would be greatly ...

The Excel Match function is experiencing issues when used in conjunction with the MS-Graph API

Recently, I've encountered an issue with sending a match-function post request to an Excel workbook using the MS-Graph API. Instead of receiving the value of the first column that contains the lookup value, I'm getting the value from the second c ...

Attempting to utilize the setInterval function in Ionic 4 to invoke a specific function every second, unfortunately, the function fails to execute

Working with Ionic 4 has been a breeze for me. Recently, I encountered a situation where I needed to update the value of an ion-range every second by invoking a function. However, despite successfully compiling the code, the changeMark function never seeme ...

Guide on how to add a generic return type to a function in typescript

Is there a way to annotate a function that returns a factory in TypeScript to ensure it contains correct type definitions? Consider the following code: class item<T> { constructor(a: T) { this.a = a; } a: T } function generate(c) { ret ...

Custom CSS identifier for interactive MuiButton text element

I've been searching for a CSS selector to target this dynamic date element, which is identified as MuiButton-label. While I can currently locate it using xpath in Playwright code, I'm hoping to find an alternative method using a CSS selector. Tha ...

The art of expanding Angular's HTTP client functionality

I understand that the following code is not valid in Angular, but I am using it for visual demonstration purposes. My goal is to enhance the Angular HTTP client by adding custom headers. I envision creating a class like this, where I extend the Angular h ...

How to identify generic return type in TypeScript

My goal is to develop a core dialog class that can automatically resolve dialog types and return values based on the input provided. I have made progress in implementing this functionality, but I am facing challenges with handling the return values. Each ...

What is the best way to retrieve matching values based on IDs from an imported table?

How can I retrieve values that match on ID with another imported table? My goal is to import bank details from another table using the ID and display it alongside the companyName that shares the same ID with the bank details. I've attempted several o ...

Why is the format incorrect when the Angular 7 (Change)-Function on Input of type Date isn't functioning?

I am facing an issue with updating the date using key input and assigning the selected date to a property of my object. Below is the code I'm currently working with: <input type="date" [value]="dateTime()" (change)="setDate($event)"/> The dat ...