Skip to content
This repository has been archived by the owner on Jan 10, 2021. It is now read-only.

Commit

Permalink
feat: add InputNumber decorator converting numeric inputs to number type
Browse files Browse the repository at this point in the history
  • Loading branch information
MaGnaL committed Jan 2, 2020
1 parent a8e4318 commit 53553ac
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 8 deletions.
1 change: 1 addition & 0 deletions projects/ng-utils/src/lib/decorators/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './input-changed.decorator';
export * from './input-observable.decorator';
export * from './input-flag.decorator';
export * from './input-number.decorator';
19 changes: 11 additions & 8 deletions projects/ng-utils/src/lib/decorators/input-changed.decorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,20 @@ export interface InputChangedConfig {
skipFirst?: boolean;
}

export function InputChanged(config: string | string[] | InputChangedConfig = {distinct: true}): MethodDecorator {
// process config
if (_.isString(config)) {
config = {input: config};
} else if (_.isArray(config)) {
config = {input: config};
export function InputChanged(): MethodDecorator;
export function InputChanged(fields:string | string[]): MethodDecorator;
export function InputChanged(config:InputChangedConfig): MethodDecorator;
export function InputChanged(configOrFields: string | string[] | InputChangedConfig = {distinct: true}): MethodDecorator {
// process configOrFields
if (_.isString(configOrFields)) {
configOrFields = {input: configOrFields};
} else if (_.isArray(configOrFields)) {
configOrFields = {input: configOrFields};
}

let {input} = config;
let {input} = configOrFields;

const {distinct, skipFirst} = config;
const {distinct, skipFirst} = configOrFields;

return (target: OnInputChangeClass, propertyKey: string, descriptor: TypedPropertyDescriptor<any>) => {
// check for needed setup
Expand Down
31 changes: 31 additions & 0 deletions projects/ng-utils/src/lib/decorators/input-number.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import * as _ from 'lodash';

export function InputNumber() {
return (target, inputPropertyKey: string) => {
const randomIndex: string = _.uniqueId('InputNumber') + '_' + inputPropertyKey;

// get original setup of input and remove it from the object

const originalInput: PropertyDescriptor = Object.getOwnPropertyDescriptor(target, inputPropertyKey);

delete target[inputPropertyKey];

// define new setup of input

Object.defineProperty(target, inputPropertyKey, {
get(): number {
return originalInput ? originalInput.get() : this[randomIndex];
},

set(value: string | number): void {
value = _.toNumber(value);

if (originalInput) {
originalInput.set(value);
} else {
this[randomIndex] = value;
}
}
});
};
}

0 comments on commit 53553ac

Please sign in to comment.