2

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?

2 Answers 2

15

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I find this still to be the way to trigger change detection with Angular 12 in 2021. Using .append() doesn't seem to work still. For small arrays it shouldn't be a major performance hit.
4

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

3 Comments

won't it force angular to re-render the view after each change detection?
Yes, all components that use a the persons object from the persons service would be updated. Why would you not want to change your view if the object(state) of your application has changed? If it didn`t re-render you would be showing false information. Or a past state.
Depending on the size of your application you may consider using ngrx.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.