【问题标题】:Sweet Alert using AngularJS 2 and templateing使用 AngularJS 2 和模板的甜蜜警报
【发布时间】:2016-07-26 16:31:23
【问题描述】:

我有一个小应用程序,在不使用 angualr 模板时效果很好。但是我现在需要将代码导出到其中。单击按钮时应调用 Sweet Alert。因此,当通过模板调用按钮时,甜蜜警报意味着弹出,但没有任何反应。我假设它与绑定有关,因为应用程序在 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>

【问题讨论】:

  • 种马的好点;在大多数情况下,您不应该使用 jQuery 包,而是尝试查找您正在使用的库的 angular 包。几乎总是有一个可用的。
  • 顺便说一句:Sweetalert2 现在原生支持 typescript。

标签: javascript angularjs sweetalert


【解决方案1】:

您必须使用 Life Cycle 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!");
    }
}

【讨论】:

  • 我花了两天的时间在这上面敲我的脑袋。非常感谢,您对 Angular 2 资源有什么建议吗?超出官方文档?
  • 好吧,我关注了一些在线视频并阅读了试图在那里的文档,但在 angular2 中仍然是婴儿。
猜你喜欢
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-25
  • 1970-01-01
  • 1970-01-01
  • 2018-09-29
相关资源
最近更新 更多