我有一个反应形式
<form [formGroup]="secondFormGroup">
<ng-template matStepLabel>enter items</ng-template>
<div style="display: flex; flex-direction: column;">
<mat-form-field>
<input matInput type="text" placeholder="category" [(ngModel)]="newItem.CategoryName" formControlName="category"
/>
</mat-form-field>
<mat-form-field>
<input matInput type="text" placeholder="sub category" [(ngModel)]="newItem.SubCategoryName" formControlName="subCategory"
/>
</mat-form-field>
<mat-form-field>
<input matInput type="text" placeholder="product" [(ngModel)]="newItem.ProductName" formControlName="name"/>
</mat-form-field>
<mat-form-field>
<input matInput [(ngModel)]="newItem.Amount" type="number" min="0" placeholder="amount" formControlName="amount"
/>
</mat-form-field>
<mat-form-field>
<input matInput [(ngModel)]="newItem.Price" type="number" min="0" placeholder="price" formControlName="price"
/>
</mat-form-field>
<button mat-raised-button color="primary" (click)="AddNewProduct(newItem)" style="float: left; align-self: flex-end;">submit</button>
</div>
</form>
我这样初始化它:
this.secondFormGroup = this._formBuilder.group({
category: ['', Validators.required],
subCategory: ['', Validators.required],
name: ['', Validators.required],
amount: ['', Validators.required],
price: ['', Validators.required]
});
单击提交后,我调用此方法:
AddNewProduct(newProduct) {
if (this.secondFormGroup.valid) {
//add product
this.secondFormGroup.reset();
}
}
添加产品后,我清除了表单。
但是,一旦清除表单,就会触发验证错误。
我希望仅当用户单击“提交”且表单无效时才显示验证错误,而不是在提交后清除表单时显示验证错误。
我怎样才能解决这个问题?
问题似乎是在调用重置后表单被标记为已提交。如果表单被标记为已提交,无论其是否原始,错误都会突出显示。
你需要打电话resetForm
相反,它位于 FormGroupDirective 上:
@ViewChild(FormGroupDirective) formGroupDirective: FormGroupDirective;
this.formGroupDirective.resetForm();
其次,你需要将它包裹在一个setTimeout
超时为0,以便提交表单before它会重置。
setTimeout(() => this.formGroupDirective.resetForm(), 0)
我已经在 StackBlitz 中对此进行了测试,一切似乎都有效:
https://stackblitz.com/edit/angular-l6xq1d?file=src%2Fapp%2Fapp.component.ts https://stackblitz.com/edit/angular-l6xq1d?file=src%2Fapp%2Fapp.component.ts
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)