/
form_control.ts
614 lines (559 loc) Β· 18 KB
/
form_control.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
/**
* @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
*/
import {Ι΅Writable as Writable} from '@angular/core';
import {AsyncValidatorFn, ValidatorFn} from '../directives/validators';
import {removeListItem} from '../util';
import {
AbstractControl,
AbstractControlOptions,
isOptionsObj,
pickAsyncValidators,
pickValidators,
} from './abstract_model';
/**
* FormControlState is a boxed form value. It is an object with a `value` key and a `disabled` key.
*
* @publicApi
*/
export interface FormControlState<T> {
value: T;
disabled: boolean;
}
/**
* Interface for options provided to a `FormControl`.
*
* This interface extends all options from {@link AbstractControlOptions}, plus some options
* unique to `FormControl`.
*
* @publicApi
*/
export interface FormControlOptions extends AbstractControlOptions {
/**
* @description
* Whether to use the initial value used to construct the `FormControl` as its default value
* as well. If this option is false or not provided, the default value of a FormControl is `null`.
* When a FormControl is reset without an explicit value, its value reverts to
* its default value.
*/
nonNullable?: boolean;
/**
* @deprecated Use `nonNullable` instead.
*/
initialValueIsDefault?: boolean;
}
/**
* Tracks the value and validation status of an individual form control.
*
* This is one of the four fundamental building blocks of Angular forms, along with
* `FormGroup`, `FormArray` and `FormRecord`. It extends the `AbstractControl` class that
* implements most of the base functionality for accessing the value, validation status,
* user interactions and events.
*
* `FormControl` takes a single generic argument, which describes the type of its value. This
* argument always implicitly includes `null` because the control can be reset. To change this
* behavior, set `nonNullable` or see the usage notes below.
*
* See [usage examples below](#usage-notes).
*
* @see {@link AbstractControl}
* @see [Reactive Forms Guide](guide/forms/reactive-forms)
* @see [Usage Notes](#usage-notes)
*
* @publicApi
*
* @overriddenImplementation Ι΅FormControlCtor
*
* @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 synchronous 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
* });
* ```
*
* ### The single type argument
*
* `FormControl` accepts a generic argument, which describes the type of its value.
* In most cases, this argument will be inferred.
*
* If you are initializing the control to `null`, or you otherwise wish to provide a
* wider type, you may specify the argument explicitly:
*
* ```
* let fc = new FormControl<string|null>(null);
* fc.setValue('foo');
* ```
*
* You might notice that `null` is always added to the type of the control.
* This is because the control will become `null` if you call `reset`. You can change
* this behavior by setting `{nonNullable: true}`.
*
* ### 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 a specific 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 to its initial value
*
* If you wish to always reset the control to its initial value (instead of null),
* you can pass the `nonNullable` option:
*
* ```
* const control = new FormControl('Nancy', {nonNullable: true});
*
* console.log(control.value); // 'Nancy'
*
* control.reset();
*
* console.log(control.value); // 'Nancy'
* ```
*
* ### 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'
* ```
*/
export interface FormControl<TValue = any> extends AbstractControl<TValue> {
/**
* The default value of this FormControl, used whenever the control is reset without an explicit
* value. See {@link FormControlOptions#nonNullable} for more information on configuring
* a default value.
*/
readonly defaultValue: TValue;
/** @internal */
_onChange: Function[];
/**
* This field holds a pending value that has not yet been applied to the form's value.
* @internal
*/
_pendingValue: TValue;
/** @internal */
_pendingChange: boolean;
/**
* 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 propagates 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.
*
*/
setValue(
value: TValue,
options?: {
onlySelf?: boolean;
emitEvent?: boolean;
emitModelToViewChange?: boolean;
emitViewToModelChange?: boolean;
},
): void;
/**
* Patches the value of a control.
*
* This function is functionally the same as {@link FormControl#setValue setValue} at this level.
* It exists for symmetry with {@link FormGroup#patchValue patchValue} on `FormGroups` and
* `FormArrays`, where it does behave differently.
*
* @see {@link FormControl#setValue} for options
*/
patchValue(
value: TValue,
options?: {
onlySelf?: boolean;
emitEvent?: boolean;
emitModelToViewChange?: boolean;
emitViewToModelChange?: boolean;
},
): void;
/**
* Resets the form control, marking it `pristine` and `untouched`, and resetting
* the value. The new value will be the provided value (if passed), `null`, or the initial value
* if `nonNullable` was set in the constructor via {@link FormControlOptions}.
*
* ```ts
* // By default, the control will reset to null.
* const dog = new FormControl('spot');
* dog.reset(); // dog.value is null
*
* // If this flag is set, the control will instead reset to the initial value.
* const cat = new FormControl('tabby', {nonNullable: true});
* cat.reset(); // cat.value is "tabby"
*
* // A value passed to reset always takes precedence.
* const fish = new FormControl('finn', {nonNullable: true});
* fish.reset('bubble'); // fish.value is "bubble"
* ```
*
* @param formState Resets the control with an initial value,
* or an object that defines the initial value and disabled state.
*
* @param options Configuration options that determine how the control propagates changes
* and emits events after the value changes.
*
* * `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 is reset.
* When false, no events are emitted.
*
*/
reset(
formState?: TValue | FormControlState<TValue>,
options?: {
onlySelf?: boolean;
emitEvent?: boolean;
},
): void;
/**
* For a simple FormControl, the raw value is equivalent to the value.
*/
getRawValue(): TValue;
/**
* @internal
*/
_updateValue(): void;
/**
* @internal
*/
_anyControls(condition: (c: AbstractControl) => boolean): boolean;
/**
* @internal
*/
_allControlsDisabled(): boolean;
/**
* Register a listener for change events.
*
* @param fn The method that is called when the value changes
*/
registerOnChange(fn: Function): void;
/**
* Internal function to unregister a change events listener.
* @internal
*/
_unregisterOnChange(fn: (value?: any, emitModelEvent?: boolean) => void): void;
/**
* Register a listener for disabled events.
*
* @param fn The method that is called when the disabled status changes.
*/
registerOnDisabledChange(fn: (isDisabled: boolean) => void): void;
/**
* Internal function to unregister a disabled event listener.
* @internal
*/
_unregisterOnDisabledChange(fn: (isDisabled: boolean) => void): void;
/**
* @internal
*/
_forEachChild(cb: (c: AbstractControl) => void): void;
/** @internal */
_syncPendingControls(): boolean;
}
// This internal interface is present to avoid a naming clash, resulting in the wrong `FormControl`
// symbol being used.
type FormControlInterface<TValue = any> = FormControl<TValue>;
/**
* Various available constructors for `FormControl`.
* Do not use this interface directly. Instead, use `FormControl`:
* ```
* const fc = new FormControl('foo');
* ```
* This symbol is prefixed with Ι΅ to make plain that it is an internal symbol.
*/
export interface Ι΅FormControlCtor {
/**
* Construct a FormControl with no initial value or validators.
*/
new (): FormControl<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 a `FormControlOptions` object that contains validation functions
* and a validation trigger.
*
* @param asyncValidator A single async validator or array of async validator functions
*/
new <T = any>(
value: FormControlState<T> | T,
opts: FormControlOptions & {nonNullable: true},
): FormControl<T>;
/**
* @deprecated Use `nonNullable` instead.
*/
new <T = any>(
value: FormControlState<T> | T,
opts: FormControlOptions & {
initialValueIsDefault: true;
},
): FormControl<T>;
/**
* @deprecated When passing an `options` argument, the `asyncValidator` argument has no effect.
*/
new <T = any>(
value: FormControlState<T> | T,
opts: FormControlOptions,
asyncValidator: AsyncValidatorFn | AsyncValidatorFn[],
): FormControl<T | null>;
new <T = any>(
value: FormControlState<T> | T,
validatorOrOpts?: ValidatorFn | ValidatorFn[] | FormControlOptions | null,
asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null,
): FormControl<T | null>;
/**
* The presence of an explicit `prototype` property provides backwards-compatibility for apps that
* manually inspect the prototype chain.
*/
prototype: FormControl<any>;
}
function isFormControlState(formState: unknown): formState is FormControlState<unknown> {
return (
typeof formState === 'object' &&
formState !== null &&
Object.keys(formState).length === 2 &&
'value' in formState &&
'disabled' in formState
);
}
export const FormControl: Ι΅FormControlCtor = class FormControl<TValue = any>
extends AbstractControl<TValue>
implements FormControlInterface<TValue>
{
/** @publicApi */
public readonly defaultValue: TValue = null as unknown as TValue;
/** @internal */
_onChange: Array<Function> = [];
/** @internal */
_pendingValue!: TValue;
/** @internal */
_pendingChange: boolean = false;
constructor(
// formState and defaultValue will only be null if T is nullable
formState: FormControlState<TValue> | TValue = null as unknown as TValue,
validatorOrOpts?: ValidatorFn | ValidatorFn[] | FormControlOptions | null,
asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null,
) {
super(pickValidators(validatorOrOpts), pickAsyncValidators(asyncValidator, validatorOrOpts));
this._applyFormState(formState);
this._setUpdateStrategy(validatorOrOpts);
this._initObservables();
this.updateValueAndValidity({
onlySelf: true,
// If `asyncValidator` is present, it will trigger control status change from `PENDING` to
// `VALID` or `INVALID`.
// The status should be broadcasted via the `statusChanges` observable, so we set
// `emitEvent` to `true` to allow that during the control creation process.
emitEvent: !!this.asyncValidator,
});
if (
isOptionsObj(validatorOrOpts) &&
(validatorOrOpts.nonNullable || validatorOrOpts.initialValueIsDefault)
) {
if (isFormControlState(formState)) {
this.defaultValue = formState.value;
} else {
this.defaultValue = formState;
}
}
}
override setValue(
value: TValue,
options: {
onlySelf?: boolean;
emitEvent?: boolean;
emitModelToViewChange?: boolean;
emitViewToModelChange?: boolean;
} = {},
): void {
(this as Writable<this>).value = this._pendingValue = value;
if (this._onChange.length && options.emitModelToViewChange !== false) {
this._onChange.forEach((changeFn) =>
changeFn(this.value, options.emitViewToModelChange !== false),
);
}
this.updateValueAndValidity(options);
}
override patchValue(
value: TValue,
options: {
onlySelf?: boolean;
emitEvent?: boolean;
emitModelToViewChange?: boolean;
emitViewToModelChange?: boolean;
} = {},
): void {
this.setValue(value, options);
}
override reset(
formState: TValue | FormControlState<TValue> = this.defaultValue,
options: {onlySelf?: boolean; emitEvent?: boolean} = {},
): void {
this._applyFormState(formState);
this.markAsPristine(options);
this.markAsUntouched(options);
this.setValue(this.value, options);
this._pendingChange = false;
}
/** @internal */
override _updateValue(): void {}
/** @internal */
override _anyControls(condition: (c: AbstractControl) => boolean): boolean {
return false;
}
/** @internal */
override _allControlsDisabled(): boolean {
return this.disabled;
}
registerOnChange(fn: Function): void {
this._onChange.push(fn);
}
/** @internal */
_unregisterOnChange(fn: (value?: any, emitModelEvent?: boolean) => void): void {
removeListItem(this._onChange, fn);
}
registerOnDisabledChange(fn: (isDisabled: boolean) => void): void {
this._onDisabledChange.push(fn);
}
/** @internal */
_unregisterOnDisabledChange(fn: (isDisabled: boolean) => void): void {
removeListItem(this._onDisabledChange, fn);
}
/** @internal */
override _forEachChild(cb: (c: AbstractControl) => void): void {}
/** @internal */
override _syncPendingControls(): boolean {
if (this.updateOn === 'submit') {
if (this._pendingDirty) this.markAsDirty();
if (this._pendingTouched) this.markAsTouched();
if (this._pendingChange) {
this.setValue(this._pendingValue, {onlySelf: true, emitModelToViewChange: false});
return true;
}
}
return false;
}
private _applyFormState(formState: FormControlState<TValue> | TValue) {
if (isFormControlState(formState)) {
(this as Writable<this>).value = this._pendingValue = formState.value;
formState.disabled
? this.disable({onlySelf: true, emitEvent: false})
: this.enable({onlySelf: true, emitEvent: false});
} else {
(this as Writable<this>).value = this._pendingValue = formState;
}
}
};
interface UntypedFormControlCtor {
new (): UntypedFormControl;
new (
formState?: any,
validatorOrOpts?: ValidatorFn | ValidatorFn[] | FormControlOptions | null,
asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null,
): UntypedFormControl;
/**
* The presence of an explicit `prototype` property provides backwards-compatibility for apps that
* manually inspect the prototype chain.
*/
prototype: FormControl<any>;
}
/**
* UntypedFormControl is a non-strongly-typed version of `FormControl`.
*/
export type UntypedFormControl = FormControl<any>;
export const UntypedFormControl: UntypedFormControlCtor = FormControl;
/**
* @description
* Asserts that the given control is an instance of `FormControl`
*
* @publicApi
*/
export const isFormControl = (control: unknown): control is FormControl =>
control instanceof FormControl;