Skip to content

Instantly share code, notes, and snippets.

@NickStrupat
Last active June 4, 2019 17:41
Show Gist options
  • Save NickStrupat/b80bda11daeea06a1a67d2d9c41d4993 to your computer and use it in GitHub Desktop.
Save NickStrupat/b80bda11daeea06a1a67d2d9c41d4993 to your computer and use it in GitHub Desktop.
import { HostBinding, OnDestroy, OnInit } from '@angular/core';
import { MediaObserver } from '@angular/flex-layout';
import { Subscription } from 'rxjs';
/**
* If you inherit (extend) your component from this class, the host element of your component will have a class added to it with the media query alias.
* For example...
*
* <app-search-bar class="some-class" _nghost-c5 ...>
*
* ...will become...
*
* <app-search-bar class="some-class lg" _nghost-c5 ...>
*
* Note the added media query alias which will change according to the window size. This makes it easy to add responsive styles to each media size by
* wrapping the size-specific styles in your component's SCSS files.
* Like this...
*
* :host-context(.sm, .md) { // styles specific to both sm and md media sizes
* .header {
* padding: 6px;
* width: 420px;
* }
* }
*
* :host-context(.lg, .xl) { // styles specific to both lg and xl media sizes
* .header {
* padding: 10px;
* width: 640px;
* }
* }
*/
export class MediaQueryClassBaseComponent implements OnInit, OnDestroy {
@HostBinding('class.xl') private xl: boolean;
@HostBinding('class.lg') private lg: boolean;
@HostBinding('class.md') private md: boolean;
@HostBinding('class.sm') private sm: boolean;
@HostBinding('class.xs') private xs: boolean;
private mediaObserverSubscription: Subscription | undefined = undefined;
constructor(protected readonly mediaObserver: MediaObserver) {}
ngOnInit(): void {
if (this.mediaObserverSubscription)
return;
this.mediaObserverSubscription = this.mediaObserver.media$.subscribe(x => {
this.xl = x.mqAlias == 'xl';
this.lg = x.mqAlias == 'lg';
this.md = x.mqAlias == 'md';
this.sm = x.mqAlias == 'sm';
this.xs = x.mqAlias == 'xs';
});
}
ngOnDestroy(): void {
if (!this.mediaObserverSubscription)
return;
this.mediaObserverSubscription.unsubscribe();
this.mediaObserverSubscription = undefined;
}
}
@TERMINALSERVERORDERLY
Copy link

.md

@NickStrupat
Copy link
Author

huh?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment