My view does not update when i change my array in *ngFor
ChangeDetectorRef
will do the trick.
Inject him in the constructor.
constructor(
...
private cdr: ChangeDetectorRef,
...
) { }
edit getSale1
like this in order to use the cdr:
getSale1() {
this.customersService.getSale1()
.subscribe(
dataList => {
this.updateDataTable(dataList);
this.cdr.detectChanges();
}
)
}
But why I have to use the ChangeDetectorRef?
Angular, by default, use the ChangeDetectionStrategy.default
that use its logic to "wake-up" the component for the render. More spec here: https://angular.io/api/core/ChangeDetectionStrategy
There are certain cases where this isn't enough. One case could be a very big nested *ngFor
.
So why use the cdr?
As I said, there are some cases when Angular does not wake up its renderer. Since every situation is not the same, it's quite impossibile to define an absolute answer to this. What cdr.detectChanges()
does, is to allow the method to inform the Angular's rendered to force the render of its component.html. In this way, no matter which strategy
are you using (even if it's .onPush
) the component will be re-rendered.
But be careful. you have to think what you are doing before implementing this. For example, re-render the html fire the ngOnChanges
event. So you could enter an endless loop.
More info about cdr: https://angular.io/api/core/ChangeDetectorRef
Hope that this cleared out some doubts.
Use a custom trackby function with a unique return statement (for instance, IDs are supposed to be unique, or you can track on the property you change)
*ngFor="let data of mySaleModelArray2; trackBy: customTB"
customTB(item, index) {
return `${item.id}-${index}`;
}