我有一个表格可以将数据插入表格。当我从表中删除数据时,数据将被删除,但表行不会被删除。 看来数据是双向绑定的,因此数据被删除但html结构保持不变。
组件
export class HomeComponent implements OnInit {
studentform = new FormGroup({
id: new FormControl(),
name: new FormControl(),
address: new FormControl()
});
student: Student[]=[];
std: Student= new Student();
constructor(public homeService: HomeService){ }
OnInit(){
this.getData();
}
getData(){
this.student = this.homeService.GetData();
}
onEdit(id:number){
console.log("Edit:" + id);
}
onDelete(id:number){
this.homeService.delete(id);
this.getData();
}
Save(model:Student){
this.homeService.SaveData(model);
this.studentform.reset();
this.getData();
}
}
服务
@Injectable()
export class HomeService{
student:Student[]=[];
SaveData(model:Student){
this.student.push(model);
}
GetData(){
return this.student;
}
delete(id:number){
for(var i=0;i<this.student.length;i++){
if(this.student[i].id==id){
delete this.student[i]
}
}
}
}
模板
div class="col-md-6">
<h5> Lists </h5>
<table>
<th>ID </th>
<th>Name </th>
<th>Address </th>
<th>Edit </th>
<th>Delete </th>
<tr *ngFor="let x of student">
<td> {{ x.id }} </td>
<td> {{ x.name }} </td>
<td> {{ x.address }} </td>
<td (click)="onEdit(x.id)"> Edit </td>
<td (click)="onDelete(x.id)"> Delete </td>
</tr>
</table>
帮助我在数据更改时更新html(模板)。
这是我点击表后的结果:数据消失但行仍然是
答案 0 :(得分:2)
delete this.student[i]
不是从数组中删除元素的正确方法。您需要使用。
this.student.splice(i, 1);
在模板中显示对象字段时,也应该进行真正的检查。否则你会得到这样的错误。通常,安全导航操作员(?
)可以解决问题。
示例:
<td> {{ x?.id }} </td>
答案 1 :(得分:2)
您实际上正在删除该对象,但它的引用仍保留在主数组中。试试这个:
delete(id:number){
for(var i=0;i<this.student.length;i++){
if(this.student[i].id==id){
this.student.splice(i, 1); //delete this.student[i]
break;
}
}
}