angularformsangular-ng-if

How can I submit a form if a condition is met using Angular?


I would like to submit the following form if selected equals true.

<form *ngIf="selected" (ngSubmit)="onSubmit()" #f="ngForm">
  <!-- Child elements of the form... -->
      <button
        type="submit"
        class="btn btn-primary"
        [disabled]="!f.valid"
        (click)="onClick()"
      >Save
      </button>
  </form>

However, the following error is thrown.

Form submission cancelled because the form is not connected.

Without *ngIf="selected" the forms works as aspected. I presume it throws the error because (ngSubmit)="onSubmit()" #f="ngForm" is not initialised when the page is loaded.

How can I submit the form if selected equals true using *ngIf?


Solution

  • I recommend adding the structural directive *ngIf as an attribute of an ng-container element as follows.

    <form (ngSubmit)="onSubmit()" #f="ngForm">
        <ng-container *ngIf="selected">
            <!-- Form children... -->
        </ng-container>
    </form>