我有一个小应用程序,在不使用 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/