Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions packages/forms/signals/src/directive/control_cva.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,12 +88,12 @@ export function cvaControlCreate(

return () => {
const fieldState = parent.state();
const value = fieldState.value();
const controlValue = fieldState.controlValue();

if (bindingUpdated(bindings, 'controlValue', value)) {
if (bindingUpdated(bindings, 'controlValue', controlValue)) {
// We don't know if the interop control has underlying signals, so we must use `untracked` to
// prevent writing to a signal in a reactive context.
untracked(() => parent.controlValueAccessor!.writeValue(value));
untracked(() => parent.controlValueAccessor!.writeValue(controlValue));
}

for (const name of CONTROL_BINDING_NAMES) {
Expand Down
63 changes: 63 additions & 0 deletions packages/forms/signals/test/web/interop.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -607,6 +607,69 @@ describe('ControlValueAccessor', () => {
expect(field().value()).toBe('initial');
});

it('should not write stale model values back to a CVA while debounce is pending', () => {
let writeValues: string[] = [];

@Component({
selector: 'custom-control-writeback-test',
template: `<input [value]="value" (input)="onInput($event.target.value)" />`,
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: CustomControlWritebackTest,
multi: true,
},
],
})
class CustomControlWritebackTest implements ControlValueAccessor {
value = '';

private onChangeFn?: (value: string) => void;

writeValue(newValue: string): void {
writeValues.push(newValue);
this.value = newValue;
}

registerOnChange(fn: (value: string) => void): void {
this.onChangeFn = fn;
}

registerOnTouched(fn: () => void): void {}

onInput(newValue: string) {
this.value = newValue;
this.onChangeFn?.(newValue);
}
}

@Component({
imports: [CustomControlWritebackTest, FormField],
template: `<custom-control-writeback-test [formField]="f" />`,
})
class TestCmp {
readonly f = form(signal('initial'), (p) => {
debounce(p, 'blur');
});
}

const fixture = act(() => TestBed.createComponent(TestCmp));

const debugEl = fixture.debugElement.query(
(el) => el.componentInstance instanceof CustomControlWritebackTest,
);

const cvaInstance = debugEl.componentInstance as CustomControlWritebackTest;

writeValues = [];

act(() => cvaInstance.onInput('updated'));

expect(cvaInstance.value).toBe('updated');

expect(writeValues).toEqual([]);
});

describe('properties', () => {
describe('disabled', () => {
it('should bind to directive input', () => {
Expand Down
Loading