|
| 1 | +import {BreakpointObserver, Breakpoints} from '@angular/cdk/layout'; |
| 2 | +import {Component, OnDestroy} from '@angular/core'; |
| 3 | +import {Subject} from 'rxjs'; |
| 4 | +import {takeUntil} from 'rxjs/operators'; |
| 5 | + |
| 6 | +/** @title Respond to viewport changes with BreakpointObserver */ |
| 7 | +@Component({ |
| 8 | + selector: 'breakpoint-observer-overview-example', |
| 9 | + templateUrl: 'breakpoint-observer-overview-example.html', |
| 10 | + styleUrls: ['breakpoint-observer-overview-example.css'] |
| 11 | +}) |
| 12 | +export class BreakpointObserverOverviewExample implements OnDestroy { |
| 13 | + destroyed = new Subject<void>(); |
| 14 | + currentScreenSize: string; |
| 15 | + |
| 16 | + // Create a map to display breakpoint names for demonstration purposes. |
| 17 | + displayNameMap = new Map([ |
| 18 | + [Breakpoints.XSmall, 'XSmall'], |
| 19 | + [Breakpoints.Small, 'Small'], |
| 20 | + [Breakpoints.Medium, 'Medium'], |
| 21 | + [Breakpoints.Large, 'Large'], |
| 22 | + [Breakpoints.XLarge, 'XLarge'], |
| 23 | + ]); |
| 24 | + |
| 25 | + constructor(breakpointObserver: BreakpointObserver) { |
| 26 | + breakpointObserver.observe([ |
| 27 | + Breakpoints.XSmall, |
| 28 | + Breakpoints.Small, |
| 29 | + Breakpoints.Medium, |
| 30 | + Breakpoints.Large, |
| 31 | + Breakpoints.XLarge, |
| 32 | + ]).pipe(takeUntil(this.destroyed)).subscribe(result => { |
| 33 | + for (const query of Object.keys(result.breakpoints)) { |
| 34 | + if (result.breakpoints[query]) { |
| 35 | + this.currentScreenSize = this.displayNameMap.get(query) ?? 'Unknown'; |
| 36 | + } |
| 37 | + } |
| 38 | + }); |
| 39 | + } |
| 40 | + |
| 41 | + ngOnDestroy() { |
| 42 | + this.destroyed.next(); |
| 43 | + this.destroyed.complete(); |
| 44 | + } |
| 45 | +} |
0 commit comments