【问题标题】:Pass button action as parameter将按钮操作作为参数传递
【发布时间】:2018-02-14 10:23:00
【问题描述】:

我想在我的html 模板中从一组对象动态生成按钮,如下所示:

打字稿

private buttons: ButtonType[] = [];

ngOnInit(){

    let button: ButtonType = new ButtonType();

    button.name = "HOMEPAGE";
    button.clazz = "btn-blue";
    button.action = "goHome()";
    this.buttons.push(button);
  }

private goHome() {
    this.router.navigate(["/"]);
  }

html

<button *ngFor="let b of buttons" type="button" [class]="b.clazz" (click)="b.action">{{b.name}}</button>

除了action 部分之外,似乎运行良好,它什么都不做。 (click) 部分根本没有渲染。是否有一种绑定方式可以将b.action 参数解释为一种方法,就像我在html 页面内写(click)="goHome()" 一样?

【问题讨论】:

  • 您可以尝试使用button.action = goHome;(无引号,无括号)和(click)="b.action()"(括号)。它应该可以工作,但由于打字稿而不确定

标签: angular typescript data-binding


【解决方案1】:

您只需要:

button.action = "goHome()"; 更改为button.action = "goHome";

(click)="b.action"(click)="this[b.action]()"

WORKING DEMO

【讨论】:

  • 谢谢,这正是我所需要的。
  • @esseara ,很高兴知道,快乐编码顺便说一句 ;)
【解决方案2】:

此时您正在传递函数 name 而不是函数/引用。

你需要做的是:

button.action = goHome()

你也可以通过匿名函数

button.action = function(){console.log('function called');}

通过执行此操作,您将向模板传递给定函数的引用,单击按钮后将调用该函数。

【讨论】:

    【解决方案3】:

    进行这些更改:

    //Components
    button.action = this.goHome
    
    //View
    (click)="b.action()"
    

    【讨论】:

      猜你喜欢
      • 2022-01-17
      • 2022-11-05
      • 2011-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-22
      相关资源
      最近更新 更多