在反应形式中,我如何创建一个自定义验证器来验证 formGroup 数组是否没有值?

In reactive forms how do I create a custom validator that can validate an array of formGroup for no values?

我的意思是我有一个包含动态订单商品集合的订单页面。我想要求用户在该数组中至少有一项。我了解自定义验证器的简单用法,但在这种情况下,我不是在验证单个控件,而是在验证一个数组。 'If there are no values in the array then give error' 怎么说?

createFormGroup(order: Order): FormGroup {
const group = this.fb.group({
  id: [order.id],
  isItPurchase: [order.isItPurchase],
  orderItems: this.fb.array([])
});

order.orderItems.forEach(x => {
  var formArray = group.controls.orderItems as FormArray;
  formArray.push(this.createOrderItem(x));
});

    return group;
  }

 
 createOrderItem(item: OrderItem): FormGroup {
    const formGroup = this.fb.group({
      id: [item.id],
      name: [item.name, Validators.required],
      unitPrice: [item.unitPrice, Validators.required],
      units: [item.units, Validators.required]
    });

    return formGroup;
  }

对于一个简单的案例,我会做类似的事情

      // xxxValidator(control: AbstractControl): { [key: string]: boolean } | null {
  //   if (control.value === 'xxx') {
  //     return { 'xxxValidator': true }
  //   }
  //   return null;
  // };

编辑 1:

我更近了。我确定错误何时存在。但是我的模板是错误的。如何查看模板中的错误?

createFormGroup(order: Order): FormGroup {
    const group = this.fb.group({
      id: [order.id],
      isItPurchase: [order.isItPurchase],
      orderItems: this.fb.array([])
    },
      { validators: [this.testValidation1] }
      // { validators: [this.testValidation2] }
    );

    order.orderItems.forEach(x => {
      var formArray = group.controls.orderItems as FormArray;
      formArray.push(this.createOrderItem(x));
    });

    return group;
  }

  createOrderItem(item: OrderItem): FormGroup {
    const formGroup = this.fb.group({
      id: [item.id],
      name: [item.name, Validators.required],
      unitPrice: [item.unitPrice, Validators.required],
      units: [item.units, Validators.required]
    });

    return formGroup;
  }

  testValidation1(form: FormGroup) {
    if (form.value.orderItems.length === 0) {
      return { valOrderItems: false };
    }

    return null;
  }

    <div>
        <div *ngFor="let fg of orderItems.controls;  let i=index">
            <app-order-item-form [orderItemForm]="fg" (itemDeleted)="onItemDeleted(i)"></app-order-item-form>
        </div>
        <!-- <span *ngIf="orderForm.errors.valOrderItems"> Must be atleast one orderItem </span> -->
    </div>

也许您应该通过

获取 FormArray 控件
   get itemsFormArray(): FormArray {
        return this.createFormGroup.get('orderItems') as FormArray;
    }

然后在你的模板中使用它,也许它不起作用或者不是你需要的但我希望它能给你线索

  <mat-error *ngIf="itemsFormArray.hasError('required')">
                    // ERROR MESSAGE               
  </mat-error>

选项 1

您可以使用 required 验证器来验证表单至少有一个元素


const group = this.fb.group({
  id: [order.id],
  isItPurchase: [order.isItPurchase],
  orderItems: this.fb.array([], [Validators.required])
});

现在获取 如果数组没有值,您可以检查 required 验证器是否失败

const error = group.get('orderItems').hasError('required');  // True if form is empty

选项 2

创建验证器函数

function formIsEmpty(control: FormArray) {
  if (control.controls.length === 0) {
    return { noValue: true}
  }
  return null;
}

在你的FormGroup中你可以像

一样使用它

const group = this.fb.group({
  id: [order.id],
  isItPurchase: [order.isItPurchase],
  orderItems: this.fb.array([], [formIsEmpty])
});

并通过

得到错误
group.get('orderItems').hasError('noValue');