Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using proper CSS media queries in Angular

I read that in Angular it is a very bad practice to use the CSS hidden element to hide an element like this:

.container{
  background-color : powderblue;
  height : 50px;
  width : 100%
}

@media (max-width: 400px){
    .container{
        display: none;
    }

}
<div class="container"></div>

And I know the Angular way to show or hide an element is using the *ngIf directive.

Question

How can I get the * ngIf to react on the media query in an 'Angular fashion'?

like image 911
Willem van der Veen Avatar asked Feb 05 '18 17:02

Willem van der Veen


3 Answers

You can use angular/breakpoints-angular-cdk

follow these steps

on the terminal

npm install @angular/cdk

Then import the layout module and and add it to your NgModule’s list of imports

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { LayoutModule } from '@angular/cdk/layout';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
  AppComponent
],
imports: [
    BrowserModule,
    LayoutModule
],
providers: [],
bootstrap: [AppComponent]
})

right after you can use it in your component, just import these classes from @angular/cdk/layout

import { Component, OnInit } from '@angular/core';
import { BreakpointObserver, BreakpointState } from '@angular/cdk/layout';

@Component({ ... })
export class AppComponent implements OnInit {
  public showContainer: boolean;
  constructor(public breakpointObserver: BreakpointObserver) {}

  ngOnInit() {
    this.breakpointObserver
      .observe(['(min-width: 400px)'])
      .subscribe((state: BreakpointState) => {
        if (state.matches) {
          this.showContainer = true;
        } else {
          this.showContainer = false;
        }
      });
  }
}

Check the docs it is a simple API

like image 163
Vitor Kevin Avatar answered Sep 23 '22 18:09

Vitor Kevin


Angular flex layout is better solution for this. You wouldn't need media queries and it has special responsive feature to show and hide for example

fxShow: This markup specifies if its host element should be displayed (or not)

<div fxShow [fxShow.xs]="isVisibleOnMobile()"></div>

fxHide: This markup specifies if its host element should NOT be displayed

<div fxHide [fxHide.gt-sm]="isVisibleOnDesktop()"></div>

No need to write lot of css and it's very compatible with angular material. https://github.com/angular/flex-layout

like image 20
indrajeet Avatar answered Sep 26 '22 18:09

indrajeet


I came up with the following base class and have found it works well.

import { HostBinding, OnDestroy, OnInit } from '@angular/core';
import { MediaObserver } from '@angular/flex-layout';
import { Subscription } from 'rxjs';

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;
    }
}

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 'lg' 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;
    }
}

I've put the full file on my gist https://gist.github.com/NickStrupat/b80bda11daeea06a1a67d2d9c41d4993

like image 40
Nick Strupat Avatar answered Sep 22 '22 18:09

Nick Strupat