问题描述
我创建了代表密码表单控制的自定义组件(以下代码已简化).
I created custom component representing password form control (code below is simplified).
PasswordComponent(html)
PasswordComponent (html)
<form [formGroup]="passwordForm">
...
<input formControlName="password" type="password">
</form>
PasswordComponent(ts)
PasswordComponent (ts)
...
@Component({
selector: 'password',
templateUrl: './password.component.html',
styleUrls: ['./password.component.css'],
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => PasswordComponent),
multi: true
}]
})
export class PasswordComponent implements ControlValueAccessor {
passwordForm: FormGroup;
onChange = (password: string) => { };
onTouched = () => { };
constructor() {
this.passwordForm = new FormGroup({
...
password: new FormControl('')
});
this.passwordForm.valueChanges.subscribe(data => this.onChange(this.value));
}
get value(): string {
return this.passwordForm.get('password').value;
}
writeValue(password: string): void {
this.passwordForm.get('password').setValue(password);
this.onChange(this.value);
}
registerOnChange(fn: any): void { this.onChange = fn; }
registerOnTouched(fn: any): void { this.onTouched = fn; }
setDisabledState?(isDisabled: boolean): void { }
}
我在其他组件而不是标准输入元素中使用它:
I use it in other components instead of standard input element:
<form [formGroup]="userForm">
...
<password formControlName="password"></password>
</form>
验证者来自外部形式(它们未在PasswordComponent中定义)
Validators are coming from outer form (they're not defined inside PasswordComponent)
this.userForm = fb.group({
...
password: ['', [Validators.minLength(10), Validators.maxLength(100)]]
});
我的问题是:如何从PasswordComponent内部获取<password>
元素的有效性?我想根据有效性对其进行样式化.换句话说,如何从代表该控件的PasswordComponent中获得userForm的密码"控件的有效性.
My question is: how can I get <password>
element validity from inside PasswordComponent? I would like to stylize it based on validity. In other words how can I get validity of userForm's 'password' control from PasswordComponent that represents this control.
推荐答案
由于我们将直接得到DI的依赖,因此无法直接从DI系统获取NgControl
实例.下图显示了为什么在自定义值访问器中注入NgControl
时会发生这种情况:
As we can't get NgControl
instance directly from DI system since we'll get a circular dependency error. The following diagram shows why it happens if we inject NgControl
in our custom value accessor:
现在应该很清楚,我们有NgControl -> FormControlName -> ValueAccessor -> CustomValueAccessor -> NgControl
循环依赖项
Now it should be clear that we have NgControl -> FormControlName -> ValueAccessor -> CustomValueAccessor -> NgControl
circular dependency
要解决此问题,您可以利用Injector
来实现:
To work around it you can leverageInjector
to achieve that:
component.ts
import { NgControl } from '@angular/forms';
export class PasswordComponent implements ControlValueAccessor {
...
ngControl: NgControl;
constructor(private inj: Injector) {
...
}
ngOnInit() {
this.ngControl = this.inj.get(NgControl)
}
template.html
{{ ngControl.control.valid }}
Plunker Example
这篇关于访问自定义表单控件的有效值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!