[英]Angular form - How to disable ngSubmit event when the form is invaild?
<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>
Now when input box is empty, though the submit button will be disabled, press enter will call both enterSubmit() and mySubmit() method. 现在,当输入框为空时,尽管将禁用提交按钮,但按Enter键将同时调用enterSubmit()和mySubmit()方法。 Even click RollDice button which has no "submit" type, will also call mySubmit().
即使单击没有“提交”类型的RollDice按钮,也会调用mySubmit()。 How can I call mySubmit() only when I click the Submit button?
仅当我单击“提交”按钮时才能调用mySubmit()吗?
Any button's or enter press' default behavior inside of a form will be to submit the form. 表单内的任何按钮或Enter键的默认行为都是提交表单。 To prevent this you could do the following:
为防止这种情况,您可以执行以下操作:
<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>
and in your typescript: 并在您的打字稿中:
rollDice(event: Event) {
event.preventDefault();
//rest of your code
}
enterSubmit(event: Event) {
event.preventDefault();
//rest of your code
}
This is allow you to only submit the form by clicking your submit button. 这允许您仅通过单击提交按钮来提交表单。
EDIT: I've added how you can check for form validity as well before submitting the form. 编辑:我已经添加了如何在提交表单之前检查表单有效性。 Solution is from here: source
解决方案是从这里: 源
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.