[英]Clear input value from Reactive Form in Angular after custom validator returns 'invalid'
我有一個用 Angular 6 編寫的反應式表單。我有一個帶有自定義驗證器的輸入文本字段。 驗證器正常工作。 文本字段包含一個下拉列表。 如果用戶輸入不在列表中的數據並切換到下一個字段,驗證器將顯示錯誤(“位置無效”)。
一旦用戶切換到下一個字段並顯示無效的錯誤消息,我希望清除文本框中的無效數據。 這是 HTML:
<input
type="text"
matInput
formControlName = 'originControl'
[(ngModel)]="originId"
[matAutocomplete]="autoOrigin"
id="mat-card__origin-input-id"
/>
<mat-autocomplete autoActiveFirstOption #autoOrigin="matAutocomplete">
<mat-option *ngFor="let option of originOptions | async" [value]="option">
{{ option }}
</mat-option>
</mat-autocomplete>
<mat-error *ngIf="scheduleForm.controls['originControl'].hasError('invalid')" id="mat-error__origin">
Please select a valid location
</mat-error>
這是驗證器功能:
export function ValidateLocation(locationArray: Array<any>): ValidatorFn {
return (control: AbstractControl): { [key: string]: boolean } | null => {
if ((control.value !== undefined || control.value !== null || control.value !== "") &&
(locationArray.indexOf(control.value) == -1)) {
return { 'invalid': true };
}
return null;
}
}
這是創建 FormControl 的打字稿:
this.scheduleForm = new FormGroup({
'originControl': new FormControl(null, [ValidateLocation(this.fetchDataService.locationArray)])
});
如何清除控件中的數據並留下錯誤信息?
你可以得到你的 formControl 並重置它
if(this.scheduleForm.get('originControl').invalid){
this.scheduleForm.get('originControl').reset();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.