angular2 submit form by pressing enter without sub

2020-02-17 06:01发布

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

<form [ngFormModel]="xxx" (ngSubmit)="xxxx()">
  <input [(ngModel)]="lxxR"   ngControl="xxxxx"/>
</form

13条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-02-17 06:35

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 clicked enter');
    // rest of your code
  }
}
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2020-02-17 06:37

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.

查看更多
何必那么认真
4楼-- · 2020-02-17 06:39

adding an invisible submit button does the trick

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

查看更多
smile是对你的礼貌
5楼-- · 2020-02-17 06:43

Edit:

  <form (submit)="submit()" >
    <input />
    <button type="submit" style="display:none">hidden submit</button>
  </form>

In order to use this method, you need to have a submit button even if it's not displayed "Thanks for Toolkit's answer"

Old Answer:

Yes, exactly as you wrote it, except the event name is (submit) instead of (ngSubmit):

<form [ngFormModel]="xxx" (submit)="xxxx()">
  <input [(ngModel)]="lxxR"   ngControl="xxxxx"/>
</form>

查看更多
混吃等死
6楼-- · 2020-02-17 06:43

You can also add (keyup.enter)="xxxx()"

查看更多
该账号已被封号
7楼-- · 2020-02-17 06:45

This way is much simple...

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

</form>
查看更多
登录 后发表回答