javascript - 即使我在处理程序中返回 false,Angular 仍会提交表单
问题描述
我有以下内容:
HTML 模板:
<form [action]='endpoint' method="post" target="my_iframe" #confirmForm (ngSubmit)="submitConfirmation()">
<button type="submit" (click)="confirmForm.submit()">Submit</button>
</form>
<iframe name="my_iframe"></iframe>
在组件中:
submitConfirmation() {
return false;
}
我也试过抛出一个错误:
submitConfirmation() {
throw Error('test');
return false;
}
无论我做什么,表单仍然提交!我在网上找到的每个资源都告诉我,如果我在提交处理程序中返回 false,则不会提交表单。这可能与iframe有关吗?(由于我不会进入的原因,它是必需的)。该方法肯定会运行,我已经检查并三重检查。
在相关说明中,我真的需要(click)="confirmForm.submit()
提交按钮吗?
编辑:我刚刚尝试删除(click)="confirmForm.submit()
,现在我更加困惑!当我删除该绑定时,按钮仍然有效,该方法submitConfirmation
仍然被调用,但现在无论我是否返回 false,表单都无法提交。
解决方案
Just need to preventDefault
on the triggering event. Your component class should look like:
submitConfirmation(event) {
event.preventDefault();
// other stuff
}
To use that will require passing in the $event
parameter from the component template:
<form ... (ngSubmit)="submitConfirmation($event)">
<button type="submit">Submit</button>
</form>
No need for (click)="confirmForm.submit()
. Buttons within a form will default to a type of submit
(explicitly set type="button"
otherwise) and this will trigger the (ngSubmit)
event.
推荐阅读
- java - 如何将外部 jar 添加到 Webots?
- c# - 如何将单个类型的正确实例注入另一个类
- javascript - 如何在函数内部传递一个作为访问属性的参数
- c# - 如何使用重定向在 asp.net core 2.0 的新选项卡中打开链接
- python-3.x - O(1) 设置位计数
- vue.js - Vue: filter an array of objects doesn't work properly
- eclipse - Prevent Eclipse from collapsing a path in project explorer that I manually opened?
- javascript - How can I combine multiple scroll event listeners into one?
- javascript - 正则表达式测试不适用于数字
- docker - 在运行 HornetQ 的两个 Docker 容器之间共享数据文件