'MediaObserver vs BreakpointObserver - what are the differences?
After doing some searching, I came to realize that I'm supposed to use the Flex-Layout library to make Material-themed UI responsive (as answered here). And according to the documentation, this library provides the MediaObserver
class to programmatically detect media query activation.
I used the material schematics command -
ng g @angular/material:navigation shell/layout
to add a Sidenav
component, and noticed the following generated code -
export class LayoutComponent {
isHandset$: Observable<boolean> = this.breakpointObserver.observe(Breakpoints.Handset).pipe(
map(result => result.matches),
shareReplay()
);
constructor(private breakpointObserver: BreakpointObserver) { }
}
It is using the BreakpointObserver
class and predefined Breakpoints
from @angular/cdk/layout
package to detect viewport changes. And the documentation says -
The layout package provides utilities to build responsive UIs that react to screen-size changes.
So, apparently, there are two different libraries available for making Material-themed UI responsive and they use different approaches. (Please correct me if I'm wrong).
I'd like to know -
- From usage perspective what are the differences between these two libraries/packages, that is, when to use which?
- Does
MediaObserver
usesBreakpointObserver
under-the-hood? - If I use Flex-Layout, should I avoid
@angular/cdk/layout
utilities altogether? Are there some best practices to follow in this regard?
Edit: 2020.05.11
According to the source code of MediaObserver
, it doesn't use the BreakpointObserver
under-the-hood. It uses the native Window.matchMedia()
API instead.
Solution 1:[1]
From : https://github.com/angular/flex-layout/issues/685
@angular/cdk BreakpointObserver will not replace @angular/flex-layout MediaObserver. MediaObserver is an enhanced version that notifies subscribers of activations for standard AND overlapping (lt-xxx, gt-xxx) breakpoints.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mike Jerred |