Search code examples
htmlangularangular9sweetalertsweetalert2

Is it possible to add an entire angular component inside sweet alert 2?


I wanted to know if there is a way to make an angular component open up in a sweet alert box, for example

 Swal.fire(
  {
    HTML: '<app-exampleselector></app-exampleselector>',
  })

what I intended was to use the component selector instead of writing code inside the function, which in turn is not an option cause I intend to use a lot of functions including database service functions as well which makes it quite a bulky code. is there a way to do this? or should I settle on opening the component on a new tab?


Solution

  • the answer is more or less!

    but its not like your example. If you want, you can instantiate the component you desire to be in the alert inside the other component wich you will trigger the alert. put a template ref (#myAlert for instance), get the reference using @ViewChild and pass the reference to the sweetalert on html parameter:

    //app.component.html
    <div style="display: none;"> <!--YOU NEED TO PUT THE COMPONENT INSIDE A HIDDEN DIV-->
    
    <app-my-alert-content #myAlert [inputSomething]="inputSomething"></app-my-alert-content>    
    </div>
    
    ------------------------
    //app.component.ts
    
    import Swal from 'sweetalert2';
    
    @ViewChild('myAlert',{static: false})
    myAlert: ElementRef;
    
    triggerAlert(){
      Swal.fire({
        html: this.myAlert.nativeElement
      });
    }