0

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.

  • can you provide a stackblitz? – Aakash Garg Oct 01 '21 at 12:58
  • how you are adding that button html in `buttonz` to template? – navnath Oct 01 '21 at 13:00
  • using an Angular DataGrid cellRenderer function that takes in the backend data and decides whether to show or hide this button. if this button is shown, i should call the xyz() function – ripunjoym1998 Oct 01 '21 at 13:04
  • Don't know about `DataGrid cellRenderer` but Since its angular `onClick` should be `(click)` – navnath Oct 01 '21 at 13:04
  • I tried doing that, but then it ignored the function totally and instead treats the function name as a string literal – ripunjoym1998 Oct 01 '21 at 13:07
  • @ripunjoym1998 check this. It will help you https://stackoverflow.com/questions/50778659/ag-grid-cellrender-with-button-click – navnath Oct 01 '21 at 13:25
  • This won’t just work. Angular hasn’t processed that piece of dynamically added html. This could work, but it’s pretty complicated and means you’ll have to ship the compiler in your build. – MikeOne Oct 01 '21 at 13:25

1 Answers1

1

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.

Danilo Körber
  • 858
  • 1
  • 7
  • 27