检查是否需要 NgControl

Joh*_*nko 7 primeng angular angular-reactive-forms angular-forms

由于各种原因,我有几个包装 PrimeNG 组件的自定义组件。我的组件的某些实例以反应形式使用,并且该字段的“要求”是使用Validators.required验证器设置的。

PrimeNG 组件提供一个required属性。

如何检查组件的 NgControl 是否有所需的验证器?存在.disabled.invalid,但.invalid可以表示任何意思。

这是我现在使用的,它适用于下拉菜单,但对于任何其他类型的输入来说都是不正确的。

@Component({
  selector: 'my-component',
  templateUrl: 'my.component.html'
})
export class MyComponent implements OnInit, ControlValueAccessor {
  
  @Input()
  public disabled: boolean
  @Input()
  public required: boolean

  constructor(
        @Optional() @Self() public ngControl: NgControl
  ) {
        if (this.ngControl != null) {
            this.ngControl.valueAccessor = this;
        }
    }

    ngOnInit() {
        if (this.ngControl) {
            this.required = this.ngControl.invalid;
            this.disabled = this.ngControl.disabled;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我确信有更好的方法可以做到这一点,但我不知道如何做。

Ame*_*mer 6

尝试检查控件是否有required验证器,如下所示:

  ngOnInit() {
    if (this.ngControl) {
      this.required = this.hasRequiredValidator(this.ngControl.control);
      this.disabled = this.ngControl.disabled;
    }
  }

  hasRequiredValidator(control: AbstractControl): boolean {
    if (control.validator) {
      const validator = control.validator({} as AbstractControl);
      if (validator && validator.required) {
        return true;
      }
    }
    return false;
  }
Run Code Online (Sandbox Code Playgroud)

更新:

从 Angular 12.2.0 开始,要检查 NgControl 是否具有required验证器,我们可以使用Angular 12.2.0 中引入的AbstractControl.hasValidator() API(就像 MatInput在使用必需的验证器时如何显示必需的星号一样)

  constructor(@Optional() @Self() private ngControl: NgControl) {}

  ngOnInit() {
    if (this.ngControl) {
      this.required = this.ngControl?.control?.hasValidator(Validators.required);
    }
  }
Run Code Online (Sandbox Code Playgroud)