flex-layout布局--ObservableMedia

初始准备

npm install angular/flex-layout-builds

app.module.ts

import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {FlexLayoutModule} from "@angular/flex-layout";

import {DemoAppComponent} from './demo-app/demo-app';

@NgModule({
  declarations: [DemoAppComponent],
  bootstrap: [DemoAppComponent],
  imports: [
    BrowserModule,
    FlexLayoutModule
  ]
})
export class DemoAppModule {}

ObservableMedia可以监控布局改变并调用函数
包含三个方法

subscribe(): Subscription
asObservable(): Observable<MediaChange>
isActive(query: string): boolean

ObservableMedia::subscribe()

下面的例子当我们屏幕的宽度变为xs时,运行loadMobileContent函数

app.component.html

<div class="container m-150"
       fxLayout="row"
       fxLayout.xs="column"
       fxLayoutAlign="center"
       fxLayoutGap="10px"
       fxLayoutGap.xs="0">
    <div class="item" fxFlex="33">1</div>
    <div class="item" fxFlex="33">2</div>
    <div class="item" fxFlex="33">3</div>
  </div>

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  watcher: Subscription;
  activeMediaQuery = "";

  constructor(media: ObservableMedia) {
    this.watcher = media.subscribe((change: MediaChange) => { this.activeMediaQuery = change ? `'${change.mqAlias}' = (${change.mediaQuery})` : ''; if ( change.mqAlias == 'xs') { console.log(this.activeMediaQuery); console.log(media.isActive('gt-sm'));//false console.log(media.isActive('xs'));//true this.loadMobileContent(change); } }); } loadMobileContent(change) { console.log(change); } } 

change对象为

{matches: true, mediaQuery: "(min-width: 0px) and (max-width: 599px)", mqAlias: "xs", suffix: "Xs"}

activeMediaQuery的值为

'xs' = ((min-width: 0px) and (max-width: 599px))

ObservableMedia::asObservable()

asObservable(): Observable<MediaChange>

ObservableMedia 并不是真正意义上的 Observable. 它仅仅是一个被用来暴露额外方法 如 ‘isActive()’的外壳。
用.asObservable() 来转换成Observable,然后就可以用RxJs操作符了 如such as media.asObservable().filter(….).

别忘记导入你需要的RxJS操作符

import {Component} from '@angular/core';
import {Subscription} from 'rxjs/Subscription';
import {filter} from 'rxjs/operators/filter';

import {MediaChange, ObservableMedia} from "@angular/flex-layout";

@Component({
   selector : 'responsive-component'
})
export class MyDemo {

  constructor(media: ObservableMedia) {
      media.asObservable()
        .pipe(
          filter((change: MediaChange) => change.mqAlias == 'xs') ).subscribe(() => this.loadMobileContent() ); } loadMobileContent() { } }
相关文章
相关标签/搜索
每日一句
    每一个你不满意的现在,都有一个你没有努力的曾经。
本站公众号
   欢迎关注本站公众号,获取更多程序园信息
开发小院