@angular/cdk/coercion package provides utilities for coercing values to specific types, commonly used for component inputs.
Installation
Boolean Coercion
Coerce any value to boolean (useful for attribute inputs):false,"false",null,undefined,""→false- Everything else →
true
Number Coercion
Coerce values to numbers:Array Coercion
Ensure a value is an array:CSS Pixel Value Coercion
Coerce to CSS pixel value:Element Coercion
CoerceElementRef to HTMLElement:
Practical Examples
Flexible Size Input
Multi-value Input
API Reference
coerceBooleanProperty
coerceNumberProperty
coerceArray
coerceCssPixelValue
coerceElement
ElementRef or Element to the element.
Modern Approach (Angular 16+)
Angular 16+ provides built-in transform functions:Best Practices
- Use modern transforms - Prefer
booleanAttribute/numberAttributein Angular 16+ - Provide fallback values - For
coerceNumberProperty - Type safety - Use TypeScript generics with
coerceArray - Null handling - Coercion functions handle null/undefined gracefully
- Documentation - Document expected input types in component docs