Angular multiple forms each with its submit button

885 Views Asked by At

I want to have two forms on a page, each with their own submit button and validation. However, when I try and submit the 1st form the validation for the 2nd form triggers (and vice versa). Is there a way I can restrict the validation to trigger just for a given form. Here is an extract from my template (other inputs/tags/attributes removed for brevity):

<form #profileForm="ngForm" (ngSubmit)="onSubmit(profileForm)">
  <input name="name" #name="ngModel" [(ngModel)]="user.name" required/>
  <div class="invalid-feedback" *ngIf="profileForm.submitted && name.invalid">
     <p *ngIf="name.errors.required">Name is required</p>
  </div>
  <button type="submit" class="btn">Save</button>
</form>

<form #settingsForm="ngForm" (ngSubmit)="onSubmit(settingsForm)">
  <input name="accountType" #accountType="ngModel" [(ngModel)]="user.accountType" required/>
  <div class="invalid-feedback" *ngIf="settingsForm.submitted && accountType.invalid">
     <p *ngIf="accountType.errors.required">Account Type is required</p>
  </div>
  <button type="submit" class="btn">Update Settings</button>
</form>

I've had a look into ngModelGroup but couldn't see how this would help TBH as I want to specify on the button which form/validation should be triggered.

Any help would be appreciated.

0

There are 0 best solutions below