Skip to content

Instantly share code, notes, and snippets.

@NickStrupat
Last active April 12, 2019 19:11
Show Gist options
  • Save NickStrupat/ff5c65377d752aaceaa40db48668fc6a to your computer and use it in GitHub Desktop.
Save NickStrupat/ff5c65377d752aaceaa40db48668fc6a to your computer and use it in GitHub Desktop.
Add the media query alias to the body tag with angular flex-layout
import { Component, OnInit, OnDestroy, Inject, Renderer2 } from '@angular/core';
import { Subscription } from 'rxjs';
import { MediaObserver } from '@angular/flex-layout';
import { DOCUMENT } from '@angular/common';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, OnDestroy {
mediaObserverSubscription: Subscription;
currentMediaQueryAlias: string;
constructor(
@Inject(DOCUMENT) private document: Document,
private renderer: Renderer2,
private mediaObserver: MediaObserver,
) {}
ngOnInit(): void {
this.mediaObserver.media$.subscribe(mediaChange => {
this.renderer.removeClass(this.document.body, this.currentMediaQueryAlias);
this.currentMediaQueryAlias = mediaChange.mqAlias;
this.renderer.addClass(this.document.body, this.currentMediaQueryAlias);
});
}
ngOnDestroy(): void {
if (this.mediaObserverSubscription)
this.mediaObserverSubscription.unsubscribe();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment