Angular2根据css属性/屏幕大小更改操作

时间:2016-03-17 08:33:47

标签: angular

我正在创建某种收件箱屏幕。所以我在左侧有我的菜单,旁边有一个消息列表。我在bootstrap的网格系统的帮助下创建了这个屏幕。

当您选择信息时,它将显示在屏幕的右侧。但是当屏幕太小时,它会隐藏消息(hidden-xs,hidden-sm)。应该发生的是,当我选择一条消息时,它应该显示在同一个屏幕上,这已经有效了。但是当屏幕很小时,它应该导航到另一个页面。

我遇到的唯一问题是如何根据屏幕大小或css属性(可见性:隐藏)更改操作?

因此,当屏幕为md或lg时,消息显示在同一屏幕上,否则它将路由到另一个组件。

1 个答案:

答案 0 :(得分:1)

您必须使用客户端窗口大小的observable,这可以通过使用@ angular / flex-layout来完成,您可以找到API here

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

希望这可以帮到你!