user35
user35

Reputation: 468

Cannot update template in angular 2 when data is changed

I have a form to insert data to a table. When i delete data from table , the data is removed but the table row is not deleted. It appears that the data is two way binding so data is removed but the html structure remains same.

Component

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();

}

}

Service

@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]
       }
   }  
}

}

Template

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>         

Help me update the html (template) when data changes.

This is the result after I click table : data is gone but row remains

enter image description here

Upvotes: 0

Views: 103

Answers (2)

eko
eko

Reputation: 40647

delete this.student[i] is not the correct way to remove an element from an array in this situation. You need to use splice().

this.student.splice(i, 1);

Also you should do a truthy check when displaying object fields in the template. Otherwise you will get errors like that. Usually safe-navigation operator(?) will do the trick.

Example:

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

Upvotes: 2

mickdev
mickdev

Reputation: 2885

You are actually deleting the object but it's reference remain in the primary array. Try this instead :

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

Upvotes: 2

Related Questions