我有一个自定义的表单控件组件(这是美化的输入)。之所以将其作为自定义组件,是为了简化UI更改-也就是说,如果从根本上改变我们对输入控件进行样式设置的方式,则很容易在整个应用程序中传播更改。
目前,我们在Angular https://material.angular.io中使用Material Design
当这些样式无效时,它们会很好地控制。
我们已经实现了ControlValueAccessor,以允许我们将formControlName传递给我们的自定义组件,该组件运行良好。当自定义控件有效/无效并且应用程序按预期运行时,表单有效/无效。
但是,问题在于,我们需要根据自定义组件内的UI是否无效来对其进行样式设置,这似乎是我们无法做到的-实际需要设置样式的输入从未得到验证,它只需在父组件之间传递数据。
组件
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]
});
最佳答案
您可以通过DI访问NgControl
。 NgControl
包含有关验证状态的所有信息。要检索NgControl
,您不应通过NG_VALUE_ACCESSOR
提供组件,而应在构造函数中设置访问器。
@Component({
selector: 'custom-form-comp',
templateUrl: '..',
styleUrls: ...
})
export class CustomComponent implements ControlValueAccessor {
constructor(@Self() @Optional() private control: NgControl) {
this.control.valueAccessor = this;
}
// ControlValueAccessor methods and others
public get invalid(): boolean {
return this.control ? this.control.invalid : false;
}
public get showError(): boolean {
if (!this.control) {
return false;
}
const { dirty, touched } = this.control;
return this.invalid ? (dirty || touched) : false;
}
}
请浏览此article以了解完整信息。
关于forms - 在Angular中使用ControlValueAccessor继承验证,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45556839/