我的意思是我有一个包含动态订单项目集合的订单页面。我想要求用户在该数组中至少有一项。我了解自定义验证器的简单用法,但在这种情况下,我验证的不是单个控件,而是一个数组。我怎么说'如果数组中没有值则给出错误'?
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>