Generate different (click) attributes in a ngFor loop of buttons from array

Viewed 3796

I have a JSON file from which I get configuration to generate an array of buttons in a toolbar.

In each record, I store information about each button, as well as the class, the icon ... and I also want to set in each button the method that will trigger through the event (click)

How do I generate each button in the view with its click event?

It is an angular component that generates a toolbar based on the information it receives from this JSON file

I need something like:

HTML

<mat-button-toggle-group>
    <mat-button-toggle *ngFor="let tool of tools">
      <button [click]="tool.click"><i [class]="tool.class"></i></button>
    </mat-button-toggle>
  </mat-button-toggle-group>

Array (JSON file)

tools =
  [
    { id: 0, class: 'fas fa-sign-out-alt', click: 'addPizza()'},
    { id: 1, class: 'fas fa-arrow-left', click: 'removePizza()' },
    { id: 2, class: 'far fa-sticky-note', click: 'updateGrid()' }
  ];

Expected: Generate a group of buttons within each button has a specific method

2 Answers

Make two changes, In Template replace [click]="tool.click" with (click)="tool.click()" and in TS, make click property a function

Try like this:

TS:

tools =
  [
    { id: 0, class: 'fas fa-sign-out-alt', click: () => this.addPizza()},
    { id: 1, class: 'fas fa-arrow-left', click: () => this.removePizza() },
    { id: 2, class: 'far fa-sticky-note',click: () => this.updateGrid() }
  ];

Template:

 <button (click)="tool.click()"><i [class]="tool.class"></i></button>

Finally I solved by another way,

Basically it was not working because i was retrieving the information by an input in the component, not by a direct variable within the component itself (I omitted this fact in my question).

So finally I created a method in the component that handle the function triggered depending on the string setted on the click property in the JSON file:

JSON:

tools =
  [
    { id: 0, class: 'fas fa-sign-out-alt', click: 'addPizza'},
    { id: 1, class: 'fas fa-arrow-left', click: 'removePizza' },
    { id: 2, class: 'far fa-sticky-note', click: 'updateGrid' }
  ];

HTML:

<div>
<button *ngFor="let tool of tools" (click)="handleClick(tool.click)">
  <i [class]="tool.class" ></i>
</button>

Component:

  handleClick(method: string) {
   switch (method) {
     case 'addPizza':
     this.addPizza();
    break;
     case 'removePizza':
     this.removePizza();
    break;
     case 'updateGrid':
     this.updateGrid();
    break;

  default:
    break;
}

}

Related