当不使用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>
您必须使用救生圈挂钩才能使其正常工作:
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!");
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句