Pressing the confirm button will close the sweet alert dialog

When pressing the confirm button, the swal closes. Is this the intended behavior? If so, how can I incorporate the loading example from the examples? Here is my swal code:

<swal #saveSwal
title="Are you sure?"
text ="Do you want to save changes"
cancelButtonColor="#d33"
showCancelButton="true"
cancelButtonText="No! Review"
confirmButtonColor="#3085d6"
confirmButtonText='Yes, Save progress'
(confirm)="save()"
[showLoaderOnConfirm]="true"

[focusCancel]="true">

Is there a way to keep the swal open and display the loading animation until an asynchronous operation is completed?

Answer №1

To execute an asynchronous call and maintain the alert open, you must define the preConfirm property along with showLoaderOnConfirm. Instead of listing all the SweetAlert configuration options in the HTML, it is recommended to create a property of type SweetAlertOptions within the component class and then utilize property binding with the [options] @Input decorator provided by the <swal></swal> component.

For this purpose, import SweetAlertOptions as follows:

import swal, { SweetAlertOptions } from 'sweetalert2';

A button has been implemented in the component class to trigger the alert manually, and .then() is used to display the success message upon completion of the asynchronous operation. The utilization of ViewChild and the imported SwalComponent have facilitated this process.

Snippet for the component class

app.component.ts

import { Component, ViewChild} from '@angular/core';
import swal,{ SweetAlertOptions } from 'sweetalert2';
import { SwalComponent } from '@toverux/ngx-sweetalert2';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 4';

  public alertOption:SweetAlertOptions = {};
  @ViewChild('saveSwal') private saveSwal: SwalComponent;

  constructor(){
    this.alertOption = {
      title:"Are you sure?",
      text:"Do you want to save changes",
      cancelButtonColor:"#d33",
      showCancelButton:true,
      cancelButtonText:"No! Review",
      confirmButtonColor:"#3085d6",
      confirmButtonText:'Yes, Save progress',
      showLoaderOnConfirm:true,
      focusCancel:true,
      preConfirm: () => {
    return new Promise((resolve) => {
      setTimeout(() => {
        console.log("Doing async operation");
        resolve()
      }, 5000)
    })
  },
  allowOutsideClick: () => !swal.isLoading()
    }
  }

  showAlert(evt:any){
    this.saveSwal.show().then(() => {
      swal({
      type: 'success',
      title: 'Ajax request finished!'
    })
   })
  }
  save(){
    console.log("data saved");
  }
}

HTML file

app.component.html

<swal #saveSwal
(confirm)="save()"
[options]="alertOption"
>
</swal>

<button (click)="showAlert($event)">Click here</button>
Module file
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { SweetAlert2Module } from '@toverux/ngx-sweetalert2';

@NgModule({
  imports:      [ BrowserModule, FormsModule, SweetAlert2Module.forRoot()],
  declarations: [ AppComponent, HelloComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

This setup ensures that the loader remains visible during the async call, displaying the success message only after its completion.

Check out the live demo: https://stackblitz.com/edit/angular4-ifaa17?file=app%2Fapp.component.ts

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

Lookup users either by their email or their unique primary key in the form of a UUID

Currently, I am utilizing typeorm along with typescript and the postgresql driver Within my controller, below is a snippet of code: const userRepository = getCustomRepository(UserRepositories); const query = { by_email: {where: {email: user_receiver} }, b ...

What causes me to create components with incorrect paths?

Can someone assist me with creating a new component in the dynamic-print folder instead of it being created in the app? Thank you ...

Setting character limits when defining string variables in TypeScript

Upon reviewing the documentation, it appears that there is no straightforward method to perform type checking for the minimum and maximum length of a string data type. However, is there a possible way to define a string data type using custom types in ord ...

Unable to utilize ngForm when values are already predefined

I have an Angular application with Ionic 4. Here is the HTML code for my form: <form #formAuth="ngForm" (ngSubmit)="sendCode(formAuth)" method="post"> <ion-select placeholder="Country" ngModel name="area_code" interface="modal"> <io ...

Fake AxiosInstance. In need of obtaining response in a single test

In my api.ts file import axios from 'axios' export const api = axios.create({ baseURL: 'http://localhost:3333/', }) Within my react-page.spec.tsx file: import React from 'react' import '@testing-library/jest-dom&apo ...

Recommendations for Organizing Multiple "Isolated" Applications Using MVC 5 and Angular 2

We are currently managing a large MVC 5 ASP.NET 4.5.1 web application that follows the concept of treating each page as its own application due to the vast areas it covers. The existing pages are built using JQuery, regular Javascript, and Handlebars templ ...

Playing around with Segment Analytics testing using Jest in TypeScript

I've been struggling to write a unit test that verifies if the .track method of Analytics is being called. Despite my efforts, the test keeps failing, even though invoking the function through http does trigger the call. I'm unsure if I've i ...

How can we recreate this ngModel text input form in a radio format for a spring boot mvc and angular application?

As I was following a tutorial on creating an employee CRUD model using spring boot and mysql server for the backend and angular for the frontend, I encountered a form group during the creation process. The tutorial originally had a text input field for gen ...

Transform the request in an Angular2 and jQuery Ajax POST call

I'm in the process of migrating my application from angularJS to angular2 and I've encountered a roadblock with an ajax POST call. return $.ajax({ url: "http://www.url.com", crossDomain: true, contentType: 'applicati ...

The combination of Angular's *ngIf directive and ng-template is causing issues

When I have up to 3 icons, I require less space compared to when I have 3 icons or more. To address this issue, I have implemented the following code that utilizes both *ngIf and ng-template. Unfortunately, the implementation is not functioning as expect ...

How can Angular 2 e2e tests maintain respect for their execution order?

What's the best way to ensure that Angular 2 e2e tests run in the order they are declared? I am currently using Angular-cli for my project. ...

Accessing property values from a map in Angular

Is there a way to retrieve a property from a map and display it in a table using Angular? I keep getting [object Object] when I try to display it. Even using property.first doesn't show anything. //model export interface UserModel { room: Map ...

Converting Blob to File in Electron: A step-by-step guide

Is there a way to convert a Blob into a File object in ElectronJS? I attempted the following: return new File([blob], fileName, {lastModified: new Date().getTime(), type: blob.type}); However, it appears that ElectronJs handles the File object differently ...

Creating a Component with a flexible template: (Using transclusion and an inline template)

Trying to come up with a solution for creating a component that can work with dynamic template strings and access local variables within the template has proven to be quite challenging. No matter what approach I take, I always seem to struggle with getting ...

How to retrieve cookie value from callback response in Angular?

There are two domains: Angular Application: samlapp.domain.com Node Application: samlapi.domain.com When Node calls the callback with the cookie, it redirects to the samlapp application (samlapp.domain.com/landing) Concern: How can I retrieve the cook ...

Angular: Displaying data in a list format from a multidimensional array

My data structure is as follows: { 'TeamLeader': 'Andrew', 'subordinates': [{ 'Name': 'Daniel', 'subordinates': [{ 'Name': 'Stev ...

The CoreUI Sidebar gracefully hovers over the main page content

I recently started using CoreUI to design the layout for my application, but I ran into an issue while trying to integrate the Sidebar. Although the Sidebar is visible on the left side, I'm having trouble making sure that the router-view takes up the ...

Tips for transmitting static information from route configuration to components

I am facing an issue with passing static data from a route to a component in Angular. Despite trying to pass the data in the route configuration, I keep receiving empty data when subscribing to it from the ActivatedRoute. Below is the code snippet that I h ...

A method to eliminate the mouse-over effect following the selection of an input box

Currently, I am utilizing Angular and encountering three specific requirements. Initially, there is an input box where I aim to display a placeholder upon pageload as 'TEXT1'. This placeholder should then toggle on mouse hover to display 'TE ...

Is it possible to deactivate the click event on an Angular mat table row?

Within my Angular mat table, I have implemented code that expands a table row when clicked. However, I now need to prevent certain rows from being clickable based on the "element.disable" property. <ng-container matColumnDef="id"> <th mat-hea ...