我知道這個問題以前被問過很多次。我想在提交后重置我的表單和驗證。我使用 formGroup 創建一個表單。如果表單有效,我使用按鈕提交表單我使用 form.reset() 重置表單它清除欄位但不是錯誤我也嘗試使用
this.form.markAsPristine();
this.form.markAsUntouched();
this.form.updateValueAndValidity();
重置表單驗證,但它沒有作業
從下面給出的代碼中,我可以重置表單,但輸入欄位仍然臟或被觸摸,結果輸入欄位標記為紅色。有人可以建議我什么是創建表單、重置表單和驗證的最佳實踐。
我的 html 代碼是
<mat-form-field appearance="outline" style="width: 100%;">
<input type="text" matInput formControlName="title" placeholder="Enter Module Title" #message maxlength="50">
<mat-error *ngIf="form.controls.title.hasError('required') && (form.controls.title.dirty || form.controls.title.touched)">
Module Title is <strong>required</strong>
</mat-error>
</mat-form-field>
<button (click)="save()"> Save</button>
這是我的 .TS 檔案
@ViewChild('my2Form', { static: false }) my2Form!: NgForm;
this.form = this.fb.group({
title: ['',[Validators.required]],
});
save()
{ if(this.form.invalid)
{ this.form.markAllAsTouched();
return;
}
else
{
this.my2Form.resetForm();
this.form.markAsPristine();
this.form.markAsUntouched();
this.form.updateValueAndValidity();
this.form.markAsPristine();
}

uj5u.com熱心網友回復:
在模板中添加type=button:
<button type="button" (click)="save()">Save</button>
在 component.ts
if (this.form1.invalid) {
this.form1.markAllAsTouched();
} else {
this.form1.reset();
}
角度演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/311248.html
