简体   繁体   中英

how to bind dynamic function on HTML element using angular 6?

I am trying to bind the event on the dynamically created element. I am quite successful but I am not able to bind the function to the event. here is my code

.ts code

 data = ['fn1()', 'fn2()', 'fn3()'];
 fn1() { alert(1) }
  fn2() { alert(2) }
  fn3() { alert(3) }

html code

   table>
  <ng-container *ngFor='let d of data'>
    <tr (click)=d>
      <td>
        :) !!!
      </td>
    </tr>
  </ng-container>

but, when I add the function statically then it is getting called, ie.

<table>
  <ng-container *ngFor='let d of data'>
    <tr (click)=fn1()>
      <td>
        :) !!!
      </td>
    </tr>
  </ng-container>

</table>

this works, can anyone help me on this?

You want an array of functions, not an array of strings. And you want to call the function when the div is clicked:

TypeScript:

fn1 = () => { alert(1) };
fn2 = () => { alert(2) };
fn3 = () => { alert(3) };
data = [this.fn1, this.fn2, this.fn3];

HTML:

<div (click)="d()">

Demo

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