2017-03-08 101 views
0

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

這是我後點擊表中的結果:數據已經一去不復返了,但仍然排

enter image description here

+0

@echonax,它不關於數據,它關於視圖,數據更新視圖不​​是。 如何刪除該行,單擊刪除時,該視圖是否會再次呈現?我不這麼認爲,那就是爲什麼有空行。 請幫我明白 – user35

+0

你看到錯誤你正在得到正確的?它試圖在你的html中選擇'undefined'的'id'。試試上面鏈接中的第二個解決方案。 – echonax

+0

@echonax,添加數據,點擊刪除:沒有錯誤,再次添加數據點擊:刪除再次生成錯誤, 任何方式,即使我沒有錯誤,空行仍然存在,我想刪除該行。 – user35

回答

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; 
     } 
    } 
} 
2

delete this.student[i]是不是在這種情況下,數組中刪除元素的正確方法。您需要使用splice()

this.student.splice(i, 1); 

此外,您應該在模板中顯示對象字段時進行truthy檢查。否則,你會得到這樣的錯誤。通常安全導航運營商(?)將會做到這一點。

實施例:

<td> {{ x?.id }} </td>