简体   繁体   English

如何将焦点设置到验证器 function 内部验证失败的控件?

[英]How to set focus to a control that failed validation from inside the validator function?

I have a custom validator function as follows:我有一个自定义验证器 function,如下所示:

export function numRangeValidator(min: number, max: number): ValidatorFn {
return (control: AbstractControl): { [key: string]: boolean } | null => {
    let tempVal;
    try {
        tempVal = typeof (control.value) === 'number' ? +control.value : +control.value.replace(/[pP]/g, '');
    } catch { }
    if (control.value === null || control.value === '' || control.value === undefined || !control.value) {
        return null;
    }
    if (control.value !== undefined && (isNaN(tempVal) || tempVal < min || tempVal > max)) {
        control.setValue('');
        return { 'numRange': true };
    }
    return null;
};
}

as you can see inside, I set the control's value to '' (empty) when it fails validation.正如您在内部看到的那样,我在验证失败时将控件的值设置为“”(空)。
I would also like to set focus to it, how could i inject the native control into there so I could use its .focus() method?我还想将焦点放在它上面,如何将本机控件注入到那里以便我可以使用它的.focus()方法? Any other way that would fit my situation would be good too.任何其他适合我情况的方式也都很好。

Thanks in advance!提前致谢!

I solved it by using the blur event on the input itself and checking if the control status is Invalid, from inside the custom control component and not the custom validator Fn:我通过在输入本身上使用blur事件并从自定义控件组件内部而不是自定义验证器 Fn 检查控件状态是否无效来解决它:

in.html:在.html:

   <input #oinput (blur)="checkValidation()">

and in.ts:和 in.ts:

export class GenericInputComponent implements OnInit, ControlValueAccessor {
...
@ViewChild('oinput', { static: false }) oinput: ElementRef;
...
constructor(
  @Optional()
  @Self()
  public controlDir: NgControl
} (
  this.controlDir.valueAccessor = this;
  )
...
checkValidation() {
 if (this.controlDir
     && !(this.controlDir.control.valid
     && (this.controlDir.control.touched 
     && !(this.controlDir.control.hasError('required'))))) {
         this.oinput.nativeElement.focus();
 }
}

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

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