Reputation: 1733
How can I get the current change of the MediaChange[] when I observing media changes via MediaObserver?
I observed the current is the first item in the array MediaChange[], I can use the the first item. Bu I also observed, in the MediaChange has a priority I also observed the current change had a highest priority . Which can be the best?
Working code example:
constructor(mediaObserver: MediaObserver) {
this.mediaObserverAsObservable = mediaObserver.asObservable().subscribe((changes: MediaChange[]) => {
// option A.
const currentMediaChange = changes[0];
if (currentMediaChange.mqAlias === 'sm' || currentMediaChange.mqAlias === 'xs') {
if (this.sidenav) {
this.sidenav.close();
}
} else {
if (this.sidenav) {
this.sidenav.open();
}
}
// Option B.
const maxPriority = changes.reduce(
(currentMax, mediaChange) => (mediaChange.priority > currentMax ? mediaChange.priority : currentMax),
changes[0].priority
);
const currentMediaChange = changes.find(mc => mc.priority === maxPriority);
if (currentMediaChange) {
if (currentMediaChange.mqAlias === 'sm' || currentMediaChange.mqAlias === 'xs') {
if (this.sidenav) {
this.sidenav.close();
}
} else {
if (this.sidenav) {
this.sidenav.open();
}
}
}
});
}
Or I can use mediaObserver.isActive() to identify what query matched for the current viewport?
Thank you.
Upvotes: 0
Views: 1049
Reputation: 758
On 7.0.0-beta.24 (2019-03-17) the angular/flex-layout
did a break change so mediaObserver.asObservable()
is an observable that return MediaChange[]
The MediaChange
source code has an attribute called priority which give you the priority of activation where looks like on MediaChange[]
is sort by descendent order.
In other words highest priority is first. The option A I think so it's the best option based on above. Because you should choose the active mediaQuery
and it's the most high priority. It's not needed use reduce
when we know it's on first place.
Upvotes: 1