Angular2 我可以在表单控件上设置验证器吗?
Angular2 can I get the validators set on a form control?
我写了一个自定义控件组件,我想获取它上面设置了哪些验证器。我想知道设置了哪些验证器,这样我就可以为必填字段添加一个 *
。我正在使用模板驱动的形式。
这可能吗?如何实现?
我的组件:
@Component({
selector: 'input-text2',
templateUrl: './input-text2.component.html',
styleUrls: ['/input-base2.scss', './input-text2.component.scss'],
providers: [
{ provide: NG_VALUE_ACCESSOR, multi: true, useExisting: InputText2Component }
]
})
export class InputText2Component extends InputBase2 implements ControlValueAccessor, OnInit {
private ngControl: NgControl;
value: string;
valueChange: (value: any) => void;
_onTouched: (value: any) => void;
constructor(private injector: Injector) {
super();
}
ngOnInit(): void {
this.ngControl = this.injector.get(NgControl);
}
..//other methods
}
我认为将这些构造函数依赖项添加到您的组件应该会让您获得验证器。
@NgModule({
imports: [ BrowserModule, FormsModule, ReactiveFormsModule ],
constructor(@Optional() @Inject(NG_VALIDATORS) private validators,
@Optional() @Inject(NG_ASYNC_VALIDATORS) private validators) {}
FormsModule
应该导出这些标记。
我写了一个自定义控件组件,我想获取它上面设置了哪些验证器。我想知道设置了哪些验证器,这样我就可以为必填字段添加一个 *
。我正在使用模板驱动的形式。
这可能吗?如何实现?
我的组件:
@Component({
selector: 'input-text2',
templateUrl: './input-text2.component.html',
styleUrls: ['/input-base2.scss', './input-text2.component.scss'],
providers: [
{ provide: NG_VALUE_ACCESSOR, multi: true, useExisting: InputText2Component }
]
})
export class InputText2Component extends InputBase2 implements ControlValueAccessor, OnInit {
private ngControl: NgControl;
value: string;
valueChange: (value: any) => void;
_onTouched: (value: any) => void;
constructor(private injector: Injector) {
super();
}
ngOnInit(): void {
this.ngControl = this.injector.get(NgControl);
}
..//other methods
}
我认为将这些构造函数依赖项添加到您的组件应该会让您获得验证器。
@NgModule({
imports: [ BrowserModule, FormsModule, ReactiveFormsModule ],
constructor(@Optional() @Inject(NG_VALIDATORS) private validators,
@Optional() @Inject(NG_ASYNC_VALIDATORS) private validators) {}
FormsModule
应该导出这些标记。