是否可能通过按下回车键提交没有提交按钮的表单(例如:)
<form [ngFormModel]="xxx" (ngSubmit)="xxxx()">
<input [(ngModel)]="lxxR" ngControl="xxxxx"/>
</form
You can also add (keyup.enter)="xxxx()"
或许您可以给文本框添加keypress
或keydown
事件,并将事件分配给一个函数,当按下enter键时进行提交。
您的模板应该是这样的
<form (keydown)="keyDownFunction($event)">
<input type="text" />
</form
你的类内部的函数应该长这样
keyDownFunction(event) {
if (event.keyCode === 13) {
alert('you just pressed the enter key');
// rest of your code
}
}
编辑:
<form (submit)="submit()" >
<input />
<button type="submit" style="display:none">hidden submit</button>
</form>
(submit)
而不是(ngSubmit)
:<form [ngFormModel]="xxx" (submit)="xxxx()">
<input [(ngModel)]="lxxR" ngControl="xxxxx"/>
</form>
我更倾向于使用(keydown.enter)="mySubmit()"
,因为如果光标不在<textarea>
的结尾处,就不会添加换行符。
这种方法更加简单...
<form [formGroup]="form" (keyup.enter)="yourMethod(form.value)">
</form>
<input type="text" (keyup.enter)="yourMethod()" />
(keyup.enter)="methodname()"
这应该是有效的,并且已经在许多答案中提到了,但是应该出现在表单标签上而不是按钮上。
始终使用keydown.enter而不是keyup.enter以避免延迟。
<textarea [(ngModel)]="textValue" (keydown.enter)="sendMessage();false" ></textarea>
在组件.ts文件中的and函数
textValue : string = '';
sendMessage() {
console.log(this.textValue);
this.textValue = '';
}
大多数回答建议使用类似以下的东西:
<form [formGroup]="form" (ngSubmit)="yourMethod()" (keyup.enter)="yourMethod()">
</form>
这种方法不会将表单对象标记为已提交
。你可能并不在意这一点,但如果你正在使用像@ngspot/ngx-errors(无耻的自我推广)这样的东西来显示验证错误,那么你需要解决这个问题。以下是解决方法:
<form [formGroup]="form" (ngSubmit)="yourMethod()" (keyup.enter)="submitBtn.click()">
<button #submitBtn>Submit</button>
</form>
Just simply add (keyup.enter)="yourFunction()"