mirror of
https://github.com/angular/angular.git
synced 2026-11-22 22:55:25 -05:00
fix(forms): support updateOn blur and submit for custom FormValueControl
Custom controls implementing `FormValueControl` bound via `[formControl]` or `formControlName` currently bypass `setUpControlValueAccessor`. In `NgControl.ngControlCreate`, incoming values from the custom control model were applied directly to the `FormControl` without checking `control.updateOn`. This update respects `control.updateOn` by buffering pending values and dirty state when `updateOn` is set to `'blur'` or `'submit'`. Value and validity are committed on `touch` output emissions for `'blur'`, and on form submission for `'submit'`. Programmatic resets also synchronize the reset value to the custom control when pending changes are cleared. Programmatic `setValue` and `reset` calls now also update `[(ngModel)]` for custom controls, as they do for CVAs.
This commit is contained in:
committed by
Alex Rickabaugh
parent
f3c77f1e2b
commit
401b4f2011
File diff suppressed because it is too large
Load Diff
@@ -14,6 +14,7 @@ import {
|
||||
inject,
|
||||
input,
|
||||
model,
|
||||
output,
|
||||
signal,
|
||||
ViewChild,
|
||||
} from '@angular/core';
|
||||
@@ -37,6 +38,15 @@ class TemplateFvcInput {
|
||||
readonly errors = input<readonly any[]>([]);
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: 'my-touch-fvc',
|
||||
template: '<input #i [value]="value()" (input)="value.set(i.value)" (blur)="touch.emit()" />',
|
||||
})
|
||||
class TouchFvcInput {
|
||||
readonly value = model('');
|
||||
readonly touch = output<void>();
|
||||
}
|
||||
|
||||
describe('NgModel with FVC', () => {
|
||||
it('should sync ngModel value to FVC (model -> view)', async () => {
|
||||
@Component({
|
||||
@@ -382,6 +392,123 @@ describe('NgModel with FVC', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('NgModel updateOn with FVC', () => {
|
||||
it('should commit value to ngModel on blur', async () => {
|
||||
@Component({
|
||||
template: `<my-touch-fvc
|
||||
[(ngModel)]="val"
|
||||
[ngModelOptions]="{updateOn: 'blur'}"
|
||||
#model="ngModel"
|
||||
/>`,
|
||||
imports: [TouchFvcInput, FormsModule],
|
||||
})
|
||||
class TestCmp {
|
||||
val = signal('initial');
|
||||
@ViewChild('model') model!: NgModel;
|
||||
}
|
||||
|
||||
const fixture = await actAsync(() => TestBed.createComponent(TestCmp));
|
||||
const fvc = fixture.debugElement.query(By.directive(TouchFvcInput)).componentInstance;
|
||||
|
||||
act(() => fvc.value.set('typed'));
|
||||
expect(fixture.componentInstance.val()).toBe('initial');
|
||||
expect(fixture.componentInstance.model.control.value).toBe('initial');
|
||||
expect(fixture.componentInstance.model.control.dirty).toBe(false);
|
||||
|
||||
act(() => fvc.touch.emit());
|
||||
expect(fixture.componentInstance.val()).toBe('typed');
|
||||
expect(fixture.componentInstance.model.control.value).toBe('typed');
|
||||
expect(fixture.componentInstance.model.control.dirty).toBe(true);
|
||||
expect(fixture.componentInstance.model.control.touched).toBe(true);
|
||||
expect(fvc.value()).toBe('typed');
|
||||
});
|
||||
|
||||
it('should update ngModel when the control value is set programmatically', async () => {
|
||||
@Component({
|
||||
template: `<my-touch-fvc [(ngModel)]="val" #model="ngModel" />`,
|
||||
imports: [TouchFvcInput, FormsModule],
|
||||
})
|
||||
class TestCmp {
|
||||
val = signal('initial');
|
||||
@ViewChild('model') model!: NgModel;
|
||||
}
|
||||
|
||||
const fixture = await actAsync(() => TestBed.createComponent(TestCmp));
|
||||
|
||||
await actAsync(() => fixture.componentInstance.model.control.setValue('new'));
|
||||
|
||||
expect(fixture.componentInstance.val()).toBe('new');
|
||||
});
|
||||
|
||||
it('should update ngModel when the control is reset', async () => {
|
||||
@Component({
|
||||
template: `<my-touch-fvc [(ngModel)]="val" #model="ngModel" />`,
|
||||
imports: [TouchFvcInput, FormsModule],
|
||||
})
|
||||
class TestCmp {
|
||||
val = signal('initial');
|
||||
@ViewChild('model') model!: NgModel;
|
||||
}
|
||||
|
||||
const fixture = await actAsync(() => TestBed.createComponent(TestCmp));
|
||||
|
||||
await actAsync(() => fixture.componentInstance.model.reset('reset'));
|
||||
|
||||
expect(fixture.componentInstance.val()).toBe('reset');
|
||||
});
|
||||
|
||||
it('should update ngModel with a value changed by a valueChanges subscriber', async () => {
|
||||
@Component({
|
||||
template: `<my-touch-fvc [(ngModel)]="val" #model="ngModel" />`,
|
||||
imports: [TouchFvcInput, FormsModule],
|
||||
})
|
||||
class TestCmp {
|
||||
val = signal('initial');
|
||||
@ViewChild('model') model!: NgModel;
|
||||
}
|
||||
|
||||
const fixture = await actAsync(() => TestBed.createComponent(TestCmp));
|
||||
const fvc = fixture.debugElement.query(By.directive(TouchFvcInput)).componentInstance;
|
||||
const control = fixture.componentInstance.model.control;
|
||||
control.valueChanges.subscribe((value) => {
|
||||
if (value === 'typed') {
|
||||
control.setValue('TYPED');
|
||||
}
|
||||
});
|
||||
|
||||
await actAsync(() => fvc.value.set('typed'));
|
||||
|
||||
expect(fixture.componentInstance.val()).toBe('TYPED');
|
||||
expect(fvc.value()).toBe('TYPED');
|
||||
});
|
||||
|
||||
it('should discard pending value when model changes before blur', async () => {
|
||||
@Component({
|
||||
template: `<my-touch-fvc
|
||||
[(ngModel)]="val"
|
||||
[ngModelOptions]="{updateOn: 'blur'}"
|
||||
#model="ngModel"
|
||||
/>`,
|
||||
imports: [TouchFvcInput, FormsModule],
|
||||
})
|
||||
class TestCmp {
|
||||
val = signal('initial');
|
||||
@ViewChild('model') model!: NgModel;
|
||||
}
|
||||
|
||||
const fixture = await actAsync(() => TestBed.createComponent(TestCmp));
|
||||
const fvc = fixture.debugElement.query(By.directive(TouchFvcInput)).componentInstance;
|
||||
|
||||
act(() => fvc.value.set('typed'));
|
||||
await actAsync(() => fixture.componentInstance.val.set('external'));
|
||||
expect(fvc.value()).toBe('external');
|
||||
|
||||
act(() => fvc.touch.emit());
|
||||
expect(fixture.componentInstance.val()).toBe('external');
|
||||
expect(fixture.componentInstance.model.control.dirty).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('NgModel parseErrors binding', () => {
|
||||
it('should sync FVC parseErrors to NgModel control', async () => {
|
||||
@Component({
|
||||
|
||||
@@ -157,6 +157,13 @@ export abstract class NgControl extends AbstractControlDirective {
|
||||
errors?: ValidationErrors | null;
|
||||
} | null = null;
|
||||
|
||||
/**
|
||||
* Last value emitted by the custom control that has not been committed to the `FormControl`
|
||||
* yet (`updateOn: 'blur' | 'submit'`). Only meaningful while `hasPendingCustomValue` is true.
|
||||
*/
|
||||
private pendingCustomValue: unknown = undefined;
|
||||
private hasPendingCustomValue = false;
|
||||
|
||||
constructor(
|
||||
injector?: Injector,
|
||||
renderer?: Renderer2,
|
||||
@@ -175,21 +182,38 @@ export abstract class NgControl extends AbstractControlDirective {
|
||||
protected setupCustomControl(): void {
|
||||
this.subscription?.unsubscribe();
|
||||
|
||||
const control = this.control;
|
||||
const cdr = this.injector?.get(ChangeDetectorRef);
|
||||
if (!this.control || !cdr) {
|
||||
if (!control || !cdr) {
|
||||
return;
|
||||
}
|
||||
|
||||
const markForCheck = cdr.markForCheck.bind(cdr);
|
||||
this.subscription = new Subscription();
|
||||
|
||||
this.subscription.add(this.control.valueChanges.subscribe(markForCheck));
|
||||
this.subscription.add(this.control.statusChanges.subscribe(markForCheck));
|
||||
this.subscription.add(() => this.discardPendingCustomValue(control));
|
||||
|
||||
// `registerOnChange` and `_unregisterOnChange` are declared on `FormControl` (and
|
||||
// `SignalFormControl`), not on `AbstractControl`. We guard `registerOnChange` at runtime.
|
||||
if (typeof (control as FormControl).registerOnChange === 'function') {
|
||||
const onControlChange = (newValue?: unknown, emitModelEvent?: boolean) => {
|
||||
this.discardPendingCustomValue(control);
|
||||
if (emitModelEvent) {
|
||||
this.viewToModelUpdate(newValue);
|
||||
}
|
||||
markForCheck();
|
||||
};
|
||||
(control as FormControl).registerOnChange(onControlChange);
|
||||
this.subscription.add(() => (control as FormControl)._unregisterOnChange(onControlChange));
|
||||
}
|
||||
|
||||
this.subscription.add(control.valueChanges.subscribe(markForCheck));
|
||||
this.subscription.add(control.statusChanges.subscribe(markForCheck));
|
||||
|
||||
this.resetSubscription?.unsubscribe();
|
||||
this.resetSubscription = undefined;
|
||||
if (this.userOnReset) {
|
||||
this.resetSubscription = this.control.events.subscribe((event) => {
|
||||
this.resetSubscription = control.events.subscribe((event) => {
|
||||
if (event instanceof FormResetEvent && this.control) {
|
||||
this.userOnReset?.(this.control.value);
|
||||
}
|
||||
@@ -199,7 +223,7 @@ export abstract class NgControl extends AbstractControlDirective {
|
||||
|
||||
// Add parseErrors validator if present
|
||||
if (this.parseErrorsValidator) {
|
||||
this.control.addValidators(this.parseErrorsValidator);
|
||||
control.addValidators(this.parseErrorsValidator);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -230,15 +254,42 @@ export abstract class NgControl extends AbstractControlDirective {
|
||||
// Note: We access this.control dynamically because it may not be set yet
|
||||
// (e.g., FormControlDirective's form input hasn't been bound)
|
||||
host.listenToCustomControlModel((value) => {
|
||||
// TODO: is there a case where this input has not yet been set?
|
||||
this.control?.markAsDirty();
|
||||
this.control?.setValue(value, {emitModelToViewChange: false});
|
||||
this.viewToModelUpdate(value);
|
||||
const control = this.control;
|
||||
if (!control) {
|
||||
return;
|
||||
}
|
||||
|
||||
// `_pendingValue` and `_pendingChange` are only declared on `FormControl`; cast rather than
|
||||
// checking `instanceof FormControl` so `SignalFormControl` and custom `AbstractControl`
|
||||
// subclasses are supported.
|
||||
(control as FormControl)._pendingValue = value;
|
||||
(control as FormControl)._pendingChange = true;
|
||||
control._pendingDirty = true;
|
||||
this.pendingCustomValue = value;
|
||||
this.hasPendingCustomValue = true;
|
||||
|
||||
if (control.updateOn === 'change') {
|
||||
this.updateControlFromCustom(control);
|
||||
}
|
||||
});
|
||||
|
||||
// Listen to touched changes from FVC
|
||||
host.listenToCustomControlOutput('touch', () => {
|
||||
this.control?.markAsTouched();
|
||||
const control = this.control;
|
||||
if (!control) {
|
||||
return;
|
||||
}
|
||||
|
||||
control._pendingTouched = true;
|
||||
|
||||
// `_pendingChange` is only declared on `FormControl` (same as in `listenToCustomControlModel`).
|
||||
if (control.updateOn === 'blur' && (control as FormControl)._pendingChange) {
|
||||
this.updateControlFromCustom(control);
|
||||
}
|
||||
|
||||
if (control.updateOn !== 'submit') {
|
||||
control.markAsTouched();
|
||||
}
|
||||
});
|
||||
|
||||
this.customControlBindings = {};
|
||||
@@ -247,16 +298,72 @@ export abstract class NgControl extends AbstractControlDirective {
|
||||
this.requiredValidatorViaDi = this._rawValidators.find((v) => v instanceof RequiredValidator);
|
||||
}
|
||||
|
||||
private updateControlFromCustom(control: AbstractControl): void {
|
||||
// `_pendingValue` and `_pendingChange` are only declared on `FormControl` (same as in
|
||||
// `listenToCustomControlModel`).
|
||||
const value = (control as FormControl)._pendingValue;
|
||||
// Clear the pending state before `setValue` so `valueChanges` and `events` subscribers don't
|
||||
// observe a committed value that is still marked as pending.
|
||||
(control as FormControl)._pendingChange = false;
|
||||
this.clearPendingCustomValue();
|
||||
// The custom control is the source of `value`, so it already holds it. Record that before
|
||||
// `setValue` so a `valueChanges` subscriber that synchronously sets a different value is
|
||||
// still propagated by `ngControlUpdate`.
|
||||
if (this.customControlBindings) {
|
||||
this.customControlBindings.value = value;
|
||||
}
|
||||
if (control._pendingDirty) {
|
||||
control.markAsDirty();
|
||||
}
|
||||
control.setValue(value, {emitModelToViewChange: false});
|
||||
// Read `control.value` rather than `value` in case a `valueChanges` subscriber changed it.
|
||||
this.viewToModelUpdate(control.value);
|
||||
}
|
||||
|
||||
private discardPendingCustomValue(control: AbstractControl): void {
|
||||
if (!this.hasPendingCustomValue) {
|
||||
return;
|
||||
}
|
||||
if (this.customControlBindings) {
|
||||
this.customControlBindings.value = this.pendingCustomValue;
|
||||
}
|
||||
this.clearPendingCustomValue();
|
||||
// `_pendingValue` and `_pendingChange` are only declared on `FormControl` (same as in
|
||||
// `listenToCustomControlModel`).
|
||||
(control as FormControl)._pendingValue = control.value;
|
||||
(control as FormControl)._pendingChange = false;
|
||||
control._pendingDirty = false;
|
||||
}
|
||||
|
||||
private clearPendingCustomValue(): void {
|
||||
this.pendingCustomValue = undefined;
|
||||
this.hasPendingCustomValue = false;
|
||||
}
|
||||
|
||||
protected ngControlUpdate(host: ControlDirectiveHost, bindRequired: boolean): void {
|
||||
if (!this.isCustomControlBased) {
|
||||
return;
|
||||
}
|
||||
|
||||
const control = this.control!;
|
||||
const bindings = this.customControlBindings!;
|
||||
const control = this.control;
|
||||
const bindings = this.customControlBindings;
|
||||
if (!control || !bindings) {
|
||||
return;
|
||||
}
|
||||
|
||||
// If a pending custom value was committed externally (e.g. by `syncPendingControls` on
|
||||
// form submission), update `bindings.value` to what the custom control already holds.
|
||||
// `_pendingChange` is only declared on `FormControl` (same as in `listenToCustomControlModel`).
|
||||
if (this.hasPendingCustomValue && !(control as FormControl)._pendingChange) {
|
||||
bindings.value = this.pendingCustomValue;
|
||||
this.clearPendingCustomValue();
|
||||
}
|
||||
|
||||
// Bind FormControl value -> FVC
|
||||
if (!Object.is(bindings.value, control.value)) {
|
||||
// Overwriting the custom control discards its pending value, so clear the control's
|
||||
// pending state too. Otherwise a later blur would commit the discarded value.
|
||||
this.discardPendingCustomValue(control);
|
||||
bindings.value = control.value;
|
||||
host.setCustomControlModelInput(control.value);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user