ViewportService
TheViewportService provides reactive viewport breakpoint detection using Angular CDK’s BreakpointObserver. It exposes signal-based properties for determining the current device type (mobile, tablet, or desktop) and enables responsive UI behavior throughout the application.
Overview
This core service monitors viewport size changes and provides real-time signals that components can use to adapt their layout and behavior. It’s used extensively in Air Tracker to switch between desktop panels and mobile bottom sheets, adjust grid layouts, and optimize UI for different screen sizes.The service uses Angular CDK’s predefined breakpoints (
Breakpoints.HandsetPortrait, Breakpoints.TabletPortrait, etc.) for consistent responsive behavior.Service API
Provided In
Public Properties (Signals)
Returns
true when the viewport matches handset (mobile) breakpoints, both portrait and landscape orientationsReturns
true when the viewport matches tablet breakpoints, both portrait and landscape orientationsReturns
true when the viewport is neither mobile nor tablet (fallback for larger screens)Returns the current viewport mode as a string:
'mobile', 'tablet', or 'desktop'Computed based on the priority:- If
isMobile()is true →'mobile' - Else if
isTablet()is true →'tablet' - Otherwise →
'desktop'
Types
Implementation Details
The service uses Angular CDK’sBreakpointObserver to monitor viewport changes:
Implementation
Breakpoint Mapping
| Signal | CDK Breakpoints |
|---|---|
isMobile | HandsetPortrait, HandsetLandscape |
isTablet | TabletPortrait, TabletLandscape |
isDesktop | Computed as !isMobile && !isTablet |
Usage Examples
Conditional Rendering Based on Viewport
Component with viewport-based logic
Responsive Grid Layouts
Dynamic grid row heights
Mode-Based Logic
Using mode signal
Real-World Usage in Air Tracker
FlightsShellComponent
Switches between desktop overlay panel and mobile bottom sheet:FlightsShellComponent
FlightDetailBottomSheetComponent
Adjusts grid layout ratios based on device:FlightDetailBottomSheetComponent
PollingStatusComponent
Displays different polling information based on viewport:PollingStatusComponent
Benefits
- Reactive: Uses signals for automatic change detection
- Performance: Uses
distinctUntilChanged()to minimize unnecessary updates - Type-safe: Provides
ViewportModetype for compile-time checking - Singleton: Shares breakpoint observations across all components
- Standard breakpoints: Leverages Angular CDK’s well-tested breakpoint definitions
Related
- FlightsShellComponent - Uses viewport service to switch between UI modes
- FlightDetailBottomSheetComponent - Adjusts layout based on viewport
- Angular CDK Layout - Underlying breakpoint detection
Source
~/workspace/source/src/app/core/services/viewport.service.ts