Created
March 30, 2018 04:45
-
-
Save wilsoncook/7c97bf976aa0302c1c57bfccb12b3a92 to your computer and use it in GitHub Desktop.
Angular simple boolean inputing converting decorator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Input decorator that handle a prop to do get/set automatically with toBoolean | |
* | |
* Why not using @InputBoolean alone without @Input? AOT needs @Input to be visible | |
* | |
* @howToUse | |
* ``` | |
* @Input() @InputBoolean() visible: boolean = false; | |
* | |
* // Act as below: | |
* // @Input() | |
* // get visible() { return this.__visibile; } | |
* // set visible(value) { this.__visible = value; } | |
* // __visible = false; | |
* ``` | |
*/ | |
export function InputBoolean(): any { // tslint:disable-line:no-any | |
return function InputBooleanPropDecorator (target: object, name: string): void { | |
// Add our own private prop | |
const privatePropName = `$$__${name}`; | |
if (Object.prototype.hasOwnProperty.call(target, privatePropName)) { | |
console.warn(`The prop "${privatePropName}" is already exist, it will be overrided by InputBoolean decorator.`); | |
} | |
Object.defineProperty(target, privatePropName, { | |
configurable: true, | |
writable: true | |
}); | |
Object.defineProperty(target, name, { | |
get(): boolean { | |
return this[ privatePropName ]; // tslint:disable-line:no-invalid-this | |
}, | |
set(value: boolean | string): void { | |
this[ privatePropName ] = toBoolean(value); // tslint:disable-line:no-invalid-this | |
} | |
}); | |
// // Do rest things for input decorator | |
// const inputDecorator = Input(); | |
// inputDecorator(target, name); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment