angular-typesafe-reactive-forms-helper
Version:
Use angular reactive forms with type-safety.
79 lines (74 loc) • 3.02 kB
JavaScript
import { Injectable } from '@angular/core';
import { FormBuilder } from '@angular/forms';
const getPropertyName = (propertyFunction) => {
let properties = [];
if (propertyFunction) {
if (propertyFunction.toString().includes('=>')) {
// propertyFunction.toString() sample value:
// x => x.hero.address.postcode
// we need the 'hero.address.postcode'
// for gr.get('hero.address.postcode') function
properties = propertyFunction
.split('=>')[1]
.trim()
.split('.')
.splice(1);
}
else {
// https://github.com/dsherret/ts-nameof - helped me with the code below, THANX!!!!
// propertyFunction.toString() sample value:
// function(x) { return x.hero.address.postcode;}
// we need the 'hero.address.postcode'
// for gr.get('hero.address.postcode') function
const step1 = propertyFunction.match(/return\s+([.a-zA-Z0-9]+)/i); // get the return part of the propertyFunction eg: return x.hero.address.postcode;
const step2 = step1 && step1[1].match(/([a-z0-9_]+)/gi); // split the step1[1] text to return an array eg: ['x','hero','address','postcode']
properties = (step2 && step2.splice(1)) || [];
}
}
return properties.join('.');
};
const generateGetSafeFunction = (gr) => {
return (propertyFunction) => {
const getStr = getPropertyName(propertyFunction.toString());
const p = gr.get(getStr);
return p;
};
};
const generateSetControlSafeFunction = (gr) => {
return (propertyFunction, control) => {
const getStr = getPropertyName(propertyFunction.toString());
gr.setControl(getStr, control);
};
};
const generateRemoveControlSafeFunction = (gr) => {
return (propertyFunction) => {
const getStr = getPropertyName(propertyFunction.toString());
gr.removeControl(getStr);
};
};
// tslint:disable-next-line: max-classes-per-file
class FormBuilderTypeSafe extends FormBuilder {
// override group to be type safe
group(controlsConfig, options) {
/* NOTE the return FormGroupTypeSafe<T> */
// instantiate group from angular type
const gr = super.group(controlsConfig, options);
if (gr) {
// implement getSafe method
gr.getSafe = generateGetSafeFunction(gr);
// implement setControlSafe
gr.setControlSafe = generateSetControlSafeFunction(gr);
// implement removeControlSafe
gr.removeControlSafe = generateRemoveControlSafeFunction(gr);
}
return gr;
}
}
FormBuilderTypeSafe.decorators = [
{ type: Injectable }
];
/**
* Generated bundle index. Do not edit.
*/
export { FormBuilderTypeSafe, generateGetSafeFunction, generateRemoveControlSafeFunction, generateSetControlSafeFunction };
//# sourceMappingURL=angular-typesafe-reactive-forms-helper.js.map