2016-12-14 148 views
0

是否有類似於$ mdMedia的Angular 2服務?我需要顯示或隱藏基於窗口大小的按鈕(如果窗口與屏幕大小相同,我想隱藏它)

回答

1

也許這可能對您有幫助。

resize.service.js

import {Injectable} from '@angular/core'; 
import {BehaviorSubject} from 'rxjs/BehaviorSubject'; 

@Injectable() 
export class ResizeService { 
    public window = new BehaviorSubject(null); 

    constructor() { 
     window.onresize = (e) => { 
      this.window.next(e.target); 
     }; 
    } 
} 

app.component.ts

import {Component} from '@angular/core'; 
import {ResizeService} from './resize/resize.service'; 

@Component({ 
    moduleId: module.id, 
    selector: 'my-app', 
    templateUrl: 'app.component.html', 
    providers: [ResizeService] 
}) 

export class AppComponent { 
    constructor(private resizeService: ResizeService) { 
     resizeService.window.subscribe((val) => { 
      if (val) { 
       console.log(val.innerWidth); 
      } 
     }); 

    }; 
} 

該服務使用BehaviourSubject。 See this answer瞭解它是什麼。另請參閱https://xgrommx.github.io/rx-book/content/subjects/behavior_subject/index.html

組件訂閱BehaviourSubject(窗口)並在屏幕大小更改時獲取更新的值。

1

您可以使用並應使用柔性佈局:

官方https://github.com/angular/flex-layout/wiki/Adaptive-Layouts#core-directives--responsive-features

import {ObservableMedia} from '@angular/flex-layout'; 

@Component({ 
    selector : 'my-mobile-component', 
    template : ` 
     <div *ngIf="media.isActive('xs')"> 
     This content is only shown on Mobile devices 
     </div> 
     <footer> 
     Current state: {{ }} 
     </footer> 
    ` 
}) 
export class MyMobileComponent { 
    public state = ''; 
    constructor(public media:ObservableMedia) { 
    media.asObservable() 
     .subscribe((change:MediaChange) => { 
     this.state = change ? `'${change.mqAlias}' = (${change.mediaQuery})` : "" 
     }); 
    } 
}