我有一個向表中插入數據的表單。當我從表中刪除數據時,數據將被刪除,但表格行不會被刪除。 看起來數據是雙向綁定的,所以數據被刪除,但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