I'm creating an Angular responsive app where I have more than 10 breakpoints in which I have to group the elements in different containers. Having this in mind I believe that I can't get advantage of the css mediaQueris and I want to have the innerWidth property of the window within the components.
In order to get it I have created the following directive and I extend the components with it:
import { Directive, NgZone, OnDestroy } from "@angular/core";
import { Subject, fromEvent } from "rxjs";
import { debounceTime, distinctUntilChanged, map, takeUntil } from "rxjs/operators";
@Directive()
export abstract class WindowResizeDirective implements OnDestroy {
winWidth: number = window.innerWidth;
protected destroy$: Subject<boolean> = new Subject();
constructor(private _zone: NgZone) {
this._zone.runOutsideAngular(() => {
fromEvent(window, 'resize').pipe(
debounceTime(300),
map((ev: any) => ev.target.innerWidth),
distinctUntilChanged(),
takeUntil(this.destroy$)
).subscribe(width => {
this._zone.run(() => {
this.winWidth = width;
})
});
});
}
ngOnDestroy(): void {
this.destroy$.next(true);
this.destroy$.complete();
}
}
However many times I need to use this directive of the page component once and than on many components which are children of the page component, thus a lot of change detection cycles are triggered for one and the same reason -> resize of the window. Can you suggest a way of improving the performance?
- I've been thinking of using a service instead of directive which is provided on parent level and than each child can get the same instance of the service.
- I'm not sure if the code within the directive is optimal at all.
Any suggestions would be appreciated.
bodyresize. Check this question