我有一个自定义表单控件组件(它是一个美化的输入) . 它作为自定义组件的原因是为了便于UI更改 - 即,如果我们从根本上改变我们对输入控件进行样式设置的方式,则很容易在整个应用程序中传播更改 .
目前我们在Angular中使用Material Design https://material.angular.io
哪些样式在无效时控制得非常好 .
我们已经实现了ControlValueAccessor,以便允许我们将formControlName传递给我们的自定义组件,该组件工作正常;当自定义控件有效/无效且应用程序按预期运行时,表单有效/无效 .
但是,问题是我们需要根据自定义组件是否无效来设置自定义组件的样式,我们似乎无法做到这一点 - 实际需要设置样式的输入永远不会被验证,它只需将数据传入父组件或从父组件传递数据 .
COMPONENT.ts
import { Component, forwardRef, Input, OnInit } from '@angular/core';
import {
AbstractControl,
ControlValueAccessor,
NG_VALIDATORS,
NG_VALUE_ACCESSOR,
ValidationErrors,
Validator,
} from '@angular/forms';
@Component({
selector: 'app-input',
templateUrl: './input.component.html',
styleUrls: ['./input.component.css'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => InputComponent),
multi: true
}
]
})
export class InputComponent implements OnInit, ControlValueAccessor {
writeValue(obj: any): void {
this._value = obj;
}
registerOnChange(fn: any): void {
this.onChanged = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
setDisabledState?(isDisabled: boolean): void {
this.disabled = isDisabled;
}
get value() {
return this._value;
}
set value(value: any) {
if (this._value !== value) {
this._value = value;
this.onChanged(value);
}
}
@Input() type: string;
onBlur() {
this.onTouched();
}
private onTouched = () => {};
private onChanged = (_: any) => {};
disabled: boolean;
private _value: any;
constructor() { }
ngOnInit() {
}
}
COMPONENT.html
<ng-container [ngSwitch]="type">
<md-input-container class="full-width" *ngSwitchCase="'text'">
<span mdPrefix><md-icon>lock_outline</md-icon> </span>
<input mdInput placeholder="Password" type="text" [(ngModel)]="value" (blur)="onBlur()" />
</md-input-container>
</ng-container>
示例在页面上使用:
HTML:
<app-input type="text" formControlName="foo"></app-input>
TS:
this.form = this.fb.group({
foo: [null, Validators.required]
});
3 回答
答案在这里找到:
Get access to FormControl from the custom form component in Angular
不确定这是最好的方法,我希望有人找到一个更漂亮的方式,但将子输入绑定到以这种方式获得的表单控件解决了我们的问题
另外:可能被认为是脏的,但它对我有用:
让您的组件实现Validator接口 . 2在validate函数中,您使用controlcontainer来获取组件的外部formcontrol .
使用变量跟踪父窗体控件(VALID / INVALID)的状态 .
检查是否触及 . 仅当触摸为真且状态已更改时,才对您的字段执行验证操作 .
您可以通过DI访问
NgControl
.NgControl
包含有关验证状态的所有信息 . 要检索NgControl
,您不应通过NG_VALUE_ACCESSOR
提供组件,而应在构造函数中设置访问者 .请仔细阅读article以了解完整信息 .