Forms - Click issue with two buttons

I have created a simple form with two buttons. Cancel and Save Profile.
Whenever I click on Cancel, it also triggers the Save Profile button.

Anyone knows how to avoid this situation?
Here’s the code:

TS File:

export class HomePage {

    user: any; 

    public profileDetailsForm: FormGroup;
    showForm: boolean = false;

  constructor(
    public navCtrl: NavController,
    public formBuilder: FormBuilder
    ) {

      this.user = {
        firstName: "Mark",
        lastName: "Silver",
        tagline: "",
        description: "I am what I am"
      }

      this.profileDetailsForm = formBuilder.group({
          firstName: [ this.user.firstName || '', Validators.compose([Validators.minLength(2), Validators.required]) ],
          lastName: [ this.user.lastName || '', Validators.compose([Validators.minLength(2), Validators.required]) ],

          tagline: [ this.user.tagline || '' ],
          description: [ this.user.description || '' ],   
      });

      this.showForm = true;
      console.log("showForm ", this.showForm);
      console.log("profileDetailsForm ", this.profileDetailsForm);
  }

    greyButtonClick() {
        console.log("profileDetailsForm ", this.profileDetailsForm);
    }

    saveProfileDetails() {
        console.log("In saveProfileDetails");
    }
}

Html File:

<span *ngIf="showForm">
    <form class="formClass" padding [formGroup]="profileDetailsForm" (submit)="saveProfileDetails()" novalidate>

        <h3 color="titles">Basic information</h3>

        <ion-item>
            <ion-label stacked>First Name</ion-label>
            <ion-input formControlName="firstName" type="text"
                placeholder=""></ion-input>
        </ion-item>
        
        <ion-item>
            <ion-label stacked>Last Name</ion-label>
            <ion-input formControlName="lastName" type="text"
                placeholder=""></ion-input>
        </ion-item>

        <br/>

        <h3 color="titles">Help other people get to know you</h3>

        <ion-item>
            <ion-label stacked>Tag line</ion-label>
            <ion-input formControlName="tagline" type="text"></ion-input>
        </ion-item>
        
        <ion-item>
            <ion-label stacked>About Me</ion-label>
            <ion-textarea rows="7" formControlName="description" type="text"></ion-textarea> 
        </ion-item>

        <br/>
        <button ion-button block color="light" class="bottomButton" (click)="greyButtonClick()">
            <label text-capitalize>Cancel</label>
        </button>
        <button ion-button color="dark" block class="bottomButton addButton" type="submit">
            <label text-capitalize>Save Profile</label>
        </button>
    </form>
</span>
2 Likes

I believe buttons are of type submit by default, so if you don’t want the cancel button to submit the form, you need to declare it as type="button".

11 Likes

Thanks! It solved the issue.