javascript - angular 5,反應式表單 - 重置必填表單控制項不會重置輸入框下的必填錯誤
在範本中,我有一個可以透過按按鈕打開的表單。
<form [formGroup]="person"
(ngSubmit)="onSubmitNewPerson()"
#formDirective="ngForm">
<mat-form-field>
<input matInput formControlName="firstName" required>
</mat-form-field>
<mat-form-field>
<input matInput formControlName="lastName" #last required>
</mat-form-field>
</form>
在這個組件中,我有這段程式碼-
@ViewChild('formDirective') formDirective: FormGroupDirective;
this.person = this.formBuilder.group({
lastName: ['', Validators.required],
firstName: ['', Validators.required]
});
在關閉按鈕後,我運行這個函數-
this.formDirective.resetForm();//hack that I saw in some question
this.person.reset();
但是再次打開表單後,我立即在輸入欄下看到紅色錯誤。
我也試過這個-
this.person.get('firstName').markAsUntouched();
this.person.get('lastName').markAsUntouched();
this.person.get('firstName').markAsPristine();
this.person.get('lastName').markAsPristine();
但是這也不行。
有什麼方法可以修好它嗎?
答案#1
我曾經在想要重置驗證器時使用過以下方法:
this.person.get('firstName').clearValidators();
this.person.get('firstName').updateValueAndValidity();
答案#2
只需從你的 HTML 模板中移除 required,如果你想在失去焦點時顯示錯誤訊息,試試這個方法來顯示不同的錯誤訊息。
這是 HTML 範本:
<div class="form-group">
<label for="name" class="form-control-label">
*Amount:
</label>
<input type="number" name="amount" class="form-control" [formControl]="form.controls['amount']">
<div>
<small *ngIf="form.controls['amount'].hasError('required') && form.controls['amount'].touched" class="text-danger">
Please enter an amount.
<small *ngIf="form.controls['amount'].hasError('min') && form.controls['amount'].touched" class="text-danger">
Your amount must be at least 0.01.
<small *ngIf="form.controls['amount'].hasError('max') && form.controls['amount'].touched" class="text-danger">
Your amount cannot exceed 999999.99.
</div>
這是 component.ts
import { FormGroup, FormBuilder, Validators} from '@angular/forms';
constructor(private fb: FormBuilder) { }
this.form = this.fb.group({
amount: [null, Validators.compose([Validators.required, Validators.min(0.01), Validators.max(999999.99)])],
});
