Home > Software engineering >  Strange behaviour when using reactive forms
Strange behaviour when using reactive forms

Time:09-16

I am currently working on a big form using reactive forms on Angular. It is not that complex, but it has a lot of fields. In some fields, I want to open a modal when I click a button and, inside that modal, call the backend and retrieve some data, select the data I want, and assign that to the input text. My problem is not with that, my problem comes when I click the button to search that data and fires the submit event of the form. I provide some code for better understanding.

form.component.html

<form
  [formGroup]="myForm"
  (ngSubmit)="seeFormData(myForm.value)"
>
  <div >
    <div >
      <picklist-component></picklist-component>
    </div>

    <div >
      
      ... some inputs ...      
      
      <div >
        <span>Field 1: </span>
        <div >
          <input type="text" pInputText disabled placeholder="Random placeholder" />
          <button
            pButton
            
            icon="pi pi-search"
            (click)="openModal()"
          ></button>
        </div>
      </div>
    </div>

    <div >

     ... some other inputs ...

      <div >
        <span>Field 2: </span>
        <div >
          <input type="text" pInputText disabled placeholder="Random placeholder" />
          <button
            pButton
            
            icon="pi pi-search"
            (click)="openModal()"
          ></button>
        </div>
      </div>
      
      <button
        pButton
        label="See data"
        
        icon="pi pi-external-link"
        type="submit"
      ></button>
    </div>
  </div>
</form>

form.component.ts

Some methods in order to open/close the modal:

  openModal() {
    this.display = true;
  }

  closeModal() {
    this.display = false;
  }

Method to show on console the data from the form:

  seeFormData(form: any) {
    console.log(form);
  }

I do not provide the rest of the code because the form is working fine, it shows what it must show, so I consider it is not required here.

As you can see, none of the buttons for opening the modal has any submit event or anything related to the form, they just should open the modal, but since I am very new with Angular, and even newer with reactive forms, I do not really know if I am doing it the right way.

CodePudding user response:

Default type for button is "submit" try changing the type to "button" should fix your issue something like

<button type="button" pButton  icon="pi pi-search (click)="openModal()" ></button>
  • Related