angular2 submit form by pressing enter without submit button

前端 未结 14 1678
长情又很酷
长情又很酷 2020-12-13 05:13

Is it possible to submit a form that does not have submit button (by pressing enter) example :

&
相关标签:
14条回答
  • 2020-12-13 05:56

    If you want to include both simpler than what I saw here, you can do it just by including your button inside form.

    Example with a function sending a message:

                    <form>
                        <mat-form-field> <!-- In my case I'm using material design -->
                            <input matInput #message maxlength="256" placeholder="Message">
                        </mat-form-field>
                        <button (click)="addMessage(message.value)">Send message
                        </button>
                    </form>
    

    You can choose between clicking on the button or pressing enter key.

    0 讨论(0)
  • 2020-12-13 06:02

    If you want to include both - accept on enter and accept on click then do -

     <div class="form-group">
        <input class="form-control"   type="text" 
        name="search" placeholder="Enter Search Text"
                  [(ngModel)]="filterdata"  
               (keyup.enter)="searchByText(filterdata)">
      <button type="submit"  
              (click)="searchByText(filterdata)" >
    
      </div>
    
    0 讨论(0)
  • 2020-12-13 06:03

    Hopefully this can help somebody: for some reason I couldn't track because of lack of time, if you have a form like:

    <form (ngSubmit)="doSubmit($event)">
      <button (click)="clearForm()">Clear</button>
      <button type="submit">Submit</button>
    </form>
    

    when you hit the Enter button, the clearForm function is called, even though the expected behaviour was to call the doSubmit function. Changing the Clear button to a <a> tag solved the issue for me. I would still like to know if that's expected or not. Seems confusing to me

    0 讨论(0)
  • 2020-12-13 06:04

    This way is much simple...

    <form [formGroup]="form" (keyup.enter)="yourMethod(form.value)">
    
    </form>
    
    0 讨论(0)
  • 2020-12-13 06:05
    (keyup.enter)="methodname()"
    

    this should work and already mentioned in many answers, however that should be present on form tag and not on button.

    0 讨论(0)
  • 2020-12-13 06:06

    I prefer (keydown.enter)="mySubmit()" because there won't be added a line break if the cursor was somewhere within a <textarea> but not at its end.

    0 讨论(0)
提交回复
热议问题