Angular为按钮动态分配操作(单击)

时间:2019-01-03 08:57:32

标签: angular

我有一个数组来存储要显示的警报。

appLevelAlert

     const alert = {
     message: 'Your account is not activated.'
      + ' Select the link in your email inbox to activate your account',
      actionName: 'Resend Email',
      action: 'resendEmail()'
    };

    this.appLevelAlert = this.appLevelAlert || [];
    this.appLevelAlert.push(alert);

我想将appLevelAlert.action中的resendEmail()分配给按钮的(单击)。

<clr-alert [clrAlertType]="'info'" [clrAlertAppLevel]="true" *ngFor='let alert of clarityAlertService.appLevelAlert'>
<clr-alert-item>
    <span class="alert-text">
        {{alert.message}}
    </span>
    <div class="alert-actions">
        <button class="btn alert-action" (click)="[alert.action]">{{alert.actionName}}</button>
    </div>  
</clr-alert-item>

我不确定是否可行,有人可以帮助我吗?

1 个答案:

答案 0 :(得分:2)

这是一个简化的工作示例:

import { Component } from '@angular/core';

@Component({
   selector: 'my-app',
   template: `<p>{{alert.message}}</p>
   <button type="button" (click)="alert.action()">{{alert.actionName}}</button>`
})
export class AppComponent  {

    readonly alert = {
        message: 'Your account is not activated.',
        actionName: 'Resend Email',
        action: () => this.resendEmail()
    };

    resendEmail() {
        console.log('send email');
    }
}