首页 > 解决方案 > 单击按钮时从 DIV 表中删除行

问题描述

我有以下 divTable:

<div class="divTable">
        <div class="divTableBody">
                <div class="divTableRow">
                        <div class="divTableCell">TagName</div>
                        <div class="divTableCell">Higher/Lower</div>
                        <div class="divTableCell">Threshold</div>
                        <div class="divTableCell">Delete Alert?</div>
                </div>
                <div class="divTableRow" *ngFor="let com of currentAlerts">
                        <div class="divTableCell">{{com.tagname}}</div>
                        <div class="divTableCell">{{com.symbol == 1 ? 'Higher than' : 'Lower than'}}</div>
                        <div class="divTableCell">{{com.threshold}}</div>
                        <div class="divTableCell">
                           <button mat-stroked-button color="primary" (click)="submit(com.ID)">
                              Delete
                           </button>
                        </div>
                </div>
        </div>

如您所见,该表循环遍历数组currentAlerts并为找到的每个项目创建一行。

该数组ngOnInit()通过连接到 Web API 来填充。

this.alerts.getCurrentAlerts(this.loginEmail)
      .subscribe
      ((data: CurrentAlerts[]) => {this.currentAlerts = data;
        console.log(this.currentAlerts.length)
        if(!this.currentAlerts || !this.currentAlerts.length){
          this.alertsTitleMessage = "You have no alerts configured."
        }else{
          this.alertsTitleMessage = "Here are the Alerts you have set up "
        }}
      );

单击删除按钮时,将向数据库发送删除请求。

  submit(ID){
    let isDeleted = null;
    this.alerts.deleteCurrentAlert(ID).subscribe(result => isDeleted = result);
    this.manageCurrentAlerts();
    
  }

以上所有操作都按预期工作,并且数据已从数据库中删除。

问题

如何让表格删除已删除的行?我已经阅读了使用该状态从 arra 中删除该行的答案,splice但我无法使其正常工作。

标签: htmlangulartypescript

解决方案


  • 加入,index_ngFor*ngFor="let com of currentAlerts;let i = index"
  • 在删除按钮中,传递indexiei而不是com.ID
  • splice在 TS 功能中使用,this.currentAlerts.splice(index,1)

试试这样:

<div class="divTableRow" *ngFor="let com of currentAlerts;let i = index">
  ...
  <div class="divTableCell">
    <button mat-stroked-button color="primary" (click)="submit(i)">Delete</button>
  </div>
</div>

TS

submit(index){
  this.currentAlerts.splice(index,1)
  ...

}

推荐阅读