我有一个向表中插入数据的表单。当我从表中删除数据时,数据将被删除,但表格行不会被删除。 看起来数据是双向绑定的,所以数据被删除,但html结构保持不变。更改数据时无法更新角度2中的模板
组件
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(模板)的数据发生变化时。
这是我后点击表中的结果:数据已经一去不复返了,但仍然排
@echonax,它不关于数据,它关于视图,数据更新视图不是。 如何删除该行,单击删除时,该视图是否会再次呈现?我不这么认为,那就是为什么有空行。 请帮我明白 – user35
你看到错误你正在得到正确的?它试图在你的html中选择'undefined'的'id'。试试上面链接中的第二个解决方案。 – echonax
@echonax,添加数据,点击删除:没有错误,再次添加数据点击:删除再次生成错误, 任何方式,即使我没有错误,空行仍然存在,我想删除该行。 – user35