我有一个表,其中每行都有一个删除按钮。点击按钮,数据被删除。但是,为了验证记录是否已删除,我必须刷新页面。我想在点击删除按钮时隐藏当前行。这是我的代码。
<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。问题是,当我点击删除时,所有行都会被隐藏(当然)。我怎样才能直接引用当前行?
答案 0 :(得分:2)
简单而有效:
模板面:
<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));
}
答案 1 :(得分:1)
如果要删除该行,则应将其删除,而不是隐藏行。不需要*ngIf="!hideRow"
。你不需要刷新页面,这是AngularJS的美丽。下面是删除特定行的代码。通过该行的$index
:
HTML code:
<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);
};
答案 2 :(得分: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>