I'm trying to create a Angular service that components can use to watch the window resize event. After lots of attempts I finally found this solution worked best https://stackoverflow.com/a/43833815.
However, it seemed to cause an error when running in SSR.
TypeError: this.eventManager.addGlobalEventListener is not a function
After lots of attempts this is where I'm at:
Service
import { Injectable, Inject, PLATFORM_ID } from '@angular/core';
import { EventManager } from '@angular/platform-browser';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class WindowService {
private resizeSubject: Subject<Window>;
constructor(
@Inject(PLATFORM_ID) private eventManager: EventManager) { // Event is not defined without @Inject(PLATFORM_ID)
this.resizeSubject = new Subject();
this.eventManager.addGlobalEventListener('window', 'resize', this.onResize.bind(this));
}
private onResize(event: UIEvent) {
this.resizeSubject.next(<Window>event.target);
}
/**
* Get an observerable for the window resize event
* @returns Return the window resize as an observable
*/
get onResize$(): Observable<Window> {
return this.resizeSubject.asObservable();
}
}
Component
import { Component, ElementRef, Input, OnInit, Output, EventEmitter, OnDestroy } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { Subscription } from 'rxjs/Subscription';
import { WindowService } from '../../services/window.service';
@Component({
selector: 'app-sidebar',
templateUrl: './sidebar.component.html'
})
export class SidebarComponent implements OnInit, OnDestroy {
element: HTMLElement;
resizeSubscription: Subscription;
constructor(
private readonly el: ElementRef,
private windowService: WindowService) {
this.element = el.nativeElement;
}
ngOnInit(): void {
const self = this;
this.resizeSubscription = this.windowService.onResize$
.debounceTime(100)
.subscribe(function(windowObj) {
if (windowObj.innerWidth >= 1024) {
self.open();
} else {
self.close();
}
});
}
ngOnDestroy(): void {
if (this.resizeSubscription) {
this.resizeSubscription.unsubscribe();
}
}
...
}
It seems a very complex way to bind to the window resize event but I've not found a better way that works with Angular SRR. Is there a recommended approach for this? Essentially I need to check the window size on resize (and also on load) and open or close the sidebar accordingly.