sweetalert2 / ngx-sweetalert2

Declarative, reactive, and template-driven SweetAlert2 integration for Angular
MIT License
657 stars 95 forks source link

How to use reactive form with swal ? #177

Closed AntonGrekov closed 4 years ago

AntonGrekov commented 4 years ago

Hi, guys. I am unable to find a way to use swal with angular reactive form. Wasted like 3 hours on this task. Angular 10. Following example from readme file, i encountered error with form validating. I tried going 2 ways: 1) Trying to validate form inside preConfirm function, problem: cannot access my reactive form inside preConfirm function, because this arrows to Swal component, not my current component, hence this.myForm is undefined on Swal compononent 2) Trying to use form buttons for form validation and if validation is good - close Swal modal. Problem: cannot find a way to close swal :(. I tried using @ViewChild('mySwal') with #mySwal on html component. This way:

this.mySwal.close()

is an event emitter, not a function. Using this.mySwal.close.emit() or .emit(undefined) does nothing - swal modal is not closed...

So, how to correctly validate form before closing swal ?

<swal title="Fill the form, rapidly" (confirm)="sendForm(myForm.value)">
  <!-- This form will be displayed as the alert main content
       Targets the alert's main content zone by default -->
  <form *swalPortal [formControl]="myForm">
    ...
  </form>

  <!-- This targets the confirm button's inner content
       Notice the usage of ng-container to avoid creating an useless DOM element inside the button -->
  <ng-container *swalPortal="swalTargets.confirmButton">
    Send ({{ secondsLeft }} seconds left)
  </ng-container>
</swal>
toverux commented 4 years ago

Hi,

If you're passing preConfirm through the template like this [preConfirm]="myPreConfirm", use [preConfirm]="myPreConfirm.bind(this)" instead.

To close the modal, use .dismiss(), not .close.