【发布时间】:2020-08-23 00:04:17
【问题描述】:
我正在使用响应式表单,并且我有一个简单的表单来添加产品。 这是产品界面:
export interface Product {
id: number,
name: string,
storeName: string,
price: number,
isRecieved: boolean,
deliveryDate: Date
}
每次用户单击“添加按钮”时,都会提交表单。因为每次我向提交的产品添加 ID 时,我都不想刷新页面,所以我可以保持 idCounter 变量的更新。虽然我在提交后添加了event.preventDefault(),但 idCounter 正在转向它的起始值,所以我猜测页面正在更新。如何预防?
<form [formGroup]="addProductForm" (ngSubmit)="onSubmit($event)">
<div>More inputs</div>
<button type="submit" mat-button color="accent" >Add Product</button>
countId:数字 = 1;
onSubmit(e) {
e.preventDefault();
if (this.addProductForm.valid) {
this.addProductForm.value.id = this.countId;
console.log(this.addProductForm.value)
this.addProductForm.value.isRecieved = false;
this.store.dispatch(addProductToList(this.addProductForm.value));
this.countId++;
this.addProductForm.reset(this.addProductForm)
this.router.navigate(['/products']);
}
}
【问题讨论】:
-
创建一个服务并存储计数器值,当您需要使用 observable() 从那里获取它时,由于 router.navigate 计数器会重置
-
很高兴知道它有效.. 不客气 :)
标签: javascript angular angular-reactive-forms