Angular 将按钮动作作为参数传递
我想在我的Angular 将按钮动作作为参数传递,angular,typescript,data-binding,Angular,Typescript,Data Binding,我想在我的html模板中从一组对象动态生成按钮,如下所示: typescript private buttons: ButtonType[] = []; ngOnInit(){ let button: ButtonType = new ButtonType(); button.name = "HOMEPAGE"; button.clazz = "btn-blue"; button.action = "goHome()"; this.buttons.p
html
模板中从一组对象动态生成按钮,如下所示:
typescript
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>
{{b.name}
除了
操作
部分之外,它似乎工作得很好,但没有任何作用。它在(单击)
部分中完全不渲染。是否有一种绑定方式可以将b.action
参数解释为一种方法,就像我在html
页面中写入(单击)=“goHome()”
一样?此时,您正在向其传递函数名称,而不是函数/引用
您需要做的是:
button.action = goHome()
您还可以传递注释性函数:
通过执行此操作,您将向模板传递对给定函数的引用,单击按钮后将调用该函数。您只需:
更改button.action=“goHome()”代码>至按钮。操作=“goHome”代码>
及
(单击)=“b.action”
到(单击)=“this[b.action]()”
进行以下更改:
//Components
button.action = this.goHome
//View
(click)="b.action()"
您可以尝试使用button.action=goHome代码>(无引号,无括号)和(单击)=“b.action()”
(括号)。它应该可以工作,但不确定,因为TypeScriptThank,这正是我所需要的。@esseara,很高兴知道,很高兴编码顺便说一句;)
//Components
button.action = this.goHome
//View
(click)="b.action()"