Paddy Paddy - 4 months ago 153
AngularJS Question

Sweet Alert using AngularJS 2 and templateing

i have a small app that works great, when not using angualr templating. However i need to now export the code into it. Sweet Alert should be called when a button is clicked. So when the button is called through the template sweet alert is meant to pop up, but nothing happens. I am assuing it is something to do with even binding as the app loads the code after the DOM has intializied.

//app.component.ts

import { Component } from '@angular/core';

@Component({
selector: 'my-app',
template: `
<form>
<button type="button" class="ticket_button">Book</button>
</form>
`
})
export class AppComponent {
//some app logic here
}


//index.html
//i have not included the normal header stuff here, however the my-app class shows the button

<html<body>
<my-app class="main_ticket">Loading...</my-app>
</body></html>

// I have tried to use event binding from Jquery $('.main_ticket').on('change', '.ticket_button', function() {//logic here}, but it also didn't work

<script>
//Sweet Alert call
document.querySelector('button').onclick = function(){
swal("Here's a message!");
};
</script>

Jai Jai
Answer

You have to use Life Cylcle Hooks to get it working:

export class AppComponent implements ngAfterViewInit{
//some app logic here

     ngAfterViewInit(){
       document.querySelector('button').onclick = function(){
          swal("Here's a message!");
       };
     }

}

Or better to use angular2's Standard events:

@Component({
  selector: 'my-app',
  template: `
    <form>
     <button type="button" (click)="popAlert();" class="ticket_button">Book</button>
    </form>
    `
})

Now in the Class:

export class AppComponent {
//some app logic here
    popAlert(){
      swal("Here's a message!");
    }
}