Angular Form onSubmit() is called by other button
Asked Answered
P

1

5

I am doing an Angular 12 Material App.

I have a simple Form like this

<form [formGroup]="form" class="normal-form" (ngSubmit)="onSubmit()">
  <mat-grid-list cols="2" rowHeight="300px">
    <mat-grid-tile>
      <div class="controles-container">
        <input type="hidden" formControlName="Id">
          <mat-label><strong>Active</strong></mat-label>
              <mat-slide-toggle formControlName="IsActive"
                  [checked]="checked">
              </mat-slide-toggle>
              <textarea matInput hidden></textarea>

        <mat-form-field>
          <input formControlName="Name" matInput  placeholder=" Notification Name" >
          <mat-error>This field is mandatory</mat-error>
        </mat-form-field>
        <mat-form-field>
          <mat-select formControlName="ProcessorName" placeholder="Processor Name">
            <ng-container *ngFor="let processors of dataSourceProcessors">
              <mat-option value="{{processors.Value}}">{{processors.Text}}</mat-option>
            </ng-container>
          </mat-select>
        </mat-form-field>
      </div>
    </mat-grid-tile>
    <mat-grid-tile>
      <div class="controles-container">
          <mat-label><strong>Channel</strong></mat-label>
          <li *ngFor="let chanel of dataSourceChannelLevel">
            <mat-checkbox id={{chanel.NotificationLogLevel.Id}} formControlName="Channel" (change)="onChangeEventFunc( $event)">
              {{chanel.NotificationLogLevel.Name}}
            </mat-checkbox>
          </li>
        <div class="button-row">
          <button mat-raised-button color="warn" (click)="onClose()">Close</button>
          <button mat-raised-button color="primary" type="submit" [disabled]="form.invalid">Create</button>
        </div>
      </div>
    </mat-grid-tile>
  </mat-grid-list>
</form>

In the component I have this

 form:FormGroup=new FormGroup({
    Id: new FormControl(null),
    Name: new FormControl('',Validators.required),
    IsActive: new FormControl(true),
    ProcessorName: new FormControl(0),
    Channel: new FormControl(''),
  });

I have two buttons, Create that call Form.Submit, and Close button... The problem I have is that when I call Close button, it calls onClose() function and also Submit() function.

What I am missing?

Thanks

Panorama answered 24/3, 2022 at 16:3 Comment(1)
The default type of button is submit, seems strange but its it. So, clicking to close will submit too. Try to set type="button"Data
R
10

If the button is a submit button If it's inside/associated with a form and doesn't have type="button". Add type="button" attribute to avoid triggering onsubmit function on form element.

  <button mat-raised-button color="warn" (click)="onClose()" type="button">Close</button>
 
Rummel answered 24/3, 2022 at 16:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.