Skip to content

Using NgxControlValueAccessor with [field] causes ERROR RuntimeError: NG0950: Input "field" is required but no value is available yet #654

@ptandler

Description

@ptandler

I'm experimenting with the new signal forms and tried using a component implemented with NgxControlValueAccessor with the new [field] directive. Using the custom control component with [field] I get

ERROR RuntimeError: NG0950: Input "field" is required but no value is available yet

From what I see in the stack, it seems that NgxControlValueAccessor.initialValue() calls the InteropNgControl.value and this fails because there is no value yet set to the directive's field input.

Not sure if this should be fixed here or in the [field] directive.

Example available at
https://stackblitz.com/~/github.com/ptandler/angular-signal-form-value-control-reactive-form-interop?file=src/main.ts

export interface Test {
  stringValue: string;
  numberValue: number;
}

@Component({
  selector: 'custom-form-value-control',
  template: ` <div style="border: gray solid 2px">
    <input type="text" [field]="valueForm.stringValue" />
    <input type="number" [field]="valueForm.numberValue" />
  </div>`,
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Field],
  hostDirectives: [NgxControlValueAccessor],
})
export class CustomControlComponent {
  protected readonly cva = inject(NgxControlValueAccessor<Test>);
  protected readonly valueForm = form(this.cva.value$, {
    name: 'CustomControlComponent Form',
  });
  constructor() {
    console.log('CustomControlComponent.valueForm', this.valueForm());
  }
}

@Component({
  selector: 'app-root',
  template: `
    <h4>Field {{ value() | json }}</h4>
    <!-- When I comment the next line, everything works fine. -->
    <custom-form-value-control [field]="valueForm" /><br />
    <h4>FormControl {{ formControlValue() | json }}</h4>
    <custom-form-value-control [formControl]="formControl" /><br />
  `,
  imports: [ReactiveFormsModule, JsonPipe, CustomControlComponent, Field],
})
export class App {
  // for usage with [field]
  public readonly value = signal<Test>({ stringValue: 'hi!', numberValue: 42 });
  public readonly valueForm = form(this.value, { name: 'App Form' });

  // for usage with [formControl]
  public readonly formControl = new FormControl<Test>(
    {
      stringValue: 'ho?',
      numberValue: 17,
    },
    { nonNullable: true },
  );
  protected readonly formControlValue = toSignal(this.formControl.valueChanges);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions