coerce-property
v15.0.1
Published
Utility decorator functions for coercing Angular component @Inputs into specific types
Downloads
454
Maintainers
Readme
coerce-property
Utility decorator functions for coercing Angular component @Inputs
into specific types.
Used by Angular CDK coercions.
Support
Support Angular >=15.
Installation
# Do not forget to check if Angular CDK is installed
npm i -S @angular/cdk
# And install this package
npm i -S coerce-property
Coercions
@coerce
- decorator factory@coerceBoolean
- coerces a data-bound value (typically a string) to a booleanFor example:
<app-component disabled></app-component>
@Input() @coerceBoolean disabled: boolean; // true
@coerceArray
- wraps the provided value in an array, unless the provided value is an arrayFor example:
<app-component items="item"></app-component>
@Input() @coerceArray items: string[]; // ['item']
@coercePixel
- coerces a value to a CSS pixel valueFor example:
<app-component [width]="200"></app-component>
@Input() @coercePixel width: string; // '200px'
@coerceElement
- coerces an ElementRef or an Element into an element@coerceNumber
- coerces a data-bound value (typically a string) to a numberFor example:
<app-component age="19"></app-component>
@Input() @coerceNumber age: number; // 19
Usage
import { Component, Input } from "@angular/core";
import { coerceBoolean } from "coerce-property";
@Component({
selector: "app-component",
template: ``,
})
export class SampleComponent {
@Input()
@coerceBoolean
disabled: boolean;
}
You can use:
<app-sample [disabled]="true"></app-sample>
and
<app-sample disabled></app-sample>
How does it work
import { Component, Input } from "@angular/core";
import { coerceBooleanProperty } from "@angular/cdk/coercion";
@Component({
selector: "app-component",
template: ``,
})
export class SampleComponent {
private _dsiabled: boolean;
@Input()
get disabled() {
return this._dsiabled;
}
set disabled(disabled) {
this._disabled = coerceBooleanProperty(disabled);
}
}
// @angular/cdk/coercion/boolean-property.ts
export function coerceBooleanProperty(value: any): boolean {
return value != null && `${value}` !== "false";
}