3

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?

1
  • It works for me in this plunker Commented Apr 1, 2018 at 11:25

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.