我已经按照以下步骤设置了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>
答案 0 :(得分:2)
由于isMobile
是Observable
,它将解开成类似以下的值:
{
"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。