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

Trying to determine the specific key of an object based on its value in TypeScript?

Looking to create a function that can retrieve the key for a given value. type Items<T> = Exclude<{ [P in keyof T]: [P, T[P]]; }[keyof T], undefined>[]; export const getKeyName = <T extends Record<PropertyKey, unknown>, V>( col ...

The functionality of Silex Middleware Authentication varies depending on whether it is being used in Postman or

As a developer with limited experience in back-end development, I have encountered a real problem despite my best efforts. I am currently using Silex as a simple backend for an Angular 2 App. I have implemented a middleware that checks whether the user ha ...

Angular2 - Anticipating the arrival of data from an observable

When working with Angular2 templates, it seems like they handle waiting for a list to return from an observable just fine. For example: <li *ngFor="let product of products"> {{product.DisplayProductName}} </li> ... export class Public ...

An unexpected error occurs when attempting to invoke the arrow function of a child class within an abstract parent class in Typescript

Here is a snippet of code that I'm working on. In my child class, I need to use an arrow function called hello(). When I try calling the.greeting() in the parent class constructor, I encounter an error: index.ts:29 Uncaught TypeError: this.hello is ...

Switch up your component button in Angular across various pages

I've created a new feature within a component that includes a toolbar with multiple buttons. Is there a way to customize these buttons for different pages where the component is used? Component name <app-toolbar></app-toolbar> Component ...

In search of assistance with resolving a React Typescript coding issue

I need help converting a non-TypeScript React component to use TypeScript. When attempting this conversion, I encountered the following error: Class 'Component' defines instance member function 'componentWillMount', but ext ...

The input type '{}' does not match the expected type 'Readonly<IIdeasContainerProps>'. The property '...' is not found in the type '{}'

Having recently started using TypeScript, I'm encountering some issues when attempting to execute this code snippet. Error The error message reads as follows: Failed to compile 13,8): Type '{}' is not assignable to type 'Readonly &l ...

The error message "Uncaught ReferenceError: exports is not defined and require" indicates that

I am currently developing an app using angularjs and typescript, but I've encountered a persistent error that has me stumped. Below is the snippet of my code: export var NgApp = new application.Startup(); ///<reference path="../../../../../typin ...

Angular 2 GET request returns a 404 error

I have been attempting to reproduce the ngPrime datatable demo from this Github repository. Currently, I am working with the most recent version of Angular (4) and using angular-cli in development mode. Placing a JSON file into my app folder where the serv ...

Jest identifies active handles when executing synchronous scrypt operations in the crypto module of Node.js

During the execution of a unit test using the scryptSync function from the crypto package, I am encountering error messages and warnings that are unfamiliar to me. For instance, here is an example of a unit test I am running in Jest: it('Should match ...

The click event is activated following the :active selector being triggered

My Angular application features a button with a slight animation - it moves down by a few pixels when clicked on: &:active { margin: 15px 0 0 0; } The button also has a (click)="myFunction()" event listener attached to it. A common issue arises w ...

Learn how to resubscribe and reconnect to a WebSocket using TypeScript

In my Ionic3 app, there is a specific view where I connect to a websocket observable/observer service upon entering the view: subscribtion: Subscription; ionViewDidEnter() { this.subscribtion = this.socket.message.subscribe(msg => { let confi ...

Maximizing Azure Web App capabilities to host multiple applications

I have developed an app using ASP .NET Core MVC + Angular and now I need to deploy it for three separate customers. Each customer currently has their own database. Is it feasible to create multiple sites within a single Azure web app (such as mysite.com/ ...

Event triggered by clicking on certain coordinates

Just starting with @asymmetrik/ngx-leaflet and Angular, so this might be a beginner's issue... I'm working on an Angular.io (v5) project that incorporates the @asymmetrik/ngx-leaflet-tutorial-ngcli Currently, I'm trying to retrieve the coo ...

Transforming JSON in Node.js based on JSON key

I am having trouble transforming the JSON result below into a filtered format. const result = [ { id: 'e7a51e2a-384c-41ea-960c-bcd00c797629', type: 'Interstitial (320x480)', country: 'ABC', enabled: true, ...

Transform a date string into a date entity

Collecting the user's input for the date and saving it as a string variable. The format of the value is Fri Aug 27 2021 00:00:00 GMT+0530 (India Standard Time) My goal is to convert this string back into a new Date() object in order to make additiona ...

Generating step definitions files automatically in cucumber javascript - How is it done?

Is there a way to automatically create step definition files from feature files? I came across a solution for .Net - the plugin called specflow for Visual Studio (check out the "Generating Step Definitions" section here). Is there something similar avail ...

How to Share Angular Modules Between Two Projects with Ivy Compilation Necessity

Query: I am faced with the challenge of sharing common modules between two Angular projects, one of which requires full Ivy compilation to function properly. To manage these shared resources, we have set up a private GitHub NPM repository. However, becaus ...

Guide to showcasing images dynamically in Angular using .NET Core API and database

I am looking for a way to showcase an image that is stored in the database. Below is the code snippet showing how the image file gets uploaded to the database. public string UploadImage(IFormFile file) { if (file == null) thro ...

What is the best way to transfer the API Response Time from one Fetch function to a separate asynchronous function?

After successfully obtaining the API Response Time (duration) using the 'makeAPICall' function, I am now faced with the task of passing this duration variable value to another asynchronous function. Can anyone assist me in finding a solution to a ...