1- import { MediaMatcher } from '@angular/cdk/layout' ;
2- import { Component , OnDestroy , inject , signal } from '@angular/core' ;
1+ import { BreakpointObserver } from '@angular/cdk/layout' ;
2+ import { Component , inject } from '@angular/core' ;
3+ import { toSignal } from '@angular/core/rxjs-interop' ;
34import { MatListModule } from '@angular/material/list' ;
45import { MatSidenavModule } from '@angular/material/sidenav' ;
56import { MatIconModule } from '@angular/material/icon' ;
67import { MatButtonModule } from '@angular/material/button' ;
78import { MatToolbarModule } from '@angular/material/toolbar' ;
9+ import { map } from 'rxjs/operators' ;
810
911/** @title Responsive sidenav */
1012@Component ( {
@@ -13,7 +15,7 @@ import {MatToolbarModule} from '@angular/material/toolbar';
1315 styleUrl : 'sidenav-responsive-example.css' ,
1416 imports : [ MatToolbarModule , MatButtonModule , MatIconModule , MatSidenavModule , MatListModule ] ,
1517} )
16- export class SidenavResponsiveExample implements OnDestroy {
18+ export class SidenavResponsiveExample {
1719 protected readonly fillerNav = Array . from ( { length : 50 } , ( _ , i ) => `Nav Item ${ i + 1 } ` ) ;
1820
1921 protected readonly fillerContent = Array . from (
@@ -26,23 +28,12 @@ export class SidenavResponsiveExample implements OnDestroy {
2628 cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.` ,
2729 ) ;
2830
29- protected readonly isMobile = signal ( true ) ;
31+ private readonly _breakpointObserver = inject ( BreakpointObserver ) ;
3032
31- private readonly _mobileQuery : MediaQueryList ;
32- private readonly _mobileQueryListener : ( ) => void ;
33-
34- constructor ( ) {
35- const media = inject ( MediaMatcher ) ;
36-
37- this . _mobileQuery = media . matchMedia ( '(max-width: 600px)' ) ;
38- this . isMobile . set ( this . _mobileQuery . matches ) ;
39- this . _mobileQueryListener = ( ) => this . isMobile . set ( this . _mobileQuery . matches ) ;
40- this . _mobileQuery . addEventListener ( 'change' , this . _mobileQueryListener ) ;
41- }
42-
43- ngOnDestroy ( ) : void {
44- this . _mobileQuery . removeEventListener ( 'change' , this . _mobileQueryListener ) ;
45- }
33+ protected readonly isMobile = toSignal (
34+ this . _breakpointObserver . observe ( '(max-width: 600px)' ) . pipe ( map ( result => result . matches ) ) ,
35+ { initialValue : true } ,
36+ ) ;
4637
4738 protected readonly shouldRun = / ( ^ | .) ( s t a c k b l i t z | w e b c o n t a i n e r ) .( i o | c o m ) $ / . test (
4839 window . location . host ,
0 commit comments