首页 > 解决方案 > 如何维护每个 ngFor 项目的按钮状态

问题描述

我在我的角度项目中集成 Trello。每张卡片都有一个开始计时器按钮。假设当用户单击卡片 A 的开始计时器按钮时,该按钮将替换为结束任务按钮。问题在这里结束按钮出现在所有卡片中。如果我单击卡 A 的开始按钮计时器。该按钮应仅在卡 A 上替换。它不应在所有卡上更改图片

在第 1 部分的上图中,当我单击该按钮时,我有开始计时器按钮,它会替换为第 2 部分中显示的结束计时器按钮,但是当我为模式窗口计时并单击另一张卡时,它会在另一张卡上显示结束计时器按钮也。预期的是,如果我单击卡 A 按钮,它应该只替换卡 A 上的卡 B,它应该显示开始计时器按钮。

先感谢您。

以下是我的代码 -

startTimer() {
    this.startFlag = !this.startFlag;
}

activityModal(id, name, due) {
    jQuery("#activityModal").modal('show');

    this.cardDueDate = due;
    this.mainCardName = name;
    this.mainCardId = id;
}

// card iterates
<div class="row justify-content-center no-gutters overflow">
  <section class="list" *ngFor="let item of mainListArr" id="{{item.id}}">
    <header>{{item.name}}</header>
    <article class="card" *ngFor="let card of item.cards">
      <a (click)="activityModal(card.id, card.name,card.due)">
        <header>{{card.name}}</header>
        <div class="detail badge is-due-complete" *ngIf="card.due != null">
          <i class="badge-icon fa fa-clock-o" aria-hidden="true"></i>&nbsp;
          <span class="badge-text">{{card.due | date : 'MMM dd'}}</span>
        </div>
      </a>
    </article>
  </section>
</div>


// modal popup code

<!-- Modal for activity -->
<div class="modal fade" id="activityModal" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="activityModal"
  aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" *ngIf="mainCardName !== ''">{{mainCardName}}</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close" (click)="closeActivityModal()">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <div class="row">
          <div class="col-md-9">
          some code here
           </div>
          <div class="col-md-3 text-center vertical-center">
            <small><u>Card Actions</u></small>

            <button class="btn btn-action mar-t-05" (click)="startTimer()" *ngIf="startFlag">Start Timer</button>
            <button class="btn btn-action mar-t-05" (click)="endTimer()" *ngIf="!startFlag">End Timer</button>

          </div>
        </div>
      </div>
    </div>
  </div>
</div>

标签: javascriptjqueryangularangular-directivengfor

解决方案


这是因为每张卡片中的按钮都有相同的变量来显示或隐藏开始和结束计时器。

最简单的方法是在 startTimer 和 endTimer 函数中发送卡片的索引值,并使用此索引为每张卡片设置唯一的标志值。


推荐阅读