显示/隐藏ngFor Angular中的各种元素

时间:2018-03-21 17:40:36

标签: json angular html-table json-server

我有一个表格,用于显示ngFor中的数据。当我删除一个元素时,我想隐藏它。 我想我必须在我的记录组件hide:boolean中做一个变量,默认情况下是假的,但当我点击od删除按钮时,它变为true。我不知道如何抓住"我表中的这个变量。

<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;
  }

2 个答案:

答案 0 :(得分:1)

这里有两个基本选项:

  1. 将整个记录对象传递给删除功能并切换&#34;隐藏&#34;真的

    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);
    }
    

答案 1 :(得分: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;
        }
    });
 }
相关问题