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条回答
Anthone
2楼-- · 2020-02-17 06:22

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 = '';
  }
查看更多
▲ chillily
3楼-- · 2020-02-17 06:23

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.

查看更多
老娘就宠你
4楼-- · 2020-02-17 06:24

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>
查看更多
兄弟一词,经得起流年.
5楼-- · 2020-02-17 06:30

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

查看更多
虎瘦雄心在
6楼-- · 2020-02-17 06:33

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

查看更多
放荡不羁爱自由
7楼-- · 2020-02-17 06:34
(keyup.enter)="methodname()"

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

查看更多
登录 后发表回答