2016-12-14 3 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})` : "" 
     }); 
    } 
} 
関連する問題