Reputation: 13216
I have set up my BreakpointObserver
as follows, but it doesn't seem to be firing when ever my page loads. My page is always in the mobile orientation. How can I fix it?
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>
Upvotes: 2
Views: 5033
Reputation: 39472
Since isMobile
is an Observable
which will unwrap into a value some like this:
{
"matches": true,
"breakpoints": {
"(max-width: 599px) and (orientation: portrait)": true,
"(max-width: 959px) and (orientation: landscape)": false
}
}
Place a !
before it will always make it false to *ngIf
The unwrapped object will have a matches
property, however, which is a boolean
. So you can use that.
Try this instead:
<div *ngIf="!(isMobile | async)?.matches">is not mobile</div>
<div *ngIf="(isMobile | async)?.matches">is mobile</div>
Also, change your HomeComponent
implementation to initialize isMobile
in ngOnInit
as that's what is followed as a common practice:
export class HomeComponent {
isMobile: Observable<BreakpointState>;
constructor(private breakpointObserver: BreakpointObserver) { }
ngOnInit() {
this.isMobile = this.breakpointObserver.observe(Breakpoints.Handset);
}
}
Here's a Sample StackBlitz for your ref.
Upvotes: 4