diff --git a/packages/forms/signals/test/web/reactive_fvc.spec.ts b/packages/forms/signals/test/web/reactive_fvc.spec.ts index f4a334a18f2..454dac1cdf5 100644 --- a/packages/forms/signals/test/web/reactive_fvc.spec.ts +++ b/packages/forms/signals/test/web/reactive_fvc.spec.ts @@ -6,7 +6,18 @@ * found in the LICENSE file at https://angular.dev/license */ -import {Component, computed, Directive, inject, input, model, Self, signal} from '@angular/core'; +import { + Component, + computed, + Directive, + inject, + Injector, + input, + model, + output, + Self, + signal, +} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; import { @@ -18,13 +29,17 @@ import { ɵFORM_CONTROL_INTEGRATION, ControlValueAccessor, } from '@angular/forms'; +import {FormValueControl} from '@angular/forms/signals'; +import {SignalFormControl} from '../../compat'; @Component({ selector: 'my-fvc-input', - template: '', + template: + '', }) -class MyFvcInput { +class MyFvcInput implements FormValueControl { readonly value = model(''); + readonly touch = output(); readonly disabled = input(false); readonly touched = input(false); readonly dirty = input(false); @@ -836,6 +851,277 @@ describe('FormControlName with FVC', () => { expect(fvc.required()).toBe(true); }); }); + + describe('updateOn options', () => { + it('should not update value or validity based on custom control input until blur', () => { + @Component({ + template: ``, + imports: [MyFvcInput, ReactiveFormsModule], + }) + class TestCmp { + ctrl = new FormControl('', {validators: Validators.required, updateOn: 'blur'}); + } + + const fixture = act(() => TestBed.createComponent(TestCmp)); + const fvc = fixture.debugElement.query(By.directive(MyFvcInput)).componentInstance; + + act(() => fvc.value.set('Nancy')); + + expect(fixture.componentInstance.ctrl.value).toBe(''); + expect(fixture.componentInstance.ctrl.valid).toBe(false); + + act(() => fvc.touch.emit()); + + expect(fixture.componentInstance.ctrl.value).toBe('Nancy'); + expect(fixture.componentInstance.ctrl.valid).toBe(true); + }); + + it('should not update custom control value or validity until submit', () => { + @Component({ + template: ` +
+ + + `, + imports: [MyFvcInput, ReactiveFormsModule], + }) + class TestCmp { + form = new FormGroup({ + login: new FormControl('', {validators: Validators.required, updateOn: 'submit'}), + }); + } + + const fixture = act(() => TestBed.createComponent(TestCmp)); + const fvc = fixture.debugElement.query(By.directive(MyFvcInput)).componentInstance; + + act(() => fvc.value.set('Nancy')); + + expect(fixture.componentInstance.form.value).toEqual({login: ''}); + expect(fixture.componentInstance.form.valid).toBe(false); + + const form = fixture.nativeElement.querySelector('form'); + act(() => { + form?.dispatchEvent(new Event('submit', {cancelable: true})); + }); + + expect(fixture.componentInstance.form.value).toEqual({login: 'Nancy'}); + expect(fixture.componentInstance.form.valid).toBe(true); + }); + + it('should reset custom control view value when control is reset with pending changes', () => { + @Component({ + template: ``, + imports: [MyFvcInput, ReactiveFormsModule], + }) + class TestCmp { + ctrl = new FormControl('initial', {updateOn: 'blur'}); + } + + const fixture = act(() => TestBed.createComponent(TestCmp)); + const fvc = fixture.debugElement.query(By.directive(MyFvcInput)).componentInstance; + + expect(fvc.value()).toBe('initial'); + + act(() => fvc.value.set('modified')); + expect(fixture.componentInstance.ctrl.value).toBe('initial'); + + act(() => fixture.componentInstance.ctrl.reset('reset-value')); + expect(fixture.componentInstance.ctrl.value).toBe('reset-value'); + expect(fvc.value()).toBe('reset-value'); + }); + + it('should reset custom control view value when a pending undefined value is discarded', () => { + @Component({selector: 'my-optional-fvc-input', template: ''}) + class MyOptionalFvcInput implements FormValueControl { + readonly value = model(); + readonly touch = output(); + } + + @Component({ + template: ``, + imports: [MyOptionalFvcInput, ReactiveFormsModule], + }) + class TestCmp { + ctrl = new FormControl('initial', {updateOn: 'blur'}); + } + + const fixture = act(() => TestBed.createComponent(TestCmp)); + const fvc = fixture.debugElement.query(By.directive(MyOptionalFvcInput)).componentInstance; + + act(() => fvc.value.set(undefined)); + expect(fixture.componentInstance.ctrl.value).toBe('initial'); + + act(() => fixture.componentInstance.ctrl.reset('initial')); + expect(fvc.value()).toBe('initial'); + }); + + it('should reset custom control view value when control.setValue is called with current value to discard pending changes', () => { + @Component({ + template: ``, + imports: [MyFvcInput, ReactiveFormsModule], + }) + class TestCmp { + ctrl = new FormControl('initial', {updateOn: 'blur'}); + } + + const fixture = act(() => TestBed.createComponent(TestCmp)); + const fvc = fixture.debugElement.query(By.directive(MyFvcInput)).componentInstance; + + expect(fvc.value()).toBe('initial'); + + act(() => fvc.value.set('modified')); + expect(fixture.componentInstance.ctrl.value).toBe('initial'); + expect(fvc.value()).toBe('modified'); + + act(() => fixture.componentInstance.ctrl.setValue('initial')); + expect(fvc.value()).toBe('initial'); + }); + + it('should not mark control dirty or commit on blur after programmatic setValue', () => { + @Component({ + template: ``, + imports: [MyFvcInput, ReactiveFormsModule], + }) + class TestCmp { + ctrl = new FormControl('initial', {updateOn: 'blur'}); + } + + const fixture = act(() => TestBed.createComponent(TestCmp)); + const fvc = fixture.debugElement.query(By.directive(MyFvcInput)).componentInstance; + + act(() => fvc.value.set('modified')); + + const emitted: Array = []; + fixture.componentInstance.ctrl.valueChanges.subscribe((v) => emitted.push(v)); + + act(() => { + fixture.componentInstance.ctrl.setValue('new-value'); + fixture.componentInstance.ctrl.markAsPristine(); + }); + expect(fixture.componentInstance.ctrl.dirty).toBe(false); + expect(emitted).toEqual(['new-value']); + + act(() => fvc.touch.emit()); + + expect(fixture.componentInstance.ctrl.dirty).toBe(false); + expect(emitted).toEqual(['new-value']); + }); + + it('should sync custom control bound via formControlName to a SignalFormControl', () => { + @Component({ + template: ` +
+ + + `, + imports: [MyFvcInput, ReactiveFormsModule], + }) + class TestCmp { + readonly name = new SignalFormControl('Alice', undefined, {injector: inject(Injector)}); + readonly form = new FormGroup({name: this.name}); + } + + const fixture = act(() => TestBed.createComponent(TestCmp)); + const fvc = fixture.debugElement.query(By.directive(MyFvcInput)).componentInstance; + + expect(fvc.value()).toBe('Alice'); + + act(() => fvc.value.set('Bob')); + expect(fixture.componentInstance.name.value).toBe('Bob'); + expect(fixture.componentInstance.name.dirty).toBe(true); + + act(() => fvc.touch.emit()); + expect(fixture.componentInstance.name.touched).toBe(true); + }); + + it('should sync SignalFormControl in a FormGroup with updateOn change', () => { + @Component({ + template: ` +
+ + + `, + imports: [MyFvcInput, ReactiveFormsModule], + }) + class TestCmp { + readonly name = new SignalFormControl('Alice', undefined, {injector: inject(Injector)}); + readonly form = new FormGroup({name: this.name}, {updateOn: 'change'}); + } + + const fixture = act(() => TestBed.createComponent(TestCmp)); + const fvc = fixture.debugElement.query(By.directive(MyFvcInput)).componentInstance; + + act(() => fvc.value.set('Bob')); + expect(fixture.componentInstance.form.value).toEqual({name: 'Bob'}); + act(() => fixture.componentInstance.name.setValue('Carol')); + expect(fvc.value()).toBe('Carol'); + act(() => fvc.value.set('Dave')); + expect(fixture.componentInstance.form.value).toEqual({name: 'Dave'}); + }); + + it('should not mark control dirty or emit again on blur after setValue without updating the view', () => { + @Component({ + template: ``, + imports: [MyFvcInput, ReactiveFormsModule], + }) + class TestCmp { + readonly ctrl = new FormControl('initial', {updateOn: 'blur'}); + } + + const fixture = act(() => TestBed.createComponent(TestCmp)); + const fvc = fixture.debugElement.query(By.directive(MyFvcInput)).componentInstance; + const ctrl = fixture.componentInstance.ctrl; + + act(() => fvc.value.set('modified')); + const emitted: Array = []; + ctrl.valueChanges.subscribe((v) => emitted.push(v)); + + act(() => ctrl.setValue('new-value', {emitModelToViewChange: false})); + expect(fvc.value()).toBe('new-value'); + + act(() => fvc.touch.emit()); + + expect(ctrl.value).toBe('new-value'); + expect(ctrl.dirty).toBe(false); + expect(emitted).toEqual(['new-value']); + }); + + it('should discard pending changes when custom control is destroyed before commit', () => { + @Component({ + template: ` +
+ @if (show()) { + + } + + `, + imports: [MyFvcInput, ReactiveFormsModule], + }) + class TestCmp { + readonly show = signal(true); + readonly name = new FormControl('initial', {updateOn: 'submit'}); + readonly form = new FormGroup({name: this.name}); + } + + const fixture = act(() => TestBed.createComponent(TestCmp)); + const fvc = fixture.debugElement.query(By.directive(MyFvcInput)).componentInstance; + + act(() => fvc.value.set('modified')); + expect(fixture.componentInstance.name.value).toBe('initial'); + + // Destroy the custom control while `_pendingChange` is true. + act(() => fixture.componentInstance.show.set(false)); + + // Submitting the form should not commit the discarded pending value or mark it dirty. + const formEl = fixture.nativeElement.querySelector('form'); + act(() => { + formEl?.dispatchEvent(new Event('submit', {cancelable: true})); + }); + + expect(fixture.componentInstance.name.value).toBe('initial'); + expect(fixture.componentInstance.name.dirty).toBe(false); + }); + }); }); function act(fn: () => T): T { diff --git a/packages/forms/signals/test/web/template_fvc.spec.ts b/packages/forms/signals/test/web/template_fvc.spec.ts index f51a6c1119e..9aa7024716f 100644 --- a/packages/forms/signals/test/web/template_fvc.spec.ts +++ b/packages/forms/signals/test/web/template_fvc.spec.ts @@ -14,6 +14,7 @@ import { inject, input, model, + output, signal, ViewChild, } from '@angular/core'; @@ -37,6 +38,15 @@ class TemplateFvcInput { readonly errors = input([]); } +@Component({ + selector: 'my-touch-fvc', + template: '', +}) +class TouchFvcInput { + readonly value = model(''); + readonly touch = output(); +} + 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: ``, + 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: ``, + 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: ``, + 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: ``, + 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: ``, + 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({ diff --git a/packages/forms/src/directives/ng_control.ts b/packages/forms/src/directives/ng_control.ts index de11f9471b0..440a2b889fa 100644 --- a/packages/forms/src/directives/ng_control.ts +++ b/packages/forms/src/directives/ng_control.ts @@ -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); }