Stefan
Stefan

Reputation: 97

Angular2 change action based on css attributes / screen size

I'm creating some kind of inbox screen. So I have my menu on the left side, and next to it there is a list of messages. I created this screen with the help of bootstrap's grid system.

When you select a message it will show up at the right side of the screen. But when the screen is too small, it hides the message (hidden-xs, hidden-sm). What should happen is that when I select a message it should show up on the same screen, this works already. But when the screen is to small it should navigate to a different page.

The only question I got is how do I change the action based on the screen size or css attribute (visibility: hidden)?

So when the screen is md or lg the message displays on the same screen, else it will route to another component.

Upvotes: 3

Views: 764

Answers (1)

Lorenzo Imperatrice
Lorenzo Imperatrice

Reputation: 997

You have to use an observable of the client window size, this can be done by using @angular/flex-layout, you can find the API here.

your-component.component.ts

import { Component, AfterViewInit } from '@angular/core';
import { ObservableMedia, MediaChange } from '@angular/flex-layout';
import { Subscription } from 'rxjs/Rx';

@Component({
    selector: 'app-your-component',
    templateUrl: './your-component.component.html',
    styleUrls: ['./your-component.component.css']
})
export class YourComponentComponent implements AfterViewInit {

    // Subscription of the observer of the screen size
    mediaQuery$: Subscription;

    // The active media query (xs | sm | md | lg | xl)
    activeMediaQuery: string;

    constructor(
        private observableMedia: ObservableMedia
    ){}

    ngAfterViewInit () {

        this.mediaQuery$ = this.observableMedia.subscribe( (change: MediaChange) => {
            this.activeMediaQuery = `${change.mqAlias}`;
            if (this.activeMediaQuery === 'xs' || this.activeMediaQuery === 'sm') {
                // Here goes code for action in xs or sm (small screen)
            } else {
                // Here goes code for action in gt-sm (bigger screen)
            }
        });
    }
}

Hope that this can help you!

Upvotes: 1

Related Questions