You can use Angular cdk:
Sometimes we need to know the width of the browser window in our component’s class file. You could have a @HostListener in a component for the window's resize event, but you'd have to maintain the service, write tests to make sure it was working properly, handle observables correctly so there aren't memory leaks, etc. The Angular CDK's LayoutModule has a BreakpointObserver class that you can inject into a component, provide a breakpoint (or breakpoints) that you want to watch for, and it will emit each time you cross the threshold of a breakpoint (i.e. if I want to know when the screen is smaller than 700px, it will emit a value when I cross under 700px, and then again when I cross back over 700px).
import { Output, Injectable, EventEmitter } from '@angular/core';
import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout';
@Injectable({
providedIn: 'root',
})
export class ScreenService {
@Output() changed = new EventEmitter();
constructor(private breakpointObserver: BreakpointObserver) {
this.breakpointObserver
.observe([Breakpoints.XSmall, Breakpoints.Small, Breakpoints.Medium, Breakpoints.Large])
.subscribe(() => this.changed.next());
}
private isLargeScreen() {
const isLarge = this.breakpointObserver.isMatched(Breakpoints.Large);
const isXLarge = this.breakpointObserver.isMatched(Breakpoints.XLarge);
return isLarge || isXLarge;
}
public get sizes() {
return {
'screen-x-small': this.breakpointObserver.isMatched(Breakpoints.XSmall),
'screen-small': this.breakpointObserver.isMatched(Breakpoints.Small),
'screen-medium': this.breakpointObserver.isMatched(Breakpoints.Medium),
'screen-large': this.isLargeScreen(),
};
}
}
And use it to detect screen size to open/close menu for example:
this.isMenuOpened = this.screen.sizes['screen-large'];
Also detect screen size changes:
this.screen.changed.subscribe(() => this.updateForm());
Better Explanation is here
Stackblitz Example is here
GitHub Repo is here