2017-03-08 108 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>