如何在Angular中将Validator设置为自定义表单控件



我想将验证器设置为从自定义控制组件外部在formGroup中进行精确控制

<form [formGroup]="fg">
<custom-control formControlName="custom">
</custom-control>
</form>
this.fg = this.fb.group({
custom: [null,Validator.required]
});

这是自定义控制组件:

@Component({
selector: 'custom-control',
template: `
<mat-form-field>
<input [formControl]="inputFormControl" />
<mat-error 
*ngIf="inputFormControl.hasError('required')">Required</mat-error>
</mat-form-field>
`,
styleUrls: ["custom-control.component.scss"],
providers: [
{
provide: NG_VALUE_ACCESSOR,
multi:true,
useExisting: CustomControlComponent
}
]
})
export class CustomControlComponent implements ControlValueAccessor {
inputFormControl: new FormControl();
onChange = (quantity) => {};
onTouched = () => {};
writeValue(quantity: number) {
this.quantity = quantity;
}
registerOnChange(onChange: any) {
this.onChange = onChange;
}
registerOnTouched(onTouched: any) {}
}

如何显示此必需的错误?如果我通过fg.get('custom'(.setValidator(XXX(设置另一个验证器呢?谢谢

如果要使用mat-error:

  • mat-error元素需要在具有抛出错误的inputmat-form-field
  • 实际位于mat-form-field中的FormControl必须是经过验证的精确FormControl

在您当前的情况下,您需要在custom-control周围添加一个mat-form-field,并将mat-error放在其中,而不是将mat-error放在custom-component内部。

实现Validator接口并提供NG_VALIDATORS

@Component({
selector: 'custom-control',
template: `
<input [formControl]="inputFormControl" />
<mat-error *ngIf="inputFormControl.hasError('required')">Required</mat-error>
`,
styleUrls: ["custom-control.component.scss"],
providers: [
{
provide: NG_VALUE_ACCESSOR,
multi:true,
useExisting: CustomControlComponent
},
{
provide: NG_VALIDATORS,
useExisting: forwardRef(() => CustomControlComponent),
multi: true,
},
]
})
export class CustomControlComponent implements ControlValueAccessor, Validator {
inputFormControl: new FormControl();
onChange = (quantity) => {};
onTouched = () => {};
writeValue(quantity: number) {
this.quantity = quantity;
}
registerOnChange(onChange: any) {
this.onChange = onChange;
}
registerOnTouched(onTouched: any) {}
onValidatorChange = () => {
};
registerOnValidatorChange(fn: () => void): void {
this.onValidatorChange = fn;
}
validate(c: AbstractControl): ValidationErrors | null {
return this.inputFormControl.invalid ? { internal: true } : null;
}
}

最新更新