Last active
April 12, 2019 19:11
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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