UNPKG

@crnk/angular-ngrx

Version:

Angular helper library for ngrx-json-api and crnk:

58 lines 2.71 kB
import { Directive, forwardRef } from '@angular/core'; import { AbstractControl, NG_VALIDATORS, ValidationErrors, Validator } from '@angular/forms'; import { Path } from '../crnk.expression'; import { ResourceError, StoreResource } from 'ngrx-json-api'; import * as _ from 'lodash'; export var RESOURCE_VALIDATOR = { provide: NG_VALIDATORS, useExisting: forwardRef(function () { return ResourceValidatorDirective; }), multi: true }; /** * Gets validation messages from the underlying resource. */ var ResourceValidatorDirective = /** @class */ (function () { function ResourceValidatorDirective() { } ResourceValidatorDirective.prototype.validate = function (c) { var path = c['_pathModel']; if (!path) { throw new Error('ResourceValidatorDirective can only be used with crnkFormExpression and crnkExpression'); } // note that invalid changes to not get pushed to the store. In this case the controlValue // and the resourceValue will differ and resource errors are no longer deemed useful. // Otherwise either errorous values would have to be pushed as well or the component could never // recover from an invalid state; var controlValue = c.value; var resourceValue = path.getValue(); var dirty = !_.isEqual(controlValue, resourceValue); var resource = path.getResource(); if (resource && resource.errors && !dirty) { var sourcePointer = path.getSourcePointer(); var validationErrors = {}; for (var _i = 0, _a = resource.errors; _i < _a.length; _i++) { var resourceError = _a[_i]; var errorKey = this.computeControlErrorKey(resourceError); if (resourceError.source && sourcePointer === resourceError.source.pointer && errorKey) { validationErrors[errorKey] = resourceError; } } return validationErrors; } return null; }; ResourceValidatorDirective.prototype.computeControlErrorKey = function (error) { return error.code ? error.code : error.id; }; ResourceValidatorDirective.decorators = [ { type: Directive, args: [{ selector: '[crnkFormExpression],[crnkExpression]', providers: [RESOURCE_VALIDATOR] },] }, ]; /** @nocollapse */ ResourceValidatorDirective.ctorParameters = function () { return []; }; return ResourceValidatorDirective; }()); export { ResourceValidatorDirective }; //# sourceMappingURL=crnk.expression.form.validators.jsonapi.js.map