/
model.ts
1932 lines (1766 loc) Β· 62.7 KB
/
model.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* Copyright Google Inc. 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
*/
import {EventEmitter} from '@angular/core';
import {Observable} from 'rxjs';
import {composeAsyncValidators, composeValidators} from './directives/shared';
import {AsyncValidatorFn, ValidationErrors, ValidatorFn} from './directives/validators';
import {toObservable} from './validators';
/**
* Reports that a FormControl is valid, meaning that no errors exist in the input value.
*
* @see `status`
*/
export const VALID = 'VALID';
/**
* Reports that a FormControl is invalid, meaning that an error exists in the input value.
*
* @see `status`
*/
export const INVALID = 'INVALID';
/**
* Reports that a FormControl is pending, meaning that that async validation is occurring and
* errors are not yet available for the input value.
*
* @see `markAsPending`
* @see `status`
*/
export const PENDING = 'PENDING';
/**
* Reports that a FormControl is disabled, meaning that the control is exempt from ancestor
* calculations of validity or value.
*
* @see `markAsDisabled`
* @see `status`
*/
export const DISABLED = 'DISABLED';
function _find(control: AbstractControl, path: Array<string|number>| string, delimiter: string) {
if (path == null) return null;
if (!(path instanceof Array)) {
path = (<string>path).split(delimiter);
}
if (path instanceof Array && (path.length === 0)) return null;
return (<Array<string|number>>path).reduce((v: AbstractControl, name) => {
if (v instanceof FormGroup) {
return v.controls.hasOwnProperty(name as string) ? v.controls[name] : null;
}
if (v instanceof FormArray) {
return v.at(<number>name) || null;
}
return null;
}, control);
}
function coerceToValidator(
validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null): ValidatorFn|
null {
const validator =
(isOptionsObj(validatorOrOpts) ? (validatorOrOpts as AbstractControlOptions).validators :
validatorOrOpts) as ValidatorFn |
ValidatorFn[] | null;
return Array.isArray(validator) ? composeValidators(validator) : validator || null;
}
function coerceToAsyncValidator(
asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null, validatorOrOpts?: ValidatorFn |
ValidatorFn[] | AbstractControlOptions | null): AsyncValidatorFn|null {
const origAsyncValidator =
(isOptionsObj(validatorOrOpts) ? (validatorOrOpts as AbstractControlOptions).asyncValidators :
asyncValidator) as AsyncValidatorFn |
AsyncValidatorFn | null;
return Array.isArray(origAsyncValidator) ? composeAsyncValidators(origAsyncValidator) :
origAsyncValidator || null;
}
export type FormHooks = 'change' | 'blur' | 'submit';
/**
* Interface for options provided to an `AbstractControl`.
*
* @publicApi
*/
export interface AbstractControlOptions {
/**
* @description
* The list of validators applied to a control.
*/
validators?: ValidatorFn|ValidatorFn[]|null;
/**
* @description
* The list of async validators applied to control.
*/
asyncValidators?: AsyncValidatorFn|AsyncValidatorFn[]|null;
/**
* @description
* The event name for control to update upon.
*/
updateOn?: 'change'|'blur'|'submit';
}
function isOptionsObj(
validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null): boolean {
return validatorOrOpts != null && !Array.isArray(validatorOrOpts) &&
typeof validatorOrOpts === 'object';
}
/**
* This is the base class for `FormControl`, `FormGroup`, and `FormArray`.
*
* It provides some of the shared behavior that all controls and groups of controls have, like
* running validators, calculating status, and resetting state. It also defines the properties
* that are shared between all sub-classes, like `value`, `valid`, and `dirty`. It shouldn't be
* instantiated directly.
*
* @see [Forms Guide](/guide/forms)
* @see [Reactive Forms Guide](/guide/reactive-forms)
* @see [Dynamic Forms Guide](/guide/dynamic-form)
*
* @publicApi
*/
export abstract class AbstractControl {
/** @internal */
// TODO(issue/24571): remove '!'.
_pendingDirty !: boolean;
/** @internal */
// TODO(issue/24571): remove '!'.
_pendingTouched !: boolean;
/** @internal */
_onCollectionChange = () => {};
/** @internal */
// TODO(issue/24571): remove '!'.
_updateOn !: FormHooks;
// TODO(issue/24571): remove '!'.
private _parent !: FormGroup | FormArray;
private _asyncValidationSubscription: any;
/**
* The current value of the control.
*
* * For a `FormControl`, the current value.
* * For a `FormGroup`, the values of enabled controls as an object
* with a key-value pair for each member of the group.
* * For a `FormArray`, the values of enabled controls as an array.
*
*/
public readonly value: any;
/**
* Initialize the AbstractControl instance.
*
* @param validator The function that determines the synchronous validity of this control.
* @param asyncValidator The function that determines the asynchronous validity of this
* control.
*/
constructor(public validator: ValidatorFn|null, public asyncValidator: AsyncValidatorFn|null) {}
/**
* The parent control.
*/
get parent(): FormGroup|FormArray { return this._parent; }
/**
* The validation status of the control. There are four possible
* validation status values:
*
* * **VALID**: This control has passed all validation checks.
* * **INVALID**: This control has failed at least one validation check.
* * **PENDING**: This control is in the midst of conducting a validation check.
* * **DISABLED**: This control is exempt from validation checks.
*
* These status values are mutually exclusive, so a control cannot be
* both valid AND invalid or invalid AND disabled.
*/
// TODO(issue/24571): remove '!'.
public readonly status !: string;
/**
* A control is `valid` when its `status` is `VALID`.
*
* @see {@link AbstractControl.status}
*
* @returns True if the control has passed all of its validation tests,
* false otherwise.
*/
get valid(): boolean { return this.status === VALID; }
/**
* A control is `invalid` when its `status` is `INVALID`.
*
* @see {@link AbstractControl.status}
*
* @returns True if this control has failed one or more of its validation checks,
* false otherwise.
*/
get invalid(): boolean { return this.status === INVALID; }
/**
* A control is `pending` when its `status` is `PENDING`.
*
* @see {@link AbstractControl.status}
*
* @returns True if this control is in the process of conducting a validation check,
* false otherwise.
*/
get pending(): boolean { return this.status == PENDING; }
/**
* A control is `disabled` when its `status` is `DISABLED`.
*
* Disabled controls are exempt from validation checks and
* are not included in the aggregate value of their ancestor
* controls.
*
* @see {@link AbstractControl.status}
*
* @returns True if the control is disabled, false otherwise.
*/
get disabled(): boolean { return this.status === DISABLED; }
/**
* A control is `enabled` as long as its `status` is not `DISABLED`.
*
* @returns True if the control has any status other than 'DISABLED',
* false if the status is 'DISABLED'.
*
* @see {@link AbstractControl.status}
*
*/
get enabled(): boolean { return this.status !== DISABLED; }
/**
* An object containing any errors generated by failing validation,
* or null if there are no errors.
*/
// TODO(issue/24571): remove '!'.
public readonly errors !: ValidationErrors | null;
/**
* A control is `pristine` if the user has not yet changed
* the value in the UI.
*
* @returns True if the user has not yet changed the value in the UI; compare `dirty`.
* Programmatic changes to a control's value do not mark it dirty.
*/
public readonly pristine: boolean = true;
/**
* A control is `dirty` if the user has changed the value
* in the UI.
*
* @returns True if the user has changed the value of this control in the UI; compare `pristine`.
* Programmatic changes to a control's value do not mark it dirty.
*/
get dirty(): boolean { return !this.pristine; }
/**
* True if the control is marked as `touched`.
*
* A control is marked `touched` once the user has triggered
* a `blur` event on it.
*/
public readonly touched: boolean = false;
/**
* True if the control has not been marked as touched
*
* A control is `untouched` if the user has not yet triggered
* a `blur` event on it.
*/
get untouched(): boolean { return !this.touched; }
/**
* A multicasting observable that emits an event every time the value of the control changes, in
* the UI or programmatically.
*/
// TODO(issue/24571): remove '!'.
public readonly valueChanges !: Observable<any>;
/**
* A multicasting observable that emits an event every time the validation `status` of the control
* recalculates.
*
* @see {@link AbstractControl.status}
*
*/
// TODO(issue/24571): remove '!'.
public readonly statusChanges !: Observable<any>;
/**
* Reports the update strategy of the `AbstractControl` (meaning
* the event on which the control updates itself).
* Possible values: `'change'` | `'blur'` | `'submit'`
* Default value: `'change'`
*/
get updateOn(): FormHooks {
return this._updateOn ? this._updateOn : (this.parent ? this.parent.updateOn : 'change');
}
/**
* Sets the synchronous validators that are active on this control. Calling
* this overwrites any existing sync validators.
*/
setValidators(newValidator: ValidatorFn|ValidatorFn[]|null): void {
this.validator = coerceToValidator(newValidator);
}
/**
* Sets the async validators that are active on this control. Calling this
* overwrites any existing async validators.
*/
setAsyncValidators(newValidator: AsyncValidatorFn|AsyncValidatorFn[]|null): void {
this.asyncValidator = coerceToAsyncValidator(newValidator);
}
/**
* Empties out the sync validator list.
*/
clearValidators(): void { this.validator = null; }
/**
* Empties out the async validator list.
*/
clearAsyncValidators(): void { this.asyncValidator = null; }
/**
* Marks the control as `touched`. A control is touched by focus and
* blur events that do not change the value.
*
* @see `markAsUntouched()`
* @see `markAsDirty()`
* @see `markAsPristine()`
*
* @param opts Configuration options that determine how the control propagates changes
* and emits events events after marking is applied.
* * `onlySelf`: When true, mark only this control. When false or not supplied,
* marks all direct ancestors. Default is false.
*/
markAsTouched(opts: {onlySelf?: boolean} = {}): void {
(this as{touched: boolean}).touched = true;
if (this._parent && !opts.onlySelf) {
this._parent.markAsTouched(opts);
}
}
/**
* Marks the control as `untouched`.
*
* If the control has any children, also marks all children as `untouched`
* and recalculates the `touched` status of all parent controls.
*
* @see `markAsTouched()`
* @see `markAsDirty()`
* @see `markAsPristine()`
*
* @param opts Configuration options that determine how the control propagates changes
* and emits events after the marking is applied.
* * `onlySelf`: When true, mark only this control. When false or not supplied,
* marks all direct ancestors. Default is false.
*/
markAsUntouched(opts: {onlySelf?: boolean} = {}): void {
(this as{touched: boolean}).touched = false;
this._pendingTouched = false;
this._forEachChild(
(control: AbstractControl) => { control.markAsUntouched({onlySelf: true}); });
if (this._parent && !opts.onlySelf) {
this._parent._updateTouched(opts);
}
}
/**
* Marks the control as `dirty`. A control becomes dirty when
* the control's value is changed through the UI; compare `markAsTouched`.
*
* @see `markAsTouched()`
* @see `markAsUntouched()`
* @see `markAsPristine()`
*
* @param opts Configuration options that determine how the control propagates changes
* and emits events after marking is applied.
* * `onlySelf`: When true, mark only this control. When false or not supplied,
* marks all direct ancestors. Default is false.
*/
markAsDirty(opts: {onlySelf?: boolean} = {}): void {
(this as{pristine: boolean}).pristine = false;
if (this._parent && !opts.onlySelf) {
this._parent.markAsDirty(opts);
}
}
/**
* Marks the control as `pristine`.
*
* If the control has any children, marks all children as `pristine`,
* and recalculates the `pristine` status of all parent
* controls.
*
* @see `markAsTouched()`
* @see `markAsUntouched()`
* @see `markAsDirty()`
*
* @param opts Configuration options that determine how the control emits events after
* marking is applied.
* * `onlySelf`: When true, mark only this control. When false or not supplied,
* marks all direct ancestors. Default is false..
*/
markAsPristine(opts: {onlySelf?: boolean} = {}): void {
(this as{pristine: boolean}).pristine = true;
this._pendingDirty = false;
this._forEachChild((control: AbstractControl) => { control.markAsPristine({onlySelf: true}); });
if (this._parent && !opts.onlySelf) {
this._parent._updatePristine(opts);
}
}
/**
* Marks the control as `pending`.
*
* A control is pending while the control performs async validation.
*
* @see {@link AbstractControl.status}
*
* @param opts Configuration options that determine how the control propagates changes and
* emits events after marking is applied.
* * `onlySelf`: When true, mark only this control. When false or not supplied,
* marks all direct ancestors. Default is false..
* * `emitEvent`: When true or not supplied (the default), the `statusChanges`
* observable emits an event with the latest status the control is marked pending.
* When false, no events are emitted.
*
*/
markAsPending(opts: {onlySelf?: boolean, emitEvent?: boolean} = {}): void {
(this as{status: string}).status = PENDING;
if (opts.emitEvent !== false) {
(this.statusChanges as EventEmitter<any>).emit(this.status);
}
if (this._parent && !opts.onlySelf) {
this._parent.markAsPending(opts);
}
}
/**
* Disables the control. This means the control is exempt from validation checks and
* excluded from the aggregate value of any parent. Its status is `DISABLED`.
*
* If the control has children, all children are also disabled.
*
* @see {@link AbstractControl.status}
*
* @param opts Configuration options that determine how the control propagates
* changes and emits events after the control is disabled.
* * `onlySelf`: When true, mark only this control. When false or not supplied,
* marks all direct ancestors. Default is false..
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges`
* observables emit events with the latest status and value when the control is disabled.
* When false, no events are emitted.
*/
disable(opts: {onlySelf?: boolean, emitEvent?: boolean} = {}): void {
(this as{status: string}).status = DISABLED;
(this as{errors: ValidationErrors | null}).errors = null;
this._forEachChild(
(control: AbstractControl) => { control.disable({...opts, onlySelf: true}); });
this._updateValue();
if (opts.emitEvent !== false) {
(this.valueChanges as EventEmitter<any>).emit(this.value);
(this.statusChanges as EventEmitter<string>).emit(this.status);
}
this._updateAncestors(opts);
this._onDisabledChange.forEach((changeFn) => changeFn(true));
}
/**
* Enables the control. This means the control is included in validation checks and
* the aggregate value of its parent. Its status recalculates based on its value and
* its validators.
*
* By default, if the control has children, all children are enabled.
*
* @see {@link AbstractControl.status}
*
* @param opts Configure options that control how the control propagates changes and
* emits events when marked as untouched
* * `onlySelf`: When true, mark only this control. When false or not supplied,
* marks all direct ancestors. Default is false..
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges`
* observables emit events with the latest status and value when the control is enabled.
* When false, no events are emitted.
*/
enable(opts: {onlySelf?: boolean, emitEvent?: boolean} = {}): void {
(this as{status: string}).status = VALID;
this._forEachChild(
(control: AbstractControl) => { control.enable({...opts, onlySelf: true}); });
this.updateValueAndValidity({onlySelf: true, emitEvent: opts.emitEvent});
this._updateAncestors(opts);
this._onDisabledChange.forEach((changeFn) => changeFn(false));
}
private _updateAncestors(opts: {onlySelf?: boolean, emitEvent?: boolean}) {
if (this._parent && !opts.onlySelf) {
this._parent.updateValueAndValidity(opts);
this._parent._updatePristine();
this._parent._updateTouched();
}
}
/**
* @param parent Sets the parent of the control
*/
setParent(parent: FormGroup|FormArray): void { this._parent = parent; }
/**
* Sets the value of the control. Abstract method (implemented in sub-classes).
*/
abstract setValue(value: any, options?: Object): void;
/**
* Patches the value of the control. Abstract method (implemented in sub-classes).
*/
abstract patchValue(value: any, options?: Object): void;
/**
* Resets the control. Abstract method (implemented in sub-classes).
*/
abstract reset(value?: any, options?: Object): void;
/**
* Recalculates the value and validation status of the control.
*
* By default, it also updates the value and validity of its ancestors.
*
* @param opts Configuration options determine how the control propagates changes and emits events
* after updates and validity checks are applied.
* * `onlySelf`: When true, only update this control. When false or not supplied,
* update all direct ancestors. Default is false..
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges`
* observables emit events with the latest status and value when the control is updated.
* When false, no events are emitted.
*/
updateValueAndValidity(opts: {onlySelf?: boolean, emitEvent?: boolean} = {}): void {
this._setInitialStatus();
this._updateValue();
if (this.enabled) {
this._cancelExistingSubscription();
(this as{errors: ValidationErrors | null}).errors = this._runValidator();
(this as{status: string}).status = this._calculateStatus();
if (this.status === VALID || this.status === PENDING) {
this._runAsyncValidator(opts.emitEvent);
}
}
if (opts.emitEvent !== false) {
(this.valueChanges as EventEmitter<any>).emit(this.value);
(this.statusChanges as EventEmitter<string>).emit(this.status);
}
if (this._parent && !opts.onlySelf) {
this._parent.updateValueAndValidity(opts);
}
}
/** @internal */
_updateTreeValidity(opts: {emitEvent?: boolean} = {emitEvent: true}) {
this._forEachChild((ctrl: AbstractControl) => ctrl._updateTreeValidity(opts));
this.updateValueAndValidity({onlySelf: true, emitEvent: opts.emitEvent});
}
private _setInitialStatus() {
(this as{status: string}).status = this._allControlsDisabled() ? DISABLED : VALID;
}
private _runValidator(): ValidationErrors|null {
return this.validator ? this.validator(this) : null;
}
private _runAsyncValidator(emitEvent?: boolean): void {
if (this.asyncValidator) {
(this as{status: string}).status = PENDING;
const obs = toObservable(this.asyncValidator(this));
this._asyncValidationSubscription =
obs.subscribe((errors: ValidationErrors | null) => this.setErrors(errors, {emitEvent}));
}
}
private _cancelExistingSubscription(): void {
if (this._asyncValidationSubscription) {
this._asyncValidationSubscription.unsubscribe();
}
}
/**
* Sets errors on a form control when running validations manually, rather than automatically.
*
* Calling `setErrors` also updates the validity of the parent control.
*
* @usageNotes
* ### Manually set the errors for a control
*
* ```
* const login = new FormControl('someLogin');
* login.setErrors({
* notUnique: true
* });
*
* expect(login.valid).toEqual(false);
* expect(login.errors).toEqual({ notUnique: true });
*
* login.setValue('someOtherLogin');
*
* expect(login.valid).toEqual(true);
* ```
*/
setErrors(errors: ValidationErrors|null, opts: {emitEvent?: boolean} = {}): void {
(this as{errors: ValidationErrors | null}).errors = errors;
this._updateControlsErrors(opts.emitEvent !== false);
}
/**
* Retrieves a child control given the control's name or path.
*
* @param path A dot-delimited string or array of string/number values that define the path to the
* control.
*
* @usageNotes
* ### Retrieve a nested control
*
* For example, to get a `name` control nested within a `person` sub-group:
*
* * `this.form.get('person.name');`
*
* -OR-
*
* * `this.form.get(['person', 'name']);`
*/
get(path: Array<string|number>|string): AbstractControl|null { return _find(this, path, '.'); }
/**
* @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.
*/
getError(errorCode: string, path?: Array<string|number>|string): any {
const control = path ? this.get(path) : this;
return control && control.errors ? control.errors[errorCode] : null;
}
/**
* @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.
*/
hasError(errorCode: string, path?: Array<string|number>|string): boolean {
return !!this.getError(errorCode, path);
}
/**
* Retrieves the top-level ancestor of this control.
*/
get root(): AbstractControl {
let x: AbstractControl = this;
while (x._parent) {
x = x._parent;
}
return x;
}
/** @internal */
_updateControlsErrors(emitEvent: boolean): void {
(this as{status: string}).status = this._calculateStatus();
if (emitEvent) {
(this.statusChanges as EventEmitter<string>).emit(this.status);
}
if (this._parent) {
this._parent._updateControlsErrors(emitEvent);
}
}
/** @internal */
_initObservables() {
(this as{valueChanges: Observable<any>}).valueChanges = new EventEmitter();
(this as{statusChanges: Observable<any>}).statusChanges = new EventEmitter();
}
private _calculateStatus(): string {
if (this._allControlsDisabled()) return DISABLED;
if (this.errors) return INVALID;
if (this._anyControlsHaveStatus(PENDING)) return PENDING;
if (this._anyControlsHaveStatus(INVALID)) return INVALID;
return VALID;
}
/** @internal */
abstract _updateValue(): void;
/** @internal */
abstract _forEachChild(cb: Function): void;
/** @internal */
abstract _anyControls(condition: Function): boolean;
/** @internal */
abstract _allControlsDisabled(): boolean;
/** @internal */
abstract _syncPendingControls(): boolean;
/** @internal */
_anyControlsHaveStatus(status: string): boolean {
return this._anyControls((control: AbstractControl) => control.status === status);
}
/** @internal */
_anyControlsDirty(): boolean {
return this._anyControls((control: AbstractControl) => control.dirty);
}
/** @internal */
_anyControlsTouched(): boolean {
return this._anyControls((control: AbstractControl) => control.touched);
}
/** @internal */
_updatePristine(opts: {onlySelf?: boolean} = {}): void {
(this as{pristine: boolean}).pristine = !this._anyControlsDirty();
if (this._parent && !opts.onlySelf) {
this._parent._updatePristine(opts);
}
}
/** @internal */
_updateTouched(opts: {onlySelf?: boolean} = {}): void {
(this as{touched: boolean}).touched = this._anyControlsTouched();
if (this._parent && !opts.onlySelf) {
this._parent._updateTouched(opts);
}
}
/** @internal */
_onDisabledChange: Function[] = [];
/** @internal */
_isBoxedValue(formState: any): boolean {
return typeof formState === 'object' && formState !== null &&
Object.keys(formState).length === 2 && 'value' in formState && 'disabled' in formState;
}
/** @internal */
_registerOnCollectionChange(fn: () => void): void { this._onCollectionChange = fn; }
/** @internal */
_setUpdateStrategy(opts?: ValidatorFn|ValidatorFn[]|AbstractControlOptions|null): void {
if (isOptionsObj(opts) && (opts as AbstractControlOptions).updateOn != null) {
this._updateOn = (opts as AbstractControlOptions).updateOn !;
}
}
}
/**
* Tracks the value and validation status of an individual form control.
*
* This is one of the three fundamental building blocks of Angular forms, along with
* `FormGroup` and `FormArray`. It extends the `AbstractControl` class that
* implements most of the base functionality for accessing the value, validation status,
* user interactions and events.
*
* @see `AbstractControl`
* @see [Reactive Forms Guide](guide/reactive-forms)
* @see [Usage Notes](#usage-notes)
*
* @usageNotes
*
* ### Initializing Form Controls
*
* Instantiate a `FormControl`, with an initial value.
*
* ```ts
* const control = new FormControl('some value');
* console.log(control.value); // 'some value'
*```
*
* The following example initializes the control with a form state object. The `value`
* and `disabled` keys are required in this case.
*
* ```ts
* const control = new FormControl({ value: 'n/a', disabled: true });
* console.log(control.value); // 'n/a'
* console.log(control.status); // 'DISABLED'
* ```
*
* The following example initializes the control with a sync validator.
*
* ```ts
* const control = new FormControl('', Validators.required);
* console.log(control.value); // ''
* console.log(control.status); // 'INVALID'
* ```
*
* The following example initializes the control using an options object.
*
* ```ts
* const control = new FormControl('', {
* validators: Validators.required,
* asyncValidators: myAsyncValidator
* });
* ```
*
* ### Configure the control to update on a blur event
*
* Set the `updateOn` option to `'blur'` to update on the blur `event`.
*
* ```ts
* const control = new FormControl('', { updateOn: 'blur' });
* ```
*
* ### Configure the control to update on a submit event
*
* Set the `updateOn` option to `'submit'` to update on a submit `event`.
*
* ```ts
* const control = new FormControl('', { updateOn: 'submit' });
* ```
*
* ### Reset the control back to an initial value
*
* You reset to a specific form state by passing through a standalone
* value or a form state object that contains both a value and a disabled state
* (these are the only two properties that cannot be calculated).
*
* ```ts
* const control = new FormControl('Nancy');
*
* console.log(control.value); // 'Nancy'
*
* control.reset('Drew');
*
* console.log(control.value); // 'Drew'
* ```
*
* ### Reset the control back to an initial value and disabled
*
* ```
* const control = new FormControl('Nancy');
*
* console.log(control.value); // 'Nancy'
* console.log(control.status); // 'VALID'
*
* control.reset({ value: 'Drew', disabled: true });
*
* console.log(control.value); // 'Drew'
* console.log(control.status); // 'DISABLED'
* ```
*
* @publicApi
*/
export class FormControl extends AbstractControl {
/** @internal */
_onChange: Function[] = [];
/** @internal */
_pendingValue: any;
/** @internal */
_pendingChange: any;
/**
* Creates a new `FormControl` instance.
*
* @param formState Initializes the control with an initial value,
* or an object that defines the initial value and disabled state.
*
* @param validatorOrOpts A synchronous validator function, or an array of
* such functions, or an `AbstractControlOptions` object that contains validation functions
* and a validation trigger.
*
* @param asyncValidator A single async validator or array of async validator functions
*
*/
constructor(
formState: any = null,
validatorOrOpts?: ValidatorFn|ValidatorFn[]|AbstractControlOptions|null,
asyncValidator?: AsyncValidatorFn|AsyncValidatorFn[]|null) {
super(
coerceToValidator(validatorOrOpts),
coerceToAsyncValidator(asyncValidator, validatorOrOpts));
this._applyFormState(formState);
this._setUpdateStrategy(validatorOrOpts);
this.updateValueAndValidity({onlySelf: true, emitEvent: false});
this._initObservables();
}
/**
* Sets a new value for the form control.
*
* @param value The new value for the control.
* @param options Configuration options that determine how the control proopagates changes
* and emits events when the value changes.
* The configuration options are passed to the {@link AbstractControl#updateValueAndValidity
* updateValueAndValidity} method.
*
* * `onlySelf`: When true, each change only affects this control, and not its parent. Default is
* false.
* * `emitEvent`: When true or not supplied (the default), both the `statusChanges` and
* `valueChanges`
* observables emit events with the latest status and value when the control value is updated.
* When false, no events are emitted.
* * `emitModelToViewChange`: When true or not supplied (the default), each change triggers an
* `onChange` event to
* update the view.
* * `emitViewToModelChange`: When true or not supplied (the default), each change triggers an
* `ngModelChange`
* event to update the model.