DevicePixelRatio
Reactive wrapper around window.devicePixelRatio. Track device pixel ratio changes (zoom level or display density) with Angular signals.
Usage
import { Component } from '@angular/core';
import { devicePixelRatio } from '@signality/core';
@Component({
template: `
<p>Pixel Ratio: {{ pixelRatio() }}</p>
`,
})
export class PixelRatioDemo {
readonly pixelRatio = devicePixelRatio();
}Use InjectionToken for Singleton
For global state tracking like devicePixelRatio, consider using the provided DEVICE_PIXEL_RATIO token instead of calling the function directly. This provides a singleton instance that can be shared across your entire application, reducing memory usage and event listener overhead:
import { inject } from '@angular/core';
import { DEVICE_PIXEL_RATIO } from '@signality/core';
const pixelRatio = devicePixelRatio();
const pixelRatio = inject(DEVICE_PIXEL_RATIO); Learn more about Token-based utilities.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | DevicePixelRatioOptions | Optional configuration (see Options below) |
Options
The DevicePixelRatioOptions extends Angular's CreateSignalOptions<number> and WithInjector:
| Option | Type | Description |
|---|---|---|
initialValue | number | Initial value for SSR (default: 1) |
equal | ValueEqualityFn<number> | Custom equality function (see more) |
debugName | string | Debug name for the signal (development only) |
injector | Injector | Optional injector for DI context |
Return Value
Returns a Signal<number> containing the current device pixel ratio value.
Examples
Adaptive image loading
import { Component, computed } from '@angular/core';
import { devicePixelRatio } from '@signality/core';
@Component({
template: `
<img [src]="imageSrc()" alt="Responsive image" />
`,
})
export class AdaptiveImage {
readonly pixelRatio = devicePixelRatio();
readonly imageSrc = computed(() => {
const ratio = this.pixelRatio();
if (ratio >= 2) return '/images/logo@2x.png';
if (ratio >= 1.5) return '/images/logo@1.5x.png';
return '/images/logo.png';
});
}SSR Compatibility
On the server, the signal initializes with 1 (default pixel ratio). You can provide a custom initial value:
const pixelRatio = devicePixelRatio({
initialValue: 2
});Type Definitions
type DevicePixelRatioOptions = CreateSignalOptions<number> & WithInjector;
function devicePixelRatio(options?: DevicePixelRatioOptions): Signal<number>;Related
- MediaQuery — General media query matching
- WindowSize — Window dimensions tracking
- ScreenOrientation — Screen orientation tracking