示例 Plunker
我看到有两个选项:
- 每当
<select>
的 FormControl
值更改时,将组件 FormControl
中的错误传播到 <select>
的 FormControl
- 将组件
FormControl
中的验证器传播到 <select>
的 FormControl
以下变量可用:
selectModel
是 <select>
的 NgModel
formControl
是作为参数接收的组件的 FormControl
选项 1:传播错误
ngAfterViewInit(): void {
this.selectModel.control.valueChanges.subscribe(() => {
this.selectModel.control.setErrors(this.formControl.errors);
});
}
选项2:传播验证器
ngAfterViewInit(): void {
this.selectModel.control.setValidators(this.formControl.validator);
this.selectModel.control.setAsyncValidators(this.formControl.asyncValidator);
}
两者的区别在于传播错误意味着已经有了错误,而第二个选项涉及执行验证器第二次。其中一些,如异步验证器可能太昂贵而无法执行。
传播所有属性没有通用解决方案。各种属性由各种指令或其他方式设置,因此具有不同的生命周期,这意味着需要特殊处理。当前解决方案涉及传播验证错误和验证器。有许多可用的属性。
请注意,您可以通过订阅
FormControl.statusChanges()
来获取FormControl实例的不同状态更改。这样,您可以知道控件是有效、无效、禁用还是挂起(异步验证仍在运行)。
验证的工作原理是什么?
在幕后,验证器使用指令(
查看源代码)应用。这些指令有
providers: [REQUIRED_VALIDATOR]
,这意味着它们使用自己的分层注入器来注册验证器实例。因此,根据应用于元素上的属性,指令将在与目标元素关联的注入器中添加验证器实例。
接下来,
NgModel
和
FormControlDirective
检索这些验证器。
验证器以及值访问器的检索方式如下:
constructor(@Optional() @Host() parent: ControlContainer,
@Optional() @Self() @Inject(NG_VALIDATORS) validators: Array<Validator|ValidatorFn>,
@Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: Array<AsyncValidator|AsyncValidatorFn>,
@Optional() @Self() @Inject(NG_VALUE_ACCESSOR)
分别是:
constructor(@Optional() @Self() @Inject(NG_VALIDATORS) validators: Array<Validator|ValidatorFn>,
@Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: Array<AsyncValidator|AsyncValidatorFn>,
@Optional() @Self() @Inject(NG_VALUE_ACCESSOR)
valueAccessors: ControlValueAccessor[])
注意使用了
@Self()
,因此在获取依赖项时使用了自己的注入器(应用指令的元素的注入器)。
NgModel
和
FormControlDirective
都有一个
FormControl
实例,它实际上更新值并执行验证器。
因此,与之交互的主要点是
FormControl
实例。
此外,所有验证器或值访问器都在应用它们的元素的注入器中注册。这意味着父级不应该访问该注入器。因此,从当前组件访问由
<select>
提供的注入器是一种不好的做法。
选项1的示例代码(可以轻松替换为选项2)
以下示例有两个验证器:一个是必填项,另一个是强制选项匹配“option 3”的模式。
PLUNKER
options.component.ts
import {AfterViewInit, Component, forwardRef, Input, OnInit, ViewChild} from '@angular/core';
import {ControlValueAccessor, FormControl, NG_VALUE_ACCESSOR, NgModel} from '@angular/forms';
import {SettingsService} from '../settings.service';
const OPTIONS_VALUE_ACCESSOR: any = {
multi: true,
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => OptionsComponent)
};
@Component({
providers: [OPTIONS_VALUE_ACCESSOR],
selector: 'inf-select[name]',
templateUrl: './options.component.html',
styleUrls: ['./options.component.scss']
})
export class OptionsComponent implements ControlValueAccessor, OnInit, AfterViewInit {
@ViewChild('selectModel') selectModel: NgModel;
@Input() formControl: FormControl;
@Input() name: string;
@Input() disabled = false;
private propagateChange: Function;
private onTouched: Function;
private settingsService: SettingsService;
selectedValue: any;
constructor(settingsService: SettingsService) {
this.settingsService = settingsService;
}
ngOnInit(): void {
if (!this.name) {
throw new Error('Option name is required. eg.: <options [name]="myOption"></options>>');
}
}
ngAfterViewInit(): void {
this.selectModel.control.valueChanges.subscribe(() => {
this.selectModel.control.setErrors(this.formControl.errors);
});
}
writeValue(obj: any): void {
this.selectedValue = obj;
}
registerOnChange(fn: any): void {
this.propagateChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
}
}
options.component.html
<select #selectModel="ngModel"
class="form-control"
[disabled]="disabled"
[(ngModel)]="selectedValue"
(ngModelChange)="propagateChange($event)">
<option value="">Select an option</option>
<option *ngFor="let option of settingsService.getOption(name)" [value]="option.description">
{{option.description}}
</option>
</select>
options.component.scss
:host {
display: inline-block;
border: 5px solid transparent;
&.ng-invalid {
border-color: purple;
}
select {
border: 5px solid transparent;
&.ng-invalid {
border-color: red;
}
}
}
使用方法
定义FormControl
实例:
export class AppComponent implements OnInit {
public control: FormControl;
constructor() {
this.control = new FormControl('', Validators.compose([Validators.pattern(/^option 3$/), Validators.required]));
}
...
将
FormControl
实例绑定到组件:
<inf-select name="myName" [formControl]="control"></inf-select>
虚拟 SettingsService
export class SettingsService {
public getOption(name: string): [{ description: string }] {
return [
{ description: 'option 1' },
{ description: 'option 2' },
{ description: 'option 3' },
{ description: 'option 4' },
{ description: 'option 5' },
];
}
}