Converting Angular Inputs to Boolean Values

Ole Ersoy
2 min readFeb 2, 2023

--

Image by Kalahari from Pixabay

Scenario

We are creating a power button component which is off by default.

We want the declaration to support switching it on by simply adding on as an attribute to the component declaration like this.

<power-button on></power-button>

Approach

Create a toBoolean utility function to convert the @Input on property or use coerceBooleanProperty from the Angular CDK.

It can be imported like this (I’ll add a few demoes add the bottom of the article):

import { coerceBooleanProperty } from '@angular/cdk/coercion';

This is the toBoolean implementation.


/**
* If the value is an empty string or 'true,
* it will be converted to a truthy value.
*
* Correspondingly if the val is a string, but
* it is not an empty string or some value other
* than `true`, the coerced value will be false.
*
* Allowing empty strings to be truthy enables
* us to add a property to a component element
* without setting it to anything explicit,
* and the property value will be evaluated
* as truthy after having passed through `toBoolean`.
*
* The on property in the below example will be
* truthy, and as a result of this the property
* can be used in conjunction with HostBinding
* to turn the power button on `<power-button [class.on]="_on">`
*
* @example
* ```
* <power-button on></power-button>
* ```
*
* Non string values are converted using !!val.
*
* @param val The value
* @returns The boolean coerced value for val
*/
export function toBoolean(val: any): boolean {
if (typeof val === 'string') {
val = val.toLowerCase().trim();
return val === '' || val === 'true' ;
}
return !!val;
}

And implement the setter like this.

@Input()
set on(on: any) {
this.isOn = toBoolean(on);
}

Demo

Angular CDK Demoes

Angular Demo

Pure Typescript Demo

Related Concepts

--

--