Angular 这是将验证器添加到自定义表单控件中现有验证器的正确方法吗?
我想知道我的解决方案是否正确。在我的应用程序中,我使用的是反应式表单,在实现ControlValueAccessor的CustomFormControl中,我添加了验证器myControl:[,Validators.required]。此验证器仅在少数页面上需要,这就是formBuilder添加此验证器的原因 但我也需要有验证器,将始终用于该控件。因此,为了使其在我的控件中工作,我必须添加令牌NG_验证器,这允许我使用验证方法,据我所知,每次需要验证控件时都会触发验证方法:Angular 这是将验证器添加到自定义表单控件中现有验证器的正确方法吗?,angular,typescript,angular-reactive-forms,Angular,Typescript,Angular Reactive Forms,我想知道我的解决方案是否正确。在我的应用程序中,我使用的是反应式表单,在实现ControlValueAccessor的CustomFormControl中,我添加了验证器myControl:[,Validators.required]。此验证器仅在少数页面上需要,这就是formBuilder添加此验证器的原因 但我也需要有验证器,将始终用于该控件。因此,为了使其在我的控件中工作,我必须添加令牌NG_验证器,这允许我使用验证方法,据我所知,每次需要验证控件时都会触发验证方法: @Component
@Component({
selector: "my-control",
templateUrl: "./my-control.component.html",
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: MyControlComponent,
multi: true
},
{
provide: NG_VALIDATORS,
useExisting: MyControlComponent,
multi: true
}
]
})
export class MyControlComponent implements OnInit, ControlValueAccessor {
...
validate(value: AbstractControl): void {
value.setValidators(Validators.compose([value.validator, Validators.min(0), Validators.max(200)]));
}
}
请注意,我使用value.validator是因为我想将表单生成器中添加的现有验证器与这些最小和最大验证器合并。一切正常,但这是一个合适的解决方案,因为我在谷歌找不到这种情况。我找到了更好的解决方案,验证器可以直接添加到提供者数组中
providers: [
{provide: NG_VALIDATORS, useValue: Validators.min(0), multi: true},
{provide: NG_VALIDATORS, useValue: Validators.max(200), multi: true},
]