![](/img/trans.png)
[英]Angular 4: reactive form control is stuck in pending state with a custom async validator
[英]how to write custom validator for reactive form control
我想验证一个字段type
使其在Array表单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'); } }
尝试:
<mat-error *ngIf="myFormField.get('value').hasError(patternCustom)">required field</mat-error>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.