I have a problem with the change detection of Angular 11 in this case:
I have a map and iterate it in the template using the keyvalues pipe and an additional callback to get the original order of the map and not orderd by key.
But when I change this map the change detection does nothing.
I know that the keyvalues pipe generates a complete new array. So it is clear, that changing references in the map will not trigger the change detection. But why not on changing the complete Map?
Here is some code:
Template:
<ng-container *ngFor="let postMap of mappingMap.events | keyvalue: originalOrder; let i = index">
<ion-slide *ngIf="!postMap.value.isHiddenByFilter" (click)="showSlideActionSheet('events', postMap.key)" class="overview-slide" >
Component:
interface MappingMapvalue {
isHiddenByFilter: boolean;
sliderIndex: number;
}
mappingMap: Map<number, MappingMapvalue>;
pseudyfunction(cpt: string): void {
let newMap: any;
posts: ....................
newMap = [...this.mappingMap[cpt].entries()].sort((a, b) =>
posts[a[0]][key].toLowerCase() > posts[b[0]][key].toLowerCase()
? 1
: posts[b[0]][key].toLowerCase() > posts[a[0]][key].toLowerCase() ? -1 : 0
);
this.mappingMap[cpt] = new Map(newMap); // Why no change detection here? This is a complete new Map! Same properties but another order
}
originalOrder = (a: KeyValue<number,MappingMapvalue>, b: KeyValue<number,MappingMapvalue>): number => 0;
Is anyone able to ecplain why the change detectin does not trigger when the map is new initialized?
The change detection triggers, if I do this:
const newMap2 = new Map();
newMap2.set(700, {isHiddenByFilter: true, sliderIndex: 0});
this.mappingMap[cpt] = newMap2;
But why then and not on changing the complete map?
An additional question is:
This does not trigger change detection:
this.mappingMap[cpt] = new Map(newMap);
this.mappingMap[cpt].set('newdummyfield', {isHiddenByFilter: true, sliderIndex: undefined});
this.mappingMap[cpt].delete('newdummyfield');
But this triggers it: (This does not make sense in scenario, but I wanted to test it)
this.mappingMap[cpt] = new Map(newMap);
this.mappingMap[cpt].set('newdummyfield', {isHiddenByFilter: true, sliderIndex: undefined});
setTimeout(() => {
this.mappingMap[cpt].delete('newdummyfield');
});
Does the change detection wait for the complete synchronous code? Is this the usual behaviour of the change detection?