在自定义表单控件中为现有的验证器添加验证器,这种方式是否正确?

问题描述 投票:0回答:1

我想知道我的解决方案是否正确。在我的应用程序中,我使用的是Reactive Form,我的是 自定义表格控件 (实现ControlValueAccessor)我已经添加了验证器。myControl: ["", Validators.required]. 这个验证器只在几个页面上需要,所以由formBuilder添加。

但我也需要一些验证器,这些验证器将一直用于该控件。因此,为了让它在我的控件中工作,我必须添加 token NG_VALIDATORS 这让我可以使用 validate() 方法,据我所知,该方法在每次需要验证控件时都会被触发。

@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 因为我想将现有的验证器(在表单生成器中添加)与这些验证器合并。minmax 验证器。一切都很好,但这是一个正确的解决方案吗,因为我在google里找不到这样的案例。

angular typescript angular-reactive-forms
1个回答
1
投票

我找到了更好的解决方案,验证器可以直接添加到提供者数组中。

providers: [
    {provide: NG_VALIDATORS, useValue: Validators.min(0), multi: true},
    {provide: NG_VALIDATORS, useValue: Validators.max(200), multi: true},
]
© www.soinside.com 2019 - 2024. All rights reserved.