动态(单击)功能 - Angular2

Ton*_*ler 6 angular

将动态函数绑定到click事件时遇到一些麻烦.请看下面: -

档案1

<title-bar [actions]='[{title: "Create A New Plan", link: "hello"}]' ></title-bar>
Run Code Online (Sandbox Code Playgroud)

档案2

<div class="actions" *ngIf="actions">
    <a *ngFor="let action of actions" class="ui primary button" (click)="[action.link]()">{{action.title}}</a>
</div>
Run Code Online (Sandbox Code Playgroud)

除了在(点击)中绑定action.link之外,所有代码都完美无缺.

如果我创建以下按钮: -

<button (click)="hello()"></button>
Run Code Online (Sandbox Code Playgroud)

它应该调用hello()函数.但由于某种原因,我无法动态地使用它.

有没有人有一个简单的解决方案,我可能已经看过了?

该函数只是为了测试而调用一个简单的警报: -

public hello() {
    alert('test');
}
Run Code Online (Sandbox Code Playgroud)

我试图将点击事件更改为以下但没有任何乐趣: -

(click)="action.link"
(click)="[action.link]()"
(click)="this[action.link]()"
Run Code Online (Sandbox Code Playgroud)

我分别得到以下错误: -

No error, but not function called
inline template:3:2 caused by: ["hello"] is not a function
inline template:3:2 caused by: self.parentView.parentView.context[self.context.$implicit.link] is not a function
Run Code Online (Sandbox Code Playgroud)

任何帮助推动正确方向的人都将非常感激.

Gün*_*uer 10

在您需要的组件中

get self() { return this; }
Run Code Online (Sandbox Code Playgroud)

并在模板中

<a *ngFor="let action of actions" class="ui primary button"
  (click)="self[action.link]()">{{action.title}}</a>
Run Code Online (Sandbox Code Playgroud)

使用

<a *ngFor="let action of actions" class="ui primary button"
  (click)="this[action.link]()">{{action.title}}</a>
Run Code Online (Sandbox Code Playgroud)

  • 使用`(click)="[action.link]()"`你创建一个带有一个项目`action.link`的数组并应用一个函数调用(预计不会起作用).使用`(click)="self [action.link]()"`你引用属性为`self`返回的对象的`action.link`,它是组件类实例(我假设是什么)你要).模板AFAIK中不支持`this`,因此`self`是一种解决方法,可以使`this`可用. (2认同)
  • `this` 现在在模板中可用以引用组件类,因此不再需要 self getter (2认同)