Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 410
duke Avatar asked Jan 28 '26 23:01

duke


1 Answers

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>
like image 182
Amit Avatar answered Jan 31 '26 14:01

Amit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!