@angular/cdk/layout package provides utilities for responding to viewport size changes and media queries.
Installation
BreakpointObserver
TheBreakpointObserver allows you to observe media query changes.
Basic Usage
Custom Media Queries
Multiple Breakpoints
Predefined Breakpoints
The CDK provides predefined breakpoint constants:Synchronous Checking
Check breakpoints synchronously without subscribing:MediaMatcher
Lower-level service for working with media queries:Responsive Service Example
API Reference
BreakpointObserver
Injectable:{providedIn: 'root'}
| Method | Returns | Description |
|---|---|---|
observe(value) | Observable<BreakpointState> | Observe one or more media queries |
isMatched(value) | boolean | Synchronously check if media query matches |
BreakpointState
| Property | Type | Description |
|---|---|---|
matches | boolean | Whether any query matches |
breakpoints | {[key: string]: boolean} | Match state for each query |
MediaMatcher
Injectable:{providedIn: 'root'}
| Method | Returns | Description |
|---|---|---|
matchMedia(query) | MediaQueryList | Creates a MediaQueryList |
Best Practices
- Use predefined breakpoints - Consistent with Material Design
- ShareReplay observable - Avoid multiple subscriptions
- Unsubscribe or use async pipe - Prevent memory leaks
- Consider mobile-first - Design for small screens first
- Test on real devices - Simulators may not match exactly