我有一个 ngForm,它有多个按钮,除了提交表单的按钮外,每个按钮都有 diff 操作,例如,简单地更改用于 *ngIf 条件检查的状态。然而,每次我点击“创建”或“上传”按钮时,表单实际上又被提交了一次,从而在数据库中创建了一条新记录。
我尝试通过遵循此处的其他一些答案将 click 更改为 onClick 但问题仍然存在。请参考下面的代码帮助我。
<form #adsForm="ngForm" (submit)="onSubmit()">
<table class="table createAds text-center">
<thead>
......
</thead>
<tbody>
<tr class="border_bottom">
<td class="align-middle"><span style="color: red;">inactive</span></td>
......
<td class="align-middle" *ngIf="!paying && !created">
<button [disabled]="months === undefined"
class="btn btn-outline-primary" type="submit">Create
</button>
</td>
<td class="align-middle" *ngIf="created">
<button [disabled]="imageCount == 0" class="btn btn-outline-primary" (click)="confirmToPay()">Pay
</button>
</td>
<td class="align-middle" *ngIf="!paying && !created">
<button class="btn btn-outline-primary" (click)="onCancel()">Cancel</button>
</td>
<td class="align-middle" *ngIf="created">
<button class="btn btn-outline-primary" (click)="onUpload()">Upload</button>
</td>
</tr>
</tbody>
</table>
</form>
onSubmit() {
let data = new AdsToCreate();
......
this.memberService.createAds(data).subscribe(resp => {
this.getUserAds();
this.created = true;
}, error => {
console.log(error);
});
}
confirmToPay() {
this.confirming = true;
}
onCancel() {
this.requesting = true;
this.paying = false;
this.checking = false;
this.created = false;
}
onUpload() {
this.uploading = true;
}
这很奇怪,请尝试删除
(submit)
元素上的 form
事件处理程序。
<form #adsForm="ngForm">
并从此按钮中删除
type="submit"
并向其添加 (click)
事件处理程序:
<button [disabled]="months === undefined"
class="btn btn-outline-primary" (click)="onSubmit()">Create
</button>
或
您可以尝试将
type="button"
显式添加到所有其他按钮。
<form #adsForm="ngForm" (submit)="onSubmit()">
<table class="table createAds text-center">
<thead>
......
</thead>
<tbody>
<tr class="border_bottom">
<td class="align-middle"><span style="color: red;">inactive</span></td>
......
<td class="align-middle" *ngIf="!paying && !created">
<button [disabled]="months === undefined"
class="btn btn-outline-primary" type="submit">Create
</button>
</td>
<td class="align-middle" *ngIf="created">
<button type="button" [disabled]="imageCount == 0" class="btn btn-outline-primary" (click)="confirmToPay()">Pay
</button>
</td>
<td class="align-middle" *ngIf="!paying && !created">
<button type="button" class="btn btn-outline-primary" (click)="onCancel()">Cancel</button>
</td>
<td class="align-middle" *ngIf="created">
<button type="button" class="btn btn-outline-primary" (click)="onUpload()">Upload</button>
</td>
</tr>
</tbody>
</table>
</form>
它有效,非常感谢 您可以尝试将 type="button" 显式添加到所有其他按钮。