0

我有一个表格,它在 ngFor 中显示数据。当我删除一个元素时,我想隐藏它。我想我必须在我的记录组件中做一个hide:boolean默认情况下为假的变量,但是当我单击 od delete 按钮时,它会变为真。我不知道如何在我的表中“捕获”这个变量。

<table>
  <thead>
    <tr>
      <th>
        Id
      </th>
      <th> 
        Name
      </th>
      <th>
        Surname
      </th>
      <th>
        Actions
      </th>
    </tr>
  </thead>
  <tbody>
    <tr sl-record *ngFor="let recordElement of records" [record]="recordElement" [hidden]="recordElement.hide"></tr>
  </tbody>
</table>

还有我的记录组件:

<td>{{record.id}}</td>
<td>{{record.name}}</td>
<td>{{record.surname}}</td>
<td>
  <div class="btn-group btn-group-sm" role="group" aria-label="Actions">
    <button type="button" class="btn btn-danger" (click)="removeRecord(record.id)">
      <i class="fa fa-trash-o" aria-hidden="true"></i> Remove
    </button>
  </div>
</td>

我究竟做错了什么?我的数据在 json 文件中,由 json-server 连接。http.delete()我用功能删除记录。它从我的文件中删除,但表不会自行重新加载。

记录组件,removeRecod 函数:

removeRecord(id) {
    var url = this.data_url + "/" + id;
    this.http.delete(url).subscribe();
    this.hide = true;
  }
4

2 回答 2

1

这里有两个基本选项:

  1. 将整个记录对象传递给删除函数并将“隐藏”切换为 true

    removeRecord(record) {
       record.hide = true;
       let id = record.id;
       // do whatever to delete on server
    }
    
  2. (更好)从列表本身中删除记录,而不是试图隐藏它。

    removeRecord(id) {
       //do whatever to delete the record on server
    
       let recordIndex = this.records.findIndex(r => r.id === id);
       this.records = this.records.splice(recordIndex, 1);
    }
    
于 2018-03-21T17:53:19.797 回答
0

您只有对象的 id。这样做:

 removeRecord(id: number){
    var url = this.data_url + "/" + id;
    this.http.delete(url).subscribe();

    this.records.forEach(element => {
        if(element.id === id){
          element.hide = true;
        }
    });
 }
于 2018-03-21T17:51:39.260 回答