javascript - 使用 AngularJS 2 和模板的 Sweet Alert

标签 javascript angularjs sweetalert

我有一个小应用程序,在不使用 angualr 模板时运行良好。但是我现在需要将代码导出到其中。单击按钮时应调用 Sweet Alert。因此,当通过模板调用按钮时,甜蜜警报会弹出,但什么也没有发生。我保证它与甚至绑定(bind)有关,因为应用程序在 DOM 初始化后加载代码。

//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>

最佳答案

您必须使用Life Cylcle Hooks 才能使其正常工作:

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

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

}

或者更好地使用 angular2 的标准事件:

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

现在在类里面:

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

关于javascript - 使用 AngularJS 2 和模板的 Sweet Alert,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38584563/

相关文章:

javascript - 将 rowdata 标记从 javascript 传递到 servlet

JavaScript 日期和时间显示错误

javascript - karma 测试中未定义预期范围变量

javascript - $routeProvider 和 angularJS?

javascript - 带图像的 HTML/CSS 模态对话框(Sweetalert 或其他)

javascript - jQuery addClass() 在还使用 attr ("href"时不起作用,有些东西)

javascript - 等到canvas.toBlob()完成?

javascript - angular.js - 命名表单不起作用

android - 更改 Sweet alert 中的按钮样式

javascript - Sweet Alert确认对话框在响应之前消失?