I have a map component which has a video component inset on it. The map and video component switch classes when the video is clicked, so the video becomes fullscreen with the map inset on it.
I'm updating the class of both components using NgClass, but I noticed the class section of the map element flickering in the inspector while running my app in Chrome.
I checked it out, and it seems that ngClass is constantly updating the class from the moment the app starts, even though no changes are made to the component. I only want to change the class when the inset element is clicked.
Is this normal behaviour? Is there anything I can do to stop it?
Here's my HTML:
<map class="map" (click)="switchInset('map')" [ngClass]="setClass('map')"></map>
<app-video class="video" (click)="switchInset('video')" [ngClass]="setClass('video')"></app-video>
And my TS code:
mapFullscreen: boolean = true;
switchInset(target: string) {
switch (target) {
case 'map':
if (!this.mapFullscreen) {
this.mapFullscreen = this.mapFullscreen ? false : true;
}
break;
case 'video':
if (this.mapFullscreen) {
this.mapFullscreen = this.mapFullscreen ? false : true;
}
break;
default:
break;
}
}
setClass(target: string) {
let classes = {};
switch (target) {
case 'map':
classes = {
inset: !this.mapFullscreen,
fullscreen: this.mapFullscreen
}
break;
case 'video':
classes = {
inset: this.mapFullscreen,
fullscreen: !this.mapFullscreen
}
break;
default:
break;
}
return classes;
}
Exactly. If you have a method (function) in your binding, this function will be called every time change detection runs, and that can be quite often as your experienced.
This is the reason binding to methods is discouraged.
Instead assign the result of the method call to a property and bind to that property instead.
[ngClass]="mapClass"
ngOnChanges() { // just an example to use `ngOnChanges`
this.mapClass = setClass('map');
}