29

Angular for everyone: Coerce boolean inputs with decorator

 2 years ago
source link: https://dev.to/gaetanrdn/angular-for-everyone-coerce-boolean-inputs-with-decorator-5g1c
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Angular for everyone: Coerce boolean inputs with decorator

Sep 4

・1 min read

Hey, here’s my use case: I have a component/directive which have a Boolean input property. I often use Angular/cdk in my projects because it offers useful features we don’t need to rewrite. One of it is the coercion of properties and more precisely the coerceBooleanProperty() method. You know there are many way to bind boolean attributes on DOM element.

<button disabled=“true”>Click</button>

<button [disabled]=“true”>Click</button>

<button disabled>Click</button>
Enter fullscreen modeExit fullscreen mode

In Typescript files this will be converted in a boolean or a string and it had a difficulty to handle it.

A first approach, is to use getter/setter and to call the cdk method to always have a boolean value.

@Input()
set disabled(disabled) {
  this._disabled = cerceBooleanProperty(disabled);
}

get disabled(): boolean {
  return this._disabled;
}

private _disabled: boolean;
Enter fullscreen modeExit fullscreen mode

But I find that a lot of code to repeat each time.
It will be so much sexier to just have to write this:

@Input()
@CoerceBoolean()
public disabled: boolean;
Enter fullscreen modeExit fullscreen mode

Here’s the code of the decorator which allows to do it:

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

export function CoerceBoolean() {
    return function (target: any, key: string): void {
        const getter = function () {
            // using Typescript reflection
            return this['__' + key];
        };

        const setter = function (next: any) {
            // using Typescript reflection
            this['__' + key] = coerceBooleanProperty(next);
        };

        Object.defineProperty(target, key, {
            get: getter,
            set: setter,
            enumerable: true,
            configurable: true,
        });
    };
}
Enter fullscreen modeExit fullscreen mode

Thanks for reading. Feel free to let me know your questions or how you handle it in your projects.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK