Saud Anjum
Saud Anjum

Reputation: 246

Is there any way to bind the function name from a JSON data to the (click) of a button in angular

Hi I want to assign method name dynamically and use them.Please help. I am trying something like following.

<div class="dashboard row">
<div class="card col-lg-3" *ngFor="let card of cards">
    <h5 class="card-title">{{card.title}}</h5>
    <div class="card-body">
        <ul style="list-style-type:none;">
            <li *ngFor="let cardFeature of cardFeatures" style="padding-left: 7px;">
                <a href="" *ngIf="cardFeature.enable" [routerLink]="cardFeature.link">{{cardFeature.title}}</a>
                <button (click)="[cardFeature.method]">{{cardFeature.method}}</button>
            </li>
        </ul>
    </div>
</div>

CardFeatures is an array where I am defining the JSON data and there I am defining my method name so that I can dynamically read call that. But I am unable to achieve the goal. Please help to resolve the same. This is what I have in my ts file

cardFeatures = [
{
    "name": "id",
    "title": "ID",
    "enable": true,
    "link": "/register",
    "method": "meth1()"
},
{
    "name": "profile",
    "title": "profile",
    "enable": true,
    "link": "/link1",
    "method": "meth2()"
}
]

cards = [
{
  title: "Card1"
},
{
  title: "Card2"
}]

Upvotes: 2

Views: 455

Answers (1)

Adrita Sharma
Adrita Sharma

Reputation: 22203

Try like this:

Working Demo

 cardFeatures = [
    {
      name: "id",
      title: "ID",
      enable: true,
      link: "/register",
      method: () => this.meth1()
    },
    {
      name: "profile",
      title: "profile",
      enable: true,
      link: "/link1",
      method: () => this.meth2()
    }
  ];

Template:

<div class="card-body">
    <ul style="list-style-type:none;">
        <li *ngFor="let cardFeature of cardFeatures" style="padding-left: 7px;">
            <a href="" *ngIf="cardFeature.enable" [routerLink]="cardFeature.link">{{cardFeature.title}}</a>
            <button (click)="cardFeature.method()">Test</button>
        </li>
    </ul>
</div>

EDIT:

As per your comment, you can also try this solution

Upvotes: 1

Related Questions