Now i know that the question is originally referring to the Screen size so basically the width
and height
attributes, but for most people Breakpoints
are what really matter, therefore, and to make a global reusable solution, I would prefer using Angular
's BreakpointObserver
to handle this.
The following configuration is basically a service
with some functions
that can return
an Observable<BreakpointState>
and to be subscribed
wherever needed:
import { Injectable } from '@angular/core';
import { BreakpointObserver, BreakpointState } from '@angular/cdk/layout';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class ScreenService {
constructor(private observer: BreakpointObserver) {}
isBelowSm(): Observable<BreakpointState> {
return this.observer.observe(['(max-width: 575px)']);
}
isBelowMd(): Observable<BreakpointState> {
return this.observer.observe(['(max-width: 767px)']);
}
isBelowLg(): Observable<BreakpointState> {
return this.observer.observe(['(max-width: 991px)']);
}
isBelowXl(): Observable<BreakpointState> {
return this.observer.observe(['(max-width: 1199px)']);
}
}
The above code can be adjusted to deal with screen size the bootstrap
way (By changing max-width
into min-width
and adding 1px
for each value, and ofcourse to inverse function
s names.)
Now in the component class
, simply subscribing
to the observable
returned by any of the above functions would do.
i.e: app.component.ts
:
export class AppComponent implements AfterViewInit {
isBelowLg: boolean;
constructor(private screenService: ScreenService) {}
ngAfterViewInit(): void {
this.screenService.isBelowLg().subscribe((isBelowLg: BreakpointState) => {
this.isBelowLg = isBelowLg.matches;
});
}
}
Refer that using AfterViewInit
life cycle hook would save lot of trouble for when it comes to detectChanges()
after view was initialized.
EDIT:
As an alternative for AfterViewInit
it's the same, but additionally, you will need to use ChangeDetectorRef
to detectChanges()
, simply inject an instance in the subscribing component i.e: app.component.ts
like this:
constructor(
private screenService: ScreenService,
private cdref: ChangeDetectorRef
) {}
And afterwards, just a call for detectChanges()
would do:
this.cdref.detectChanges();