我正在尝试通过 AJAX 将新的 HTML 代码添加到 Angular 5 应用程序,并向元素添加单击事件。但是点击事件没有按预期工作,我无法使用 2 路数据绑定(bind)方式,因为我使用的是 jQuery 数据表插件,并且他将 HTML 添加到 Dom 而不是 Angular 模板。

我已经尝试过:

<button  (click)='myClassFunction()'>Click!</button>  this line does nothing 
<button  onclick='myClassFunction()'>Click!</button>  this line said myClassFunction is undefined 
<button  onclick='this.myClassFunction()'>Click!</button> this line said myClassFunction is undefined

如何将此点击事件绑定(bind)到我的函数?

请您参考如下方法:

Angular 是用 Typescript 编写的。

当您提供或构建应用程序时,此 typescript 应用程序将被编译、缩小并丑化为 native Javascript

这意味着您的

(click)="myClassFunction()" 

将成为类似的东西

onclick="srgu.gferu()" 

正如你所看到的,Angular 不会识别这一点。

使用 JQuery 还是插件并不重要:这就是 Angular 的工作方式

为此,您需要创建窗口函数,或全局函数。

myClassFunction() { 
  // Create your window function, make it tslint compliant 
  window['myWindowClassFunction'] = () => { 
    // Your function's logic here 
  }; 
} 

现在,在附加的 HTML 中,您需要编写

<button  onclick='window.myWindowClassFunction()'>Click!</button> 


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!