ripunjoym1998
ripunjoym1998

Reputation: 49

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.

Upvotes: 0

Views: 1090

Answers (1)

Danilo K&#246;rber
Danilo K&#246;rber

Reputation: 910

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.

Upvotes: 1

Related Questions