angular2 submit form by pressing enter without submit button

前端 未结 14 1677
长情又很酷
长情又很酷 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:45

    Maybe you add keypress or keydown to the input fields and assign the event to function that will do the submit when enter is clicked.

    Your template would look like this

        <form (keydown)="keyDownFunction($event)">
          <input type="text" />
        </form
    

    And you function inside the your class would look like this

        keyDownFunction(event) {
          if (event.keyCode === 13) {
            alert('you just pressed the enter key');
            // rest of your code
          }
        }
    
    0 讨论(0)
  • 2020-12-13 05:48

    Just simply add (keyup.enter)="yourFunction()"

    0 讨论(0)
  • 2020-12-13 05:50

    Always use keydown.enter instead of keyup.enter to avoid lagging.

    <textarea [(ngModel)]="textValue" (keydown.enter)="sendMessage();false" ></textarea>
    

    and function inside component.ts

     textValue : string = '';  
     sendMessage() {
        console.log(this.textValue);
        this.textValue = '';
      }
    
    0 讨论(0)
  • 2020-12-13 05:52

    add this inside your input tag

    <input type="text" (keyup.enter)="yourMethod()" />
    
    0 讨论(0)
  • 2020-12-13 05:52

    adding an invisible submit button does the trick

    <input type="submit" style="display: none;">

    0 讨论(0)
  • 2020-12-13 05:53

    Most answers here suggest using something like:

    <form [formGroup]="form" (ngSubmit)="yourMethod()" (keyup.enter)="yourMethod()">
    
    </form>
    

    This approach does not result in the form object being marked as submitted. You might not care for this, but if you're using something like @ngspot/ngx-errors (shameless self-promotion) for displaying validation errors, you gonna want to fix that. Here's how:

    <form [formGroup]="form" (ngSubmit)="yourMethod()" (keyup.enter)="submitBtn.click()">
      <button #submitBtn>Submit</button>
    </form>
    
    0 讨论(0)
提交回复
热议问题