<div>
<form (ngSubmit)="mySubmit()" #msgBoxForm="ngForm">
<button mat-raised-button color="accent" (click)="rollDice()">
RollDice
</button>
<input
type="text"
name="msgInputBox"
[(ngModel)]="TextMessage"
required
#box (keyup.enter)="enterSubmit()"
placeholder="Message" >
<button
type="submit"
class="btn btn-success"
[disabled]="!msgBoxForm.form.valid">
Submit
</button>
</form>
</div>
现在,当输入框为空时,尽管将禁用提交按钮,但按Enter键将同时调用enterSubmit()和mySubmit()方法。即使单击没有“提交”类型的RollDice按钮,也会调用mySubmit()。仅当我单击“提交”按钮时才能调用mySubmit()?
答案 0 :(得分:0)
在表单内的任何按钮或Enter键的默认行为将是提交表单。为防止这种情况,您可以执行以下操作:
<div>
<form (ngSubmit)="msgBoxForm.form.valid && mySubmit()" #msgBoxForm="ngForm">
<button mat-raised-button color="accent" (click)="rollDice($event)">
RollDice
</button>
<input
type="text"
name="msgInputBox"
[(ngModel)]="TextMessage"
required
#box (keyup.enter)="enterSubmit($event)"
placeholder="Message" >
<button
type="submit"
class="btn btn-success"
[disabled]="!msgBoxForm.form.valid">
Submit
</button>
</form>
</div>
并在您的打字稿中:
rollDice(event: Event) {
event.preventDefault();
//rest of your code
}
enterSubmit(event: Event) {
event.preventDefault();
//rest of your code
}
这允许您仅通过单击提交按钮来提交表单。
编辑:我已经添加了如何在提交表单之前检查表单有效性。解决方案来自这里:source