如何编写自定义验证器以进行响应式表单控制

时间:2019-08-22 13:37:37

标签: angular forms validation

我想验证字段type以包含数组形式itemsFormArray中重复的所选元素。我为此(itemTypeValidator写了一个自定义验证器,但未显示错误消息。另外,我编写了一个自定义的TypeItemErrorMatcher类,该类从ErrorStateMatcher实现,但无法解决( 也就是说,如果调试功能isErrorState,则断点不会在该位置停止。错误在哪里?

item.component.html

    <div *ngFor="let item of itemsFormArray.controls; let i = index">
  <mat-form-field [floatLabel]="'never'">
    <mat-select [value]="item.value.type" (selectionChange)="selectItemType($event, i)" [errorStateMatcher]="typeItemErrorMatcher">
      <mat-option *ngFor="let itemType of itemTypes$ | async" [value]="itemType.code">
        {{itemType.name}}
      </mat-option>
    </mat-select>
    <mat-error *ngIf="itemsFormArray.controls[i].get('type').hasError('itemTypeExisted')">Уже существует</mat-error>
  </mat-form-field>
</div>

item.component.ts

typeItemErrorMatcher = new TypeItemErrorMatcher();

form.service.ts

createItemsGroup(value: any): FormGroup {
  return this.fb.group({
    type: [value.type, this.itemTypeValidator()]
  });
}

itemTypeValidator(): ValidatorFn {

  return (itemTypeControl: FormControl): ValidationErrors => {
    const itemsFormArray = itemTypeControl.root.value.itemsContent;
    if (itemsFormArray && itemTypeControl.value.length !== 0) {
      const resultConditionItemType = itemsFormArray.items.some(item => {
        return itemTypeControl.value === item.type;
      });
      return resultConditionItemType ? {itemTypeExisted: true} : null;;
    }
  };
}

typeItemErrorMatcher.ts

export class TypeItemErrorMatcher implements ErrorStateMatcher {

	isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
		return form.hasError('itemTypeExisted');
	}
}

1 个答案:

答案 0 :(得分:0)

尝试:

 <mat-error *ngIf="myFormField.get('value').hasError(patternCustom)">required field</mat-error>