简体   繁体   中英

Calling a function from an html element present inside a typescript file (Angular)

I am rendering a button based on a certain condition from the backend. The button is rendered from within the ts file home.component.ts

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


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

Now when click on the button, it gives an error saying UncaughtReference: xyz is not defined. xyz() is present in the same typescript file. How do I call this function from within this html element? I am using Angular.

You should use the *ngIf directive:

component.html:

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

component.ts:

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

With this method the button only will be rendered in the DOM when backendLogic is true .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM