Skip to content

Instantly share code, notes, and snippets.

<!-- This gets converted as 10px -->
<css-pixel-coercion [padding]="10"></css-pixel-coercion>
<!-- The following strings get bound as-is -->
<!-- The component users can pass in values with other units as well -->
<css-pixel-coercion [padding]="'10px'"></css-pixel-coercion>
<css-pixel-coercion [padding]="'1em'"></css-pixel-coercion>
<css-pixel-coercion [padding]="'1rem'"></css-pixel-coercion>
import { Component, Input } from '@angular/core';
import { coerceCssPixelValue } from '@angular/cdk/coercion'; // NEW IMPORT
@Component({
selector: 'css-pixel-coercion',
template: `...`
})
export class CssPixelCoercionComponent {
// In the following code, `@Input paddingX` will NOT work with strict type checking
// But we'll make the `@Input paddingY` to work with strict type checking as well
import { Component, Input } from '@angular/core';
@Component({
selector: 'element-coercion',
template: `...`
})
export class ElementCoercionComponent {
@Input() elementOne: Element;
@Input() elementTwo: Element;
}
<!-- Assuming that 'htmlElement' is a class property that returns a native HTML element -->
<!-- Assuming that 'elementRef' is a class property that returns an instance of ElementRef -->
<element-coercion
[elementOne]="htmlElement"
[elementTwo]="elementRef"
></element-coercion>
import { Component, ElementRef, Input } from '@angular/core';
import { coerceElement } from '@angular/cdk/coercion'; // NEW IMPORT
@Component({
selector: 'element-coercion',
template: ``
})
export class ElementCoercionComponent {
// In the following code, `@Input elementOne` will NOT work with strict type checking
// But we'll make the `@Input elementTwo` to work with strict type checking as well
import { Component, ElementRef, Input } from '@angular/core';
@Component({
selector: 'element-coercion',
template: `...`
})
export class ElementCoercionComponent {
@Input() elementOne: Element | ElementRef;
@Input() elementTwo: Element | ElementRef;
}
import { Component, Input } from '@angular/core';
@Component({
selector: 'number-coercion',
template: `...`
})
export class NumberCoercionComponent {
@Input() numberOne: number;
@Input() numberTwo: number;
}
<!-- Expression with a number value or a class property -->
<number-coercion [numberOne]="10" [numberTwo]="numericValue"></number-coercion>
<!-- Inline string value or an expression with a string value -->
<number-coercion numberOne="10" [numberTwo]="stringValue"></number-coercion>
import { Component, Input } from '@angular/core';
import { coerceNumberProperty } from '@angular/cdk/coercion'; // NEW IMPORT
@Component({
selector: 'number-coercion',
template: `...`
})
export class NumberCoercionComponent {
// In the following code, `@Input numberOne` will NOT work with strict type checking
// But we'll make the `@Input numberTwo` to work with strict type checking as well