Angular 15 standalone + material + form causing valueAccessor errors?

1.4k Views Asked by At

Fiddling with the new Angular 15 standalone components. I just wanted to try a "simple" app with only one standalone component, but with Angular Material styling. All went well, but then I added a formfield to it. Then I had to add ngDefaultControl to the mat-form-field directly.

My question is: is "use ngDefaultControl" a safe approach? Is there a better one? Is there anyone who tested custom value accessors with standalone components?

I am afraid that Angular Material formfields are not really preapared for standalone usage. It bugs me because we would love to use this standalone approach in prod, like this:

    @Component({
    standalone: true,
    template: `
    <div>HELLO!</div>
    <form [formGroup]="form">
      <mat-form-field [formControl]="text">
        <input matInput />
      </mat-form-field>
    </form>
    `,
...

From this point on I had lots of errors. Finally Imported all the things I found needed:

    imports: [
    CommonModule,
    ReactiveFormsModule,
    FormsModule,
    MatFormFieldModule,
    MatInputModule,
    ],

Got an another error about animations. Got rid of it finally with replacing the BrowserModule in the main app.module.ts to BrowserAnimationsModule:

    import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

but still had error: Error: NG01203: No value accessor for form control unspecified name attribute.

After few hours of futile search I found some notes about "DefaultValueAccessor is not standalone".

Only one workaround I found, that I can add ngDefaultControl to the mat-form field.

Hmm... strange.

Could it be that all standalone components need to provide the default value accessor?

2

There are 2 best solutions below

0
On

I don't think this has anything to do with stand-alone components. You don't have the complete code listed here, but one thing that's not right in the code above is that the [formcontrol] attribute is set on the <mat-form-field> element, when in fact it should be set on the <input> element.

0
On

I had this error when migrating to the new MDC-based Angular Material Components. It was caused by:

<mat-slider [formControl]="myControl">

The solution was to move [formcontrol] to the new tag:

<input matSliderThumb [formControl]="myControl">