【问题标题】:Calling a function from an html element present inside a typescript file (Angular)从打字稿文件中的html元素调用函数(Angular)
【发布时间】:2021-11-23 02:59:30
【问题描述】:

我正在根据后端的特定条件渲染一个按钮。该按钮是从 ts 文件中呈现的 home.component.ts

if(backendLogic is true)
{
const buttonz = '<button onClick="xyz()"> Click me</button>';
return buttonz; 
}


xyz()
{
  console.log("haha");
}

现在当点击按钮时,它会给出一个错误提示 UncaughtReference: xyz is not defined。 xyz() 存在于同一个打字稿文件中。 如何从这个 html 元素中调用这个函数? 我正在使用 Angular。

【问题讨论】:

  • 你能提供一个stackblitz吗?
  • 您如何将buttonz 中的按钮html 添加到模板中?
  • 使用 Angular DataGrid cellRenderer 函数接收后端数据并决定是否显示或隐藏此按钮。如果显示此按钮,我应该调用 xyz() 函数
  • 不知道DataGrid cellRenderer,但由于它的角度onClick应该是(click)
  • 我试过这样做,但后来它完全忽略了函数,而是将函数名视为字符串文字

标签: javascript html angular typescript


【解决方案1】:

你应该使用 *ngIf 指令:

component.html:

<button *ngIf="backendLogic" onClick="xyz()">Click me</button>

component.ts:

xyz()
{
  console.log("haha");
}

只有当backendLogictrue 时,此方法才会在DOM 中呈现按钮。

【讨论】:

    猜你喜欢
    • 2016-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-29
    • 2017-11-23
    • 2021-09-01
    • 1970-01-01
    相关资源
    最近更新 更多