简体   繁体   中英

How do ngfor to set a dynamic function in Angular 8?

i have this in my html component:

<div>
    <button (click)="myFunction1()">myFunction1</button>
</div>
<div>
    <button (click)="myFunction2()">myFunction2</button>
</div>
<div>
    <button (click)="myFunction3()">myFunction3</button>
</div>

and in typescript:

myFunction1()
myFunction2()
myFunction3()

but i try to do something like this, but it's not working!

typescript component:

var myFunctions = [
"myFunction1",
"myFunction2",
"myFunction3"
]

html component:

<div *ngFor="let myFunction of myFunctions">
    <button (click)="myFunction()">{{myFunction }}</button>
</div>

Know someone what the solution?

Do you want the function to execute on the button click? Just use the array to hold reference to the functions.

// *.ts
const myFunctions = [
  myFunction1,
  myFunction2,
  myFunction3
]

Then in your template you can bind the click event to the function.

// *.html
<div *ngFor="let myFunction of myFunctions">
    <button (click)="myFunction()">myFunction</button>
</div>

Your example above is just binding the click to a string.

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