【发布时间】:2018-01-15 08:18:07
【问题描述】:
我有一个自定义表单控件组件(它是一个美化的输入)。它是一个自定义组件的原因是为了便于 UI 更改 - 即,如果我们从根本上更改输入控件样式的方式,那么将很容易在整个应用程序中传播更改。
目前我们在 Angular 中使用 Material Design https://material.angular.io
哪些样式在无效时可以很好地控制。
我们已经实现了 ControlValueAccessor 以允许我们将一个 formControlName 传递给我们的自定义组件,它可以完美地工作;当自定义控件有效/无效并且应用程序按预期运行时,表单有效/无效。
但是,问题是我们需要根据自定义组件内的 UI 是否无效来设置 UI 样式,而我们似乎无法做到 - 实际需要设置样式的输入永远不会经过验证,它只是将数据传入和传出父组件。
组件.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() {
}
}
组件.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]
});
【问题讨论】:
-
也许这就是您一直在寻找的? stackoverflow.com/questions/48573931/…
标签: forms angular validation controls