@angular/forms
Version:
Angular - directives and services for creating forms
1,221 lines (1,183 loc) • 297 kB
JavaScript
/**
* @license Angular v10.0.1
* (c) 2010-2020 Google LLC. https://angular.io/
* License: MIT
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/common'), require('rxjs'), require('rxjs/operators')) :
typeof define === 'function' && define.amd ? define('@angular/forms', ['exports', '@angular/core', '@angular/common', 'rxjs', 'rxjs/operators'], factory) :
(global = global || self, factory((global.ng = global.ng || {}, global.ng.forms = {}), global.ng.core, global.ng.common, global.rxjs, global.rxjs.operators));
}(this, (function (exports, core, common, rxjs, operators) { 'use strict';
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Used to provide a `ControlValueAccessor` for form controls.
*
* See `DefaultValueAccessor` for how to implement one.
*
* @publicApi
*/
var NG_VALUE_ACCESSOR = new core.InjectionToken('NgValueAccessor');
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var CHECKBOX_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: core.forwardRef(function () { return CheckboxControlValueAccessor; }),
multi: true,
};
/**
* @description
* A `ControlValueAccessor` for writing a value and listening to changes on a checkbox input
* element.
*
* @usageNotes
*
* ### Using a checkbox with a reactive form.
*
* The following example shows how to use a checkbox with a reactive form.
*
* ```ts
* const rememberLoginControl = new FormControl();
* ```
*
* ```
* <input type="checkbox" [formControl]="rememberLoginControl">
* ```
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
var CheckboxControlValueAccessor = /** @class */ (function () {
function CheckboxControlValueAccessor(_renderer, _elementRef) {
this._renderer = _renderer;
this._elementRef = _elementRef;
/**
* @description
* The registered callback function called when a change event occurs on the input element.
*/
this.onChange = function (_) { };
/**
* @description
* The registered callback function called when a blur event occurs on the input element.
*/
this.onTouched = function () { };
}
/**
* Sets the "checked" property on the input element.
*
* @param value The checked value
*/
CheckboxControlValueAccessor.prototype.writeValue = function (value) {
this._renderer.setProperty(this._elementRef.nativeElement, 'checked', value);
};
/**
* @description
* Registers a function called when the control value changes.
*
* @param fn The callback function
*/
CheckboxControlValueAccessor.prototype.registerOnChange = function (fn) {
this.onChange = fn;
};
/**
* @description
* Registers a function called when the control is touched.
*
* @param fn The callback function
*/
CheckboxControlValueAccessor.prototype.registerOnTouched = function (fn) {
this.onTouched = fn;
};
/**
* Sets the "disabled" property on the input element.
*
* @param isDisabled The disabled value
*/
CheckboxControlValueAccessor.prototype.setDisabledState = function (isDisabled) {
this._renderer.setProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
};
CheckboxControlValueAccessor.decorators = [
{ type: core.Directive, args: [{
selector: 'input[type=checkbox][formControlName],input[type=checkbox][formControl],input[type=checkbox][ngModel]',
host: { '(change)': 'onChange($event.target.checked)', '(blur)': 'onTouched()' },
providers: [CHECKBOX_VALUE_ACCESSOR]
},] }
];
CheckboxControlValueAccessor.ctorParameters = function () { return [
{ type: core.Renderer2 },
{ type: core.ElementRef }
]; };
return CheckboxControlValueAccessor;
}());
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var DEFAULT_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: core.forwardRef(function () { return DefaultValueAccessor; }),
multi: true
};
/**
* We must check whether the agent is Android because composition events
* behave differently between iOS and Android.
*/
function _isAndroid() {
var userAgent = common.ɵgetDOM() ? common.ɵgetDOM().getUserAgent() : '';
return /android (\d+)/.test(userAgent.toLowerCase());
}
/**
* @description
* Provide this token to control if form directives buffer IME input until
* the "compositionend" event occurs.
* @publicApi
*/
var COMPOSITION_BUFFER_MODE = new core.InjectionToken('CompositionEventMode');
/**
* @description
* The default `ControlValueAccessor` for writing a value and listening to changes on input
* elements. The accessor is used by the `FormControlDirective`, `FormControlName`, and
* `NgModel` directives.
*
* @usageNotes
*
* ### Using the default value accessor
*
* The following example shows how to use an input element that activates the default value accessor
* (in this case, a text field).
*
* ```ts
* const firstNameControl = new FormControl();
* ```
*
* ```
* <input type="text" [formControl]="firstNameControl">
* ```
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
var DefaultValueAccessor = /** @class */ (function () {
function DefaultValueAccessor(_renderer, _elementRef, _compositionMode) {
this._renderer = _renderer;
this._elementRef = _elementRef;
this._compositionMode = _compositionMode;
/**
* @description
* The registered callback function called when an input event occurs on the input element.
*/
this.onChange = function (_) { };
/**
* @description
* The registered callback function called when a blur event occurs on the input element.
*/
this.onTouched = function () { };
/** Whether the user is creating a composition string (IME events). */
this._composing = false;
if (this._compositionMode == null) {
this._compositionMode = !_isAndroid();
}
}
/**
* Sets the "value" property on the input element.
*
* @param value The checked value
*/
DefaultValueAccessor.prototype.writeValue = function (value) {
var normalizedValue = value == null ? '' : value;
this._renderer.setProperty(this._elementRef.nativeElement, 'value', normalizedValue);
};
/**
* @description
* Registers a function called when the control value changes.
*
* @param fn The callback function
*/
DefaultValueAccessor.prototype.registerOnChange = function (fn) {
this.onChange = fn;
};
/**
* @description
* Registers a function called when the control is touched.
*
* @param fn The callback function
*/
DefaultValueAccessor.prototype.registerOnTouched = function (fn) {
this.onTouched = fn;
};
/**
* Sets the "disabled" property on the input element.
*
* @param isDisabled The disabled value
*/
DefaultValueAccessor.prototype.setDisabledState = function (isDisabled) {
this._renderer.setProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
};
/** @internal */
DefaultValueAccessor.prototype._handleInput = function (value) {
if (!this._compositionMode || (this._compositionMode && !this._composing)) {
this.onChange(value);
}
};
/** @internal */
DefaultValueAccessor.prototype._compositionStart = function () {
this._composing = true;
};
/** @internal */
DefaultValueAccessor.prototype._compositionEnd = function (value) {
this._composing = false;
this._compositionMode && this.onChange(value);
};
DefaultValueAccessor.decorators = [
{ type: core.Directive, args: [{
selector: 'input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]',
// TODO: vsavkin replace the above selector with the one below it once
// https://github.com/angular/angular/issues/3011 is implemented
// selector: '[ngModel],[formControl],[formControlName]',
host: {
'(input)': '$any(this)._handleInput($event.target.value)',
'(blur)': 'onTouched()',
'(compositionstart)': '$any(this)._compositionStart()',
'(compositionend)': '$any(this)._compositionEnd($event.target.value)'
},
providers: [DEFAULT_VALUE_ACCESSOR]
},] }
];
DefaultValueAccessor.ctorParameters = function () { return [
{ type: core.Renderer2 },
{ type: core.ElementRef },
{ type: Boolean, decorators: [{ type: core.Optional }, { type: core.Inject, args: [COMPOSITION_BUFFER_MODE,] }] }
]; };
return DefaultValueAccessor;
}());
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
}
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
var __createBinding = Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
});
function __exportStar(m, exports) {
for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
}
function __asyncValues(o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
var __setModuleDefault = Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
};
function __importStar(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
}
function __importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
function __classPrivateFieldGet(receiver, privateMap) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to get private field on non-instance");
}
return privateMap.get(receiver);
}
function __classPrivateFieldSet(receiver, privateMap, value) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to set private field on non-instance");
}
privateMap.set(receiver, value);
return value;
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @description
* Base class for control directives.
*
* This class is only used internally in the `ReactiveFormsModule` and the `FormsModule`.
*
* @publicApi
*/
var AbstractControlDirective = /** @class */ (function () {
function AbstractControlDirective() {
}
Object.defineProperty(AbstractControlDirective.prototype, "value", {
/**
* @description
* Reports the value of the control if it is present, otherwise null.
*/
get: function () {
return this.control ? this.control.value : null;
},
enumerable: false,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "valid", {
/**
* @description
* Reports whether the control is valid. A control is considered valid if no
* validation errors exist with the current value.
* If the control is not present, null is returned.
*/
get: function () {
return this.control ? this.control.valid : null;
},
enumerable: false,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "invalid", {
/**
* @description
* Reports whether the control is invalid, meaning that an error exists in the input value.
* If the control is not present, null is returned.
*/
get: function () {
return this.control ? this.control.invalid : null;
},
enumerable: false,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "pending", {
/**
* @description
* Reports whether a control is pending, meaning that that async validation is occurring and
* errors are not yet available for the input value. If the control is not present, null is
* returned.
*/
get: function () {
return this.control ? this.control.pending : null;
},
enumerable: false,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "disabled", {
/**
* @description
* Reports whether the control is disabled, meaning that the control is disabled
* in the UI and is exempt from validation checks and excluded from aggregate
* values of ancestor controls. If the control is not present, null is returned.
*/
get: function () {
return this.control ? this.control.disabled : null;
},
enumerable: false,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "enabled", {
/**
* @description
* Reports whether the control is enabled, meaning that the control is included in ancestor
* calculations of validity or value. If the control is not present, null is returned.
*/
get: function () {
return this.control ? this.control.enabled : null;
},
enumerable: false,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "errors", {
/**
* @description
* Reports the control's validation errors. If the control is not present, null is returned.
*/
get: function () {
return this.control ? this.control.errors : null;
},
enumerable: false,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "pristine", {
/**
* @description
* Reports whether the control is pristine, meaning that the user has not yet changed
* the value in the UI. If the control is not present, null is returned.
*/
get: function () {
return this.control ? this.control.pristine : null;
},
enumerable: false,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "dirty", {
/**
* @description
* Reports whether the control is dirty, meaning that the user has changed
* the value in the UI. If the control is not present, null is returned.
*/
get: function () {
return this.control ? this.control.dirty : null;
},
enumerable: false,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "touched", {
/**
* @description
* Reports whether the control is touched, meaning that the user has triggered
* a `blur` event on it. If the control is not present, null is returned.
*/
get: function () {
return this.control ? this.control.touched : null;
},
enumerable: false,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "status", {
/**
* @description
* Reports the validation status of the control. Possible values include:
* 'VALID', 'INVALID', 'DISABLED', and 'PENDING'.
* If the control is not present, null is returned.
*/
get: function () {
return this.control ? this.control.status : null;
},
enumerable: false,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "untouched", {
/**
* @description
* Reports whether the control is untouched, meaning that the user has not yet triggered
* a `blur` event on it. If the control is not present, null is returned.
*/
get: function () {
return this.control ? this.control.untouched : null;
},
enumerable: false,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "statusChanges", {
/**
* @description
* Returns a multicasting observable that emits a validation status whenever it is
* calculated for the control. If the control is not present, null is returned.
*/
get: function () {
return this.control ? this.control.statusChanges : null;
},
enumerable: false,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "valueChanges", {
/**
* @description
* Returns a multicasting observable of value changes for the control that emits every time the
* value of the control changes in the UI or programmatically.
* If the control is not present, null is returned.
*/
get: function () {
return this.control ? this.control.valueChanges : null;
},
enumerable: false,
configurable: true
});
Object.defineProperty(AbstractControlDirective.prototype, "path", {
/**
* @description
* Returns an array that represents the path from the top-level form to this control.
* Each index is the string name of the control on that level.
*/
get: function () {
return null;
},
enumerable: false,
configurable: true
});
/**
* @description
* Resets the control with the provided value if the control is present.
*/
AbstractControlDirective.prototype.reset = function (value) {
if (value === void 0) { value = undefined; }
if (this.control)
this.control.reset(value);
};
/**
* @description
* Reports whether the control with the given path has the error specified.
*
* @param errorCode The code of the error to check
* @param path A list of control names that designates how to move from the current control
* to the control that should be queried for errors.
*
* @usageNotes
* For example, for the following `FormGroup`:
*
* ```
* form = new FormGroup({
* address: new FormGroup({ street: new FormControl() })
* });
* ```
*
* The path to the 'street' control from the root form would be 'address' -> 'street'.
*
* It can be provided to this method in one of two formats:
*
* 1. An array of string control names, e.g. `['address', 'street']`
* 1. A period-delimited list of control names in one string, e.g. `'address.street'`
*
* If no path is given, this method checks for the error on the current control.
*
* @returns whether the given error is present in the control at the given path.
*
* If the control is not present, false is returned.
*/
AbstractControlDirective.prototype.hasError = function (errorCode, path) {
return this.control ? this.control.hasError(errorCode, path) : false;
};
/**
* @description
* Reports error data for the control with the given path.
*
* @param errorCode The code of the error to check
* @param path A list of control names that designates how to move from the current control
* to the control that should be queried for errors.
*
* @usageNotes
* For example, for the following `FormGroup`:
*
* ```
* form = new FormGroup({
* address: new FormGroup({ street: new FormControl() })
* });
* ```
*
* The path to the 'street' control from the root form would be 'address' -> 'street'.
*
* It can be provided to this method in one of two formats:
*
* 1. An array of string control names, e.g. `['address', 'street']`
* 1. A period-delimited list of control names in one string, e.g. `'address.street'`
*
* @returns error data for that particular error. If the control or error is not present,
* null is returned.
*/
AbstractControlDirective.prototype.getError = function (errorCode, path) {
return this.control ? this.control.getError(errorCode, path) : null;
};
return AbstractControlDirective;
}());
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @description
* A base class for directives that contain multiple registered instances of `NgControl`.
* Only used by the forms module.
*
* @publicApi
*/
var ControlContainer = /** @class */ (function (_super) {
__extends(ControlContainer, _super);
function ControlContainer() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(ControlContainer.prototype, "formDirective", {
/**
* @description
* The top-level form directive for the control.
*/
get: function () {
return null;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ControlContainer.prototype, "path", {
/**
* @description
* The path to this group.
*/
get: function () {
return null;
},
enumerable: false,
configurable: true
});
return ControlContainer;
}(AbstractControlDirective));
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function unimplemented() {
throw new Error('unimplemented');
}
/**
* @description
* A base class that all control `FormControl`-based directives extend. It binds a `FormControl`
* object to a DOM element.
*
* @publicApi
*/
var NgControl = /** @class */ (function (_super) {
__extends(NgControl, _super);
function NgControl() {
var _this = _super !== null && _super.apply(this, arguments) || this;
/**
* @description
* The parent form for the control.
*
* @internal
*/
_this._parent = null;
/**
* @description
* The name for the control
*/
_this.name = null;
/**
* @description
* The value accessor for the control
*/
_this.valueAccessor = null;
/**
* @description
* The uncomposed array of synchronous validators for the control
*
* @internal
*/
_this._rawValidators = [];
/**
* @description
* The uncomposed array of async validators for the control
*
* @internal
*/
_this._rawAsyncValidators = [];
return _this;
}
Object.defineProperty(NgControl.prototype, "validator", {
/**
* @description
* The registered synchronous validator function for the control
*
* @throws An exception that this method is not implemented
*/
get: function () {
return unimplemented();
},
enumerable: false,
configurable: true
});
Object.defineProperty(NgControl.prototype, "asyncValidator", {
/**
* @description
* The registered async validator function for the control
*
* @throws An exception that this method is not implemented
*/
get: function () {
return unimplemented();
},
enumerable: false,
configurable: true
});
return NgControl;
}(AbstractControlDirective));
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var AbstractControlStatus = /** @class */ (function () {
function AbstractControlStatus(cd) {
this._cd = cd;
}
Object.defineProperty(AbstractControlStatus.prototype, "ngClassUntouched", {
get: function () {
return this._cd.control ? this._cd.control.untouched : false;
},
enumerable: false,
configurable: true
});
Object.defineProperty(AbstractControlStatus.prototype, "ngClassTouched", {
get: function () {
return this._cd.control ? this._cd.control.touched : false;
},
enumerable: false,
configurable: true
});
Object.defineProperty(AbstractControlStatus.prototype, "ngClassPristine", {
get: function () {
return this._cd.control ? this._cd.control.pristine : false;
},
enumerable: false,
configurable: true
});
Object.defineProperty(AbstractControlStatus.prototype, "ngClassDirty", {
get: function () {
return this._cd.control ? this._cd.control.dirty : false;
},
enumerable: false,
configurable: true
});
Object.defineProperty(AbstractControlStatus.prototype, "ngClassValid", {
get: function () {
return this._cd.control ? this._cd.control.valid : false;
},
enumerable: false,
configurable: true
});
Object.defineProperty(AbstractControlStatus.prototype, "ngClassInvalid", {
get: function () {
return this._cd.control ? this._cd.control.invalid : false;
},
enumerable: false,
configurable: true
});
Object.defineProperty(AbstractControlStatus.prototype, "ngClassPending", {
get: function () {
return this._cd.control ? this._cd.control.pending : false;
},
enumerable: false,
configurable: true
});
return AbstractControlStatus;
}());
var ngControlStatusHost = {
'[class.ng-untouched]': 'ngClassUntouched',
'[class.ng-touched]': 'ngClassTouched',
'[class.ng-pristine]': 'ngClassPristine',
'[class.ng-dirty]': 'ngClassDirty',
'[class.ng-valid]': 'ngClassValid',
'[class.ng-invalid]': 'ngClassInvalid',
'[class.ng-pending]': 'ngClassPending',
};
/**
* @description
* Directive automatically applied to Angular form controls that sets CSS classes
* based on control status.
*
* @usageNotes
*
* ### CSS classes applied
*
* The following classes are applied as the properties become true:
*
* * ng-valid
* * ng-invalid
* * ng-pending
* * ng-pristine
* * ng-dirty
* * ng-untouched
* * ng-touched
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
var NgControlStatus = /** @class */ (function (_super) {
__extends(NgControlStatus, _super);
function NgControlStatus(cd) {
return _super.call(this, cd) || this;
}
NgControlStatus.decorators = [
{ type: core.Directive, args: [{ selector: '[formControlName],[ngModel],[formControl]', host: ngControlStatusHost },] }
];
NgControlStatus.ctorParameters = function () { return [
{ type: NgControl, decorators: [{ type: core.Self }] }
]; };
return NgControlStatus;
}(AbstractControlStatus));
/**
* @description
* Directive automatically applied to Angular form groups that sets CSS classes
* based on control status (valid/invalid/dirty/etc).
*
* @see `NgControlStatus`
*
* @ngModule ReactiveFormsModule
* @ngModule FormsModule
* @publicApi
*/
var NgControlStatusGroup = /** @class */ (function (_super) {
__extends(NgControlStatusGroup, _super);
function NgControlStatusGroup(cd) {
return _super.call(this, cd) || this;
}
NgControlStatusGroup.decorators = [
{ type: core.Directive, args: [{
selector: '[formGroupName],[formArrayName],[ngModelGroup],[formGroup],form:not([ngNoForm]),[ngForm]',
host: ngControlStatusHost
},] }
];
NgControlStatusGroup.ctorParameters = function () { return [
{ type: ControlContainer, decorators: [{ type: core.Self }] }
]; };
return NgControlStatusGroup;
}(AbstractControlStatus));
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function isEmptyInputValue(value) {
// we don't check for string here so it also works with arrays
return value == null || value.length === 0;
}
function hasValidLength(value) {
// non-strict comparison is intentional, to check for both `null` and `undefined` values
return value != null && typeof value.length === 'number';
}
/**
* @description
* An `InjectionToken` for registering additional synchronous validators used with
* `AbstractControl`s.
*
* @see `NG_ASYNC_VALIDATORS`
*
* @usageNotes
*
* ### Providing a custom validator
*
* The following example registers a custom validator directive. Adding the validator to the
* existing collection of validators requires the `multi: true` option.
*
* ```typescript
* @Directive({
* selector: '[customValidator]',
* providers: [{provide: NG_VALIDATORS, useExisting: CustomValidatorDirective, multi: true}]
* })
* class CustomValidatorDirective implements Validator {
* validate(control: AbstractControl): ValidationErrors | null {
* return { 'custom': true };
* }
* }
* ```
*
* @publicApi
*/
var NG_VALIDATORS = new core.InjectionToken('NgValidators');
/**
* @description
* An `InjectionToken` for registering additional asynchronous validators used with
* `AbstractControl`s.
*
* @see `NG_VALIDATORS`
*
* @publicApi
*/
var NG_ASYNC_VALIDATORS = new core.InjectionToken('NgAsyncValidators');
/**
* A regular expression that matches valid e-mail addresses.
*
* At a high level, this regexp matches e-mail addresses of the format `local-part@tld`, where:
* - `local-part` consists of one or more of the allowed characters (alphanumeric and some
* punctuation symbols).
* - `local-part` cannot begin or end with a period (`.`).
* - `local-part` cannot be longer than 64 characters.
* - `tld` consists of one or more `labels` separated by periods (`.`). For example `localhost` or
* `foo.com`.
* - A `label` consists of one or more of the allowed characters (alphanumeric, dashes (`-`) and
* periods (`.`)).
* - A `label` cannot begin or end with a dash (`-`) or a period (`.`).
* - A `label` cannot be longer than 63 characters.
* - The whole address cannot be longer than 254 characters.
*
* ## Implementation background
*
* This regexp was ported over from AngularJS (see there for git history):
* https://github.com/angular/angular.js/blob/c133ef836/src/ng/directive/input.js#L27
* It is based on the
* [WHATWG version](https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address) with
* some enhancements to incorporate more RFC rules (such as rules related to domain names and the
* lengths of different parts of the address). The main differences from the WHATWG version are:
* - Disallow `local-part` to begin or end with a period (`.`).
* - Disallow `local-part` length to exceed 64 characters.
* - Disallow total address length to exceed 254 characters.
*
* See [this commit](https://github.com/angular/angular.js/commit/f3f5cf72e) for more details.
*/
var EMAIL_REGEXP = /^(?=.{1,254}$)(?=.{1,64}@)[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
/**
* @description
* Provides a set of built-in validators that can be used by form controls.
*
* A validator is a function that processes a `FormControl` or collection of
* controls and returns an error map or null. A null map means that validation has passed.
*
* @see [Form Validation](/guide/form-validation)
*
* @publicApi
*/
var Validators = /** @class */ (function () {
function Validators() {
}
/**
* @description
* Validator that requires the control's value to be greater than or equal to the provided number.
* The validator exists only as a function and not as a directive.
*
* @usageNotes
*
* ### Validate against a minimum of 3
*
* ```typescript
* const control = new FormControl(2, Validators.min(3));
*
* console.log(control.errors); // {min: {min: 3, actual: 2}}
* ```
*
* @returns A validator function that returns an error map with the
* `min` property if the validation check fails, otherwise `null`.
*
* @see `updateValueAndValidity()`
*
*/
Validators.min = function (min) {
return function (control) {
if (isEmptyInputValue(control.value) || isEmptyInputValue(min)) {
return null; // don't validate empty values to allow optional controls
}
var value = parseFloat(control.value);
// Controls with NaN values after parsing should be treated as not having a
// minimum, per the HTML forms spec: https://www.w3.org/TR/html5/forms.html#attr-input-min
return !isNaN(value) && value < min ? { 'min': { 'min': min, 'actual': control.value } } : null;
};
};
/**
* @description
* Validator that requires the control's value to be less than or equal to the provided number.
* The validator exists only as a function and not as a directive.
*
* @usageNotes
*
* ### Validate against a maximum of 15
*
* ```typescript
* const control = new FormControl(16, Validators.max(15));
*
* console.log(control.errors); // {max: {max: 15, actual: 16}}
* ```
*
* @returns A validator function that returns an error map with the
* `max` property if the validation check fails, otherwise `null`.
*
* @see `updateValueAndValidity()`
*
*/
Validators.max = function (max) {
return function (control) {
if (isEmptyInputValue(control.value) || isEmptyInputValue(max)) {
return null; // don't validate empty values to allow optional controls
}
var value = parseFloat(control.value);
// Controls with NaN values after parsing should be treated as not having a
// maximum, per the HTML forms spec: https://www.w3.org/TR/html5/forms.html#attr-input-max
return !isNaN(value) && value > max ? { 'max': { 'max': max, 'actual': control.value } } : null;
};
};
/**
* @description
* Validator that requires the control have a non-empty value.
*
* @usageNotes
*
* ### Validate that the field is non-empty
*
* ```typescript
* const control = new FormControl('', Validators.required);
*
* console.log(control.errors); // {required: true}
* ```
*
* @returns An error map with the `required` property
* if the validation check fails, otherwise `null`.
*
* @see `updateValueAndValidity()`
*