表单提交已取消,因为未连接表单
该模态框添加到一个名为<modal-placeholder>
的元素中,该元素是<app-root>
的直接子元素,而<app-root>
是我的顶级元素。
在Angular 2中,正确的方法是从DOM中移除表单并摆脱此错误?我当前使用componentRef.destroy();
表单提交已取消,因为未连接表单
该模态框添加到一个名为<modal-placeholder>
的元素中,该元素是<app-root>
的直接子元素,而<app-root>
是我的顶级元素。
在Angular 2中,正确的方法是从DOM中移除表单并摆脱此错误?我当前使用componentRef.destroy();
可能还有其他原因导致此问题发生,但在我的情况下,浏览器将一个按钮解释为提交按钮,因此当单击该按钮时,表单被提交导致错误。添加type="button"修复了这个问题。完整元素:
<button type="button" (click)="submitForm()">
type="button"
:) - Marcos Lima <form #myForm="ngForm" (ngSubmit)="onSubmit()">
在表单内部,您应该拥有提交按钮:
<button type="submit"></button>
最重要的是,如果你的表单中有其他按钮,你应该给它们添加type="button"
属性。保留默认的type
属性(我认为是submit
)将会导致警告信息。
<button type="button"></button>
今天我遇到了完全相同的问题,但没有使用模态框。在我的表单中,有两个按钮。一个提交表单,另一个在点击时返回上一页。
<button class="btn btn-default" routerLink="/events">Cancel</button>
<button type="submit" class="btn btn-primary">Submit</button>
点击具有routerLink的第一个按钮确切地执行了它应该执行的操作,但似乎也试图提交表单,然后在提交过程中必须放弃表单提交,因为表单所在的页面已从DOM中卸载。
这似乎与您遇到的问题完全相同,只是使用的是模态框而不是整个页面。
如果直接指定第二个按钮的类型为除submit以外的其他内容,则问题得到解决。
<button type="button "class="btn btn-default" routerLink="/events">Cancel</button>
所以,如果您通过“取消”按钮或类似物品关闭模态框,则指定该按钮的类型(如上所示)应解决您的问题。<form id="currency-edit" (ngSubmit)="onSubmit(f.value)" #f="ngForm">
在提交按钮上,您省略了单击方法,因为您的表单现在连接到了提交方法:
<button class="btn btn-success" type="submit">保存</button>
按钮应该是提交类型。onSubmit(value: ICurrency) {
...
}
此方法接收一个值对象,其中包含来自表单字段的值。如果在提交表单时伴随着组件的销毁,那么表单提交会在表单从DOM中分离的竞争条件下失败。例如,我们有以下代码:
submitForm() {
if (this.myForm.invalid) {
return;
}
this.saveData(); // processing Form data
this.abandonForm(); // change route, close modal, partial template ngIf-destroying etc
}
saveData
是异步的(例如通过API调用保存数据),那么我们可能需要等待结果:submitForm() {
this.saveDataAsync().subscribe(
() => this.abandonForm(),
(err) => this.processError(err) // may include abandonForm() call
);
}
submitForm() {
this.saveData();
setTimeout(() => this.abandonForm());
}
我最近遇到了这个问题,event.preventDefault()
对我有用。
将其添加到您的点击事件方法中。
<button type="submit" (click)="submitForm($event)" mat-raised-button>Save</button>
并且:
submitForm(event: Event) {
event.preventDefault();
// ...
}
type="button"
。 - Gavin Sutherland我通过添加属性type = "button"
解决了这个问题。
<button type="button" onClick={props.formHandler}>Cancel</button>
我曾经遇到过这个警告,我把按钮类型从“submit”改成了“button”,问题得到了解决。
我在Angular 6中看到了这个问题,即使没有提交按钮。 当同一模板中存在多个表单时会发生这种情况。 不确定是否有解决方案/解决方案是什么。
<form (ngSubmit)="destroyComponent()">
<button type="submit">submit</button>
</form>
componentRef.destroy();
来销毁模态框。我已经在我的问题中添加了更多细节。谢谢! - nick