BreakpointObserver未触发

时间:2018-10-13 12:50:15

标签: angular observable breakpoints

我已经按照以下步骤设置了BreakpointObserver,但是页面加载后似乎没有触发。我的页面始终处于移动方向。我该如何解决?

home.component.ts

import { Component, OnInit } from '@angular/core';
import { Breakpoints, BreakpointState, BreakpointObserver } from '@angular/cdk/layout';
import { Observable } from 'rxjs';

@Component({
  templateUrl: './home.component.html'
})
export class HomeComponent implements OnInit {
  isMobile: Observable<BreakpointState> = this.breakpointObserver.observe(Breakpoints.Handset);

  constructor(private breakpointObserver: BreakpointObserver) { }

  ngOnInit() {
  }
}

home.component.html

<div *ngIf="!isMobile | async">is not mobile</div>

<div *ngIf="isMobile | async">is mobile</div>

1 个答案:

答案 0 :(得分:2)

由于isMobileObservable,它将解开成类似以下的值:

{
  "matches": true,
  "breakpoints": {
    "(max-width: 599px) and (orientation: portrait)": true,
    "(max-width: 959px) and (orientation: landscape)": false
  }
}

!之前始终放置*ngIf

未包装的对象将具有matches属性,即boolean。所以您可以使用它。

尝试以下方法:

<div *ngIf="!(isMobile | async)?.matches">is not mobile</div>

<div *ngIf="(isMobile | async)?.matches">is mobile</div>

此外,更改您的HomeComponent实现以在isMobile中初始化ngOnInit,因为通常的做法是:

export class HomeComponent {
  isMobile: Observable<BreakpointState>;

  constructor(private breakpointObserver: BreakpointObserver) { }

  ngOnInit() {
    this.isMobile = this.breakpointObserver.observe(Breakpoints.Handset);
  }

}

这是您推荐的Sample StackBlitz