【问题标题】:Is there any way to bind the function name from a JSON data to the (click) of a button in angular有什么方法可以将函数名称从 JSON 数据绑定到 Angular 按钮的(单击)
【发布时间】:2020-02-24 18:51:02
【问题描述】:

您好,我想动态分配方法名称并使用它们。请帮忙。 我正在尝试类似以下的操作。

<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 是一个数组,我在其中定义 JSON 数据,并在那里定义我的方法名称,以便我可以动态读取调用它。但我无法实现目标。 请帮助解决同样的问题。 这就是我的 ts 文件中的内容

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"
}]

【问题讨论】:

    标签: arrays json angular methods binding


    【解决方案1】:

    试试这样:

    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()
        }
      ];
    

    模板:

    <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>
    

    编辑:

    根据你的评论,你也可以试试这个solution

    【讨论】:

    • 非常感谢您的宝贵回复。它工作正常。我是 Angular 的新手,正在尝试类似上面的东西。现在我正在尝试相同的解决方案,但这次从 ts 文件中导出和数组并获取 undefined.myFunction() 因为 angular 这个关键字。
    • 非常感谢。你是救世主。自最近几天以来,该解决方案与我想要实现的完全相同。非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-01
    • 2017-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多