首页 > 解决方案 > 即使我在处理程序中返回 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,表单都无法提交。

标签: javascripthtmlangular

解决方案


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.


推荐阅读