如何通过 *ngFor 插入函数调用,而此调用是从我正在迭代的数组中插入的字符串?
我的数组包含用户操作列表,这些操作由其函数名称(以及其他名称)描述。该模板有一个部分应使用 Ionic 的 ion-fab
指令列出每个用户条目的这些操作。我不想写下每个操作,而是使用 *ngFor
迭代列表,并将每个函数名称插入到 (click)
属性中。
不过,我当前的解决方案不起作用。
这是我的代码:
类别
constructor(
public navCtrl: NavController,
public navParams: NavParams,
private usersProv: Users
) {
this.userActions = [
{
'label' : 'Edit',
'function' : 'editUser',
'icon' : 'ios-create-outline',
'color' : 'primary'
},
{
'label' : 'Remove',
'function' : 'removeUser',
'icon' : 'ios-trash-outline',
'color' : 'yellow'
},
{
'label' : 'Send message',
'function' : 'sendMessageToUser',
'icon' : 'ios-send-outline',
'color' : 'secondary'
}
];
console.info('userActions', this.userActions);
}
模板
<ion-fab right>
<button ion-fab mini color="light">
<ion-icon name="ios-arrow-dropleft"></ion-icon>
</button>
<ion-fab-list side="left">
<div *ngFor="let action of userActions">
<button ion-fab mini color="{{action.color}}" title="{{action.label}}" (click)="action.function(user)">
<ion-icon name="{{action.icon}}"></ion-icon>
</button>
</div>
</ion-fab-list>
</ion-fab>
这是我得到的错误:
ERROR TypeError: "_v.context.$implicit.function is not a function"
使用大括号插入 ((click)="{{action.function}}(user)"
) 也没有帮助。那么错误是:
`ERROR Error: "Uncaught (in promise): Error: Template parse errors: Parser Error: Got interpolation ({{}}) where expression was expected at column 0 in [{{action.function}}(user)]`
这可能吗?
是否建议按照我的方式来处理它?</p>
提前致谢!
最佳答案
您应该保存对函数的引用,而不是使用字符串,如下所示
userActions = [
{
'label' : 'Edit',
'function' : this.editUser.bind(this),
'icon' : 'ios-create-outline',
'color' : 'primary'
},
{
'label' : 'Remove',
'function' : this.removeUser.bind(this),
'icon' : 'ios-trash-outline',
'color' : 'yellow'
},
{
'label' : 'Send message',
'function' : this.sendMessageToUser.bind(this),
'icon' : 'ios-send-outline',
'color' : 'secondary'
}
];
这里我使用了bind
,因此当我们调用该函数时,我们不会丢失this
的上下文。
然后,在 HTML 中,您可以这样调用它:
<button (click)="a.function(user)">{{a.label}}</button>
关于arrays - ionic 和 Angular : Inserting Function Names with ngFor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52570977/