TypeScript Angular:您是否可以使用对象属性作为其值的(单击)事件?

时间:2018-12-03 15:57:36

标签: html angular typescript

我正在尝试创建动态错误卡,该错误卡具有不同的错误消息和重试按钮。

这是我的打字稿对象的摘要:

errorCard: any = [];
if(error){
     this.errorCard.errorMessage = "oops try again" 
     this.errorCard.buttonFunc = "retry()";
}

现在这是我的观点:

  <div class="card-block">
       <div class="card-media-block wrap">
           <div class="card-body">
              <span class="card-media-title">
                  {{errorCard.errorMessage}} // works as expected
              </span>
              ...
            <div class="card-footer"> 
                   //this click is where I would like it to call the function that is tied to that property in this case retry() 
                <button (click)="errorCard.buttonFunc"><i class="fas fa-redo-alt"></i> Retry</button>
            </div>

与此相关,我在控制台中未收到任何错误,并且该函数也未触发。

在此先感谢你们的帮助!

1 个答案:

答案 0 :(得分:1)

假设您的组件是这样的:

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

@Component({...})
export class YourComponent {
  errorCard = {};

  ...

  retry() {
    console.log('Retry Got Called');
  }
}

为什么不简单地这样调用retry方法(<button (click)="retry()">Retry</button>

<div class="card-block">
    <div class="card-media-block wrap">
        <div class="card-body">
            <span class="card-media-title">
        {{errorCard.errorMessage}} // works as expected
      </span>
      ...
      <div class="card-footer"> 
        //this click is where I would like it to call the function that is tied to that property in this case retry() 
        <button (click)="retry()"><i class="fas fa-redo-alt"></i> Retry</button>
      </div>
        </div>
    </div>
</div>

尝试Working Sample StackBlitz