簡體   English   中英

Angular ,如何在單擊按鈕時隱藏表格行

[英]Angular , How to hide a table row on click of a button

我有一個表格,其中每一行都有一個刪除按鈕。 單擊按鈕后,數據將被刪除。 但是要驗證記錄是否已刪除,我必須刷新頁面。 我想在單擊刪除按鈕時隱藏當前行。 這是我的代碼。

<table>
    <tr>
        <th>Delete</th>
        <th>Id</th>
        <th>Name</th>
    </tr>
    <tr *ngFor="let person of people" *ngIf="!hideRow">
        <td><button (click)="delete(person.id)" title="Delete">Delete</button></td>
        <td>person.Id</td>
        <td>person.Name</td>
    </tr>
</table>

在我的 component.ts 刪除時,我更改了 hideRow 的值

delete(id) {  
  this.hideTr = true;
  this.personService.delete(id).subscribe(p=> console.log(p));
}

hideRow 是一個布爾變量,默認值為 false。 問題是當我點擊刪除時,所有的行都被隱藏了(當然)。 如何只引用當前行?

簡單但更有效:

模板端:

<tr *ngFor="let person of people" *ngIf="!person?.hideRow">
    <td><button (click)="delete(person)" title="Delete">Delete</button></td>
    <td>person.Id</td>
    <td>person.Name</td>
</tr>

組件端:

delete(person) {  
  person.hideRow = true;
  this.personService.delete(person.id).subscribe(p=> console.log(p));
}

無需更改用戶(屬性)界面

模板端:

<tr *ngFor="let person of people;let i = index;">
    <td><button (click)="delete(i , person.id)" title="Delete">Delete</button></td>
    <td>person.Id</td>
    <td>person.Name</td>
</tr>

組件端:

delete(index , id) {  
    this.people.splice(index, 1);
    this.personService.delete(id).subscribe(p=> console.log(p));
}

當您想刪除該行時,您應該實際刪除它而不是隱藏行。 不需要*ngIf="!hideRow" 您無需刷新頁面,這就是 AngularJS 的美妙之處。 下面是刪除特定行的代碼。 傳遞行的$index

HTML代碼:

<table>
    <tr>
        <th>Delete</th>
        <th>Id</th>
        <th>Name</th>
    </tr>
    <tr *ngFor="let person of people">
        <td><button (click)="delete($index)" title="Delete">Delete</button></td>
        <td>person.Id</td>
        <td>person.Name</td>
    </tr>
</table>

JavaScript 代碼:

// delete row
$scope.delete = function(index) {
    $scope.people.splice(index, 1);
};

根據您提供的代碼,我將刪除此部分*ngIf="!hideRow"並將其添加到您的組件中

delete(id) {  
    this.personService.delete(id).subscribe(p=> {
        console.log(p);
        this.people.filter( person => person.id !== id)
        // or you can use splice by using the index
    });
}

現在你的 html 更簡單,不需要使用*ngIf

<table>
    <tr>
        <th>Delete</th>
        <th>Id</th>
        <th>Name</th>
    </tr>
    <tr *ngFor="let person of people">
        <td><button (click)="delete(person.id)" title="Delete">Delete</button></td>
        <td>person.Id</td>
        <td>person.Name</td>
    </tr>
</table>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM