简体   繁体   English

自定义验证器返回“无效”后,从 Angular 中的响应式表单中清除输入值

[英]Clear input value from Reactive Form in Angular after custom validator returns 'invalid'

I have a reactive form written in Angular 6. I have an input text field that has a custom validator.我有一个用 Angular 6 编写的反应式表单。我有一个带有自定义验证器的输入文本字段。 The validator works correctly.验证器正常工作。 The text field contains a dropdown list.文本字段包含一个下拉列表。 If the user enters data not in the list and tabs to the next field, the validator display an error ('location not valid').如果用户输入不在列表中的数据并切换到下一个字段,验证器将显示错误(“位置无效”)。

I would like the invalid data in the text box to be cleared once the user tabs to the next field and the invalid error message display.一旦用户切换到下一个字段并显示无效的错误消息,我希望清除文本框中的无效数据。 This is the HTML:这是 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>

This is the validator function:这是验证器功能:

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;
    }
}

This is the typescript that creates the FormControl:这是创建 FormControl 的打字稿:

this.scheduleForm = new FormGroup({
      'originControl': new FormControl(null, [ValidateLocation(this.fetchDataService.locationArray)])     
    });

How to clear the data in the control and leave the error message?如何清除控件中的数据并留下错误信息?

you can get your formControl and reset it你可以得到你的 formControl 并重置它

if(this.scheduleForm.get('originControl').invalid){
  this.scheduleForm.get('originControl').reset();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM