Skip to content

Instantly share code, notes, and snippets.

@DuncanFaulkner
Last active Jul 9, 2021
Embed
What would you like to do?
mediaobservable-observable
import { Component, OnDestroy, OnInit } from '@angular/core';
import { MediaChange, MediaObserver } from '@angular/flex-layout';
import { Subscription } from 'rxjs';
import { distinctUntilChanged } from 'rxjs/operators';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit, OnDestroy {
title = 'Angular Flex-Layout';
/**
*
* @param mediaObserver
*/
constructor(public mediaObserver: MediaObserver) {}
private mediaSubscription!: Subscription;
private activeMediaQuery: string = '';
ngOnInit(): void {
const getAlias = (MediaChange: MediaChange[]) => {
return MediaChange[0].mqAlias;
};
this.mediaSubscription = this.mediaObserver
.asObservable()
.pipe(
distinctUntilChanged(
(x: MediaChange[], y: MediaChange[]) => getAlias(x) === getAlias(y)
)
)
.subscribe((change) => {
change.forEach((item) => {
this.activeMediaQuery = item
? `'${item.mqAlias}' = (${item.mediaQuery})`
: '';
if (item.mqAlias === 'md') {
this.loadMobileContent();
}
console.log('activeMediaQuery', this.activeMediaQuery);
});
});
}
ngOnDestroy(): void {
this.mediaSubscription.unsubscribe();
}
loadMobileContent() {
console.log('load mobile content');
// Do something special since the viewport is currently
// using mobile display sizes.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment