formGroupName cannot be set to null

Viewed 44

I'm trying to create a dynamic angular form with RxFormBuilder (Angular 13.x). I would like to set the formGroupName to null if my input doesn't belong to a nested field, otherwise set it.

I expected this attributes to be removed if set to null, but I ended up getting the error below:

Cannot read properties of null (reading '_rawValidators')

Here is a simple example to illustrate:

Component

class A {
  @prop()
  id!: number;
}

@Component({ ... })
  model: A;
  form: FormGroup;

  constructor(
    private _formBuilder: RxFormBuilder
  ) {
    this.model = new A();
    this.form = this._formBuilder.formGroup(A, this.model);
  }
}

HTML

<form [formGroup]="form" *ngIf="form">
  <ng-container [formGroupName]="null"> <-- here
    <mat-form-field>
      <input matInput name="id" formControlName="id" type="text" />
    </mat-form-field>
  </ng-container>
</form>

For me, this <ng-container [formGroupName]="null"> should become <ng-container> and not raising this error because it hasn't been set.

Is there something I'm missing, or it's a default behavior ?

1 Answers

If Ashot's comment didn't help, consider using *ngIf like this:

<form [formGroup]="form" *ngIf="form">
  <ng-container *ngIf="!belongsToNestedField">
    <mat-form-field>
      <input matInput name="id" formControlName="id" type="text" />
    </mat-form-field>
  </ng-container>
</form>

<form [formGroup]="form" *ngIf="form">
  <ng-container *ngIf="belongsToNestedField" [formGroupName]="whatever">
    <mat-form-field>
      <input matInput name="id" formControlName="id" type="text" />
    </mat-form-field>
  </ng-container>
</form>

Something else you could try, although I'm not sure if it would work, is setting the formGroupName to an empty string conditionally with a ternary operator:

<form [formGroup]="form" *ngIf="form">
  <ng-container [formGroupName]="belongsToNestedField ? 'whatever' : ''">
    <mat-form-field>
      <input matInput name="id" formControlName="id" type="text" />
    </mat-form-field>
  </ng-container>
</form>

You could also look at conditional validation in the component instead: link to docs

Related