繁体   English   中英

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

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

我有一个自定义验证器 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;
};
}

正如您在内部看到的那样,我在验证失败时将控件的值设置为“”(空)。
我还想将焦点放在它上面,如何将本机控件注入到那里以便我可以使用它的.focus()方法? 任何其他适合我情况的方式也都很好。

提前致谢!

我通过在输入本身上使用blur事件并从自定义控件组件内部而不是自定义验证器 Fn 检查控件状态是否无效来解决它:

在.html:

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

和 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