Elger Mensonides
Elger Mensonides

Reputation: 7029

Angular cdk breakpoints and universal issue

When rendering angular universal the breakpoint hits come too late. I'm using mat-sidenav which expects the drawer to be set opened or not based on a breakpoint. It seems that the breakpoint information isn't there when rendering ssr.

For example, this goes in the constructor:

this.isHandset$ = this.breakpointObserver.observe(Breakpoints.Handset)
    .pipe(
        map(result => result.matches)
    );

And in the view:

<mat-sidenav-container class="sidenav-container" fullscreen>
<mat-sidenav class="sidenav" 
    [opened]="(isHandset$ | async) === false">  <!-- close if handset -->
... etc

after the app hydrates (after the full angular project loads) the drawer opens / closes as it should based on the viewport size, but initially not.

How to make breakpoints also work with universal?

I'm currently using angular 9 rc, but same problem in 8.

Upvotes: 5

Views: 1589

Answers (1)

Reactgular
Reactgular

Reputation: 54811

You can define a default value that is emitted first before any breakpoints using startWith.

this.isHandset$ = this.breakpointObserver.observe(Breakpoints.Handset)
    .pipe(
        map(result => result.matches),
        startWith(false)
    );

Upvotes: 2

Related Questions