ngx-formcontrol-errors-async
Version:
Handle your form control errors like a champ. Async is the way!!!
63 lines (58 loc) • 2.66 kB
JavaScript
import { Subject } from 'rxjs';
import { map, takeUntil } from 'rxjs/operators';
const OBSERVABLE_FORM_ERROR_PROPNAME = {
OBSERVABLE_STORE: '__formcontrol_observables',
OBSERVABLE_KILL_NOTIFY: '__formcontrol_observableKill',
};
function prepareFormErrorObservables() {
return (_type) => {
((type) => {
type.prototype[OBSERVABLE_FORM_ERROR_PROPNAME.OBSERVABLE_STORE] = {};
type.prototype[OBSERVABLE_FORM_ERROR_PROPNAME.OBSERVABLE_KILL_NOTIFY] = new Subject();
type.prototype.ngOnDestroy = (function (ngOnDestroy) {
return function () {
ngOnDestroy && ngOnDestroy.call(this);
const destroyNotify = type.prototype[OBSERVABLE_FORM_ERROR_PROPNAME.OBSERVABLE_KILL_NOTIFY];
destroyNotify.next();
destroyNotify.complete();
type.prototype[OBSERVABLE_FORM_ERROR_PROPNAME.OBSERVABLE_STORE] = {};
};
})(type.prototype.ngOnDestroy);
})(_type);
};
}
function useFormErrorObservable(instance) {
ensureClassIsDecorated(instance, Object.values(OBSERVABLE_FORM_ERROR_PROPNAME));
return (keyName, func, translations) => {
if (instance[OBSERVABLE_FORM_ERROR_PROPNAME.OBSERVABLE_STORE][keyName])
return instance[OBSERVABLE_FORM_ERROR_PROPNAME.OBSERVABLE_STORE][keyName];
return (instance[OBSERVABLE_FORM_ERROR_PROPNAME.OBSERVABLE_STORE][keyName] = createErrorObservable(func, translations).pipe(takeUntil(instance[OBSERVABLE_FORM_ERROR_PROPNAME.OBSERVABLE_KILL_NOTIFY])));
};
}
function createErrorObservable(func, translations) {
const control = func();
return control.statusChanges.pipe(map(() => control.errors), map((x) => {
if (!x)
return null;
const [key, translateByKey] = Object.entries(translations).find(([_key]) => !!x[_key]);
return translateByKey(x[key], control);
}));
}
function ensureClassIsDecorated(instance, properties) {
const prototype = Object.getPrototypeOf(instance);
const missingDecorator = !properties.every((prop) => prop in prototype);
if (missingDecorator) {
throw new Error('this operator cannot be used inside components' +
' that are not decorated with ' +
properties.join(', ') +
' decorator');
}
}
/*
* Public API Surface of ngx-formcontrol-errors-async
*/
/**
* Generated bundle index. Do not edit.
*/
export { prepareFormErrorObservables, useFormErrorObservable };
//# sourceMappingURL=ngx-formcontrol-errors-async.js.map