【问题标题】:Angular 12 Set Validators ComponentAngular 12 设置验证器组件
【发布时间】:2021-11-01 21:14:48
【问题描述】:

在 Angular 12 中,我正在项目中设计一个可重用的组件,但在设置验证器时出现以下错误

'(ValidatorFn | null | undefined)[]' 类型的参数不能分配给 'ValidatorFn | 类型的参数验证器Fn[] |空值'。 类型 '(ValidatorFn | null | undefined)[]' 不可分配给类型 'ValidatorFn[]'。 输入'ValidatorFn |空 | undefined' 不可分配给类型 'ValidatorFn'。 类型“未定义”不可分配给类型“ValidatorFn”。

import { Component, ElementRef, Input, OnInit, Self, ViewChild } from '@angular/core';
import { ControlValueAccessor, NgControl } from '@angular/forms';

@Component({
  selector: 'app-text-input',
  templateUrl: './text-input.component.html',
  styleUrls: ['./text-input.component.css']
})
export class TextInputComponent implements OnInit, ControlValueAccessor {

  @ViewChild('input', { static: true }) input!: ElementRef;
  @Input() type = "text";
  @Input() label!: string;

  constructor(@Self() public controlDir: NgControl) {
    this.controlDir.valueAccessor = this;
  }

  ngOnInit(): void {
    const control = this.controlDir.control;
    const validator = this.controlDir.validator ? [control?.validator] : [];
    const asyncValidator = this.controlDir.asyncValidator ? [control?.asyncValidator] : [];

    control?.setValidators(validator);
    control?.setAsyncValidators(asyncValidator);
    control?.updateValueAndValidity();
  }

  onChange(event: Event) {

  }

  onTouched() {

  }

  writeValue(obj: any): void {
    this.input.nativeElement = obj || '';
  }
  registerOnChange(fn: any): void {
    this.onChange = fn;
  }
  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }
}

提前感谢您的帮助。

【问题讨论】:

    标签: angular


    【解决方案1】:

    问题与关注

    您需要确保validatorasyncValidator 与以下参数的类型完全相同:

    setValidators()

    参数:

    验证器:ValidatorFn |验证器Fn[]

    setAsyncValidators()

    参数:

    验证器 AsyncValidatorFn | AsyncValidatorFn[]

    [control?.validator] 可能返回错误消息中提到的 ValidatorFn[]null[]undefined[] 类型的值。 [control?.asyncValidator] 也是如此。

    同时,检查this.controlDir.validator 可能不正确如果它是nullvalidators 将被设置为空数组[]this.controlDir.asyncValidator 也是如此。


    解决方案

    您需要检查 controlcontrol.validator / control.asyncValidator 是否必须具有价值才能解决此问题。

    const validator = control && control.validator 
        ? [control.validator]
        : [];
    const asyncValidator = control && control.asyncValidator 
        ? [control.asyncValidator] 
        : [];
    

    Sample Solution on StackBlitz

    【讨论】:

      猜你喜欢
      • 2022-11-05
      • 2021-12-29
      • 1970-01-01
      • 2022-07-26
      • 1970-01-01
      • 2018-06-29
      • 2023-02-17
      • 2020-01-19
      • 2018-12-20
      相关资源
      最近更新 更多