gog
gog

Reputation: 12978

How to trigger change detection when array object is modified?

In my angular4 app i have a component with a *ngFor directive based in a array:

 <div *ngFor="let person of persons">
   {{person.name}}
   {{person.car}}
 </div>

In the other part of the component im able to delete a car, so in the subscribe of the deleteCar() method i update the persons array to:

 deleteCar(car) {
   this.carService.deleteCar(car).subscribe(() =>  {
   this.persons.filter(obj => obj.car == car.name)
               .forEach(i => i.car = null);
   }
 }

The problem is that the *ngFor loop is not triggered when i modify a existing person object in the persons array. How to solve this?

Upvotes: 2

Views: 5760

Answers (2)

Eduardo Vargas
Eduardo Vargas

Reputation: 9392

The best way to achieve this is to have a behavior subject in a service and accesss it in you component.

So your service class may look like this

@Injectable()
export class PersonService {

private persons=  new BehaviorSubject<any[]>([]);
public persons$ = this.persons.asObservable();//--> You can access this in your component

constructor() {
   //set the persons array here;
}

function deleteCar()//todo  

}

On the component

constructor(private personService: PersonService) {

}



ngOnInit() {
    this.persons= this.personService.persons$//Dont forget to do add the assync pipe or subscribe
}

delete(car){
    this.personService.deleteCar(car);
}

This Should work.

More info in -> https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

Upvotes: 4

Deblaton Jean-Philippe
Deblaton Jean-Philippe

Reputation: 11388

I solve it by destructuring the array. I'm not sure it's the best way to do it.

this.persons = [...this.persons];

As far as it will change the reference of the array, angular will notice that the array has been updated.

Upvotes: 15

Related Questions