如何在 CVA 中实现验证?

How to implement validation in CVA?

我创建表单,此表单的字段之一是 cantrolValueAcessor 组件。该字段只是一个数字和几个按钮。点击左键后数字减少,点击右键后数字增加。

我想对 cantrolValueAcessor 字段使用验证。当数字小于“0”时必须显示错误消息。

这是我的attempt

CVA代码:

import { Component, forwardRef } from '@angular/core';
import {
  ControlValueAccessor,
  NG_VALIDATORS,
  NG_VALUE_ACCESSOR,
  Validator,
} from '@angular/forms';

@Component({
  selector: 'hello',
  template: `
    <button (click)="minus()">minus</button>
    <button (click)="plus()">plus</button>
    {{ value }}
  `,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => HelloComponent),
      multi: true,
    },
    {
      provide: NG_VALIDATORS,
      useExisting: forwardRef(() => HelloComponent),
      multi: true,
    },
  ],
})
export class HelloComponent implements ControlValueAccessor, Validator {
  value: number;

  validate() {
    return this.value > 0 ? null : { positive: true };
  }

  onChange: any = () => {};
  onTouch: any = () => {};

  registerOnChange(fn: any) {
    this.onChange = fn;
  }
  registerOnTouched(fn: any) {
    this.onTouch = fn;
  }

  writeValue(input: number) {
    this.value = input;
  }

  minus() {
    this.value -= 1;
  }

  plus() {
    this.value += 1;
  }
}

家长代码:

this.form = this.fb.group({
      name: [null, [Validators.required]],
      email: [null, [Validators.required, Validators.email]],
      buttons: [0],
    });

由于您已经在使用表单控件,因此您可以轻松地添加它们 minValue 验证器,然后在表单控件对象中检查该错误。

https://angular.io/api/forms/Validators#min