Can't use ng-content with mat-form-field

604 Views Asked by At

I’m trying to do a dynamic form with Angular Material. ng-content doesn’t seems to work with mat-form-field.

I’m getting this error message: ERROR TypeError: Cannot read properties of undefined (reading 'errorState') at hostBindings (form-field.mjs:26:94)

Each form field is a module that contains its own component. Here is what my form looks like (with its 2 components app-form-field and app-input):

<form [formGroup]="form" novalidate autocomplete="off" (ngSubmit)="onSubmit()">
    <app-form-field>
      <app-input formControlName="input"></app-input>
    </app-form-field>
  </form>

app-form-field component contains:

<mat-form-field appearance="fill" class="form-field">
  <mat-label class="form-field__label">
    Fill form field
    <span class="form-field__req">*</span>
  </mat-label> 
  <ng-content></ng-content> 
</mat-form-field>

app-input component contains :

<input matInput
  placeholder="Placeholder"
  class="app-input"
  [value]="value"
  [placeholder]="placeholder || ''"
  [attr.disabled]="isDisabled ? true : null"
  (keyup)="onKeyup($event)"
  (blur)="onBlur()">

All my module imports look good and I want to point out that if I replace the ng-content directly with an input: it works. The issue seems to come from ng-content.

I hope someone can help me, I've been stuck on this problem for several days.

Edit - test without material: I have test my logic on angular without material and thats works. enter image description here

Thanks a lot.

1

There are 1 best solutions below

3
Alireza Ebrahimkhani On

I think your problem is you add fromControlName directive on an element that is not a form filed component and if you want to create your custom form field component you should use ControlValueAccessor interface for implementing the custom component.

Read angular official documentation about Control Value Accessor also some papers like this in medium and dev.to will help you