角子组件ng-invalid [英] Angular child component ng-invalid
问题描述
我正在创建一个自定义输入组件,该组件通过实现ControlValueAccessor
可以兼容表格.此输入组件由一个或多个子输入组成,但是我很难让ng-invalid
CSS类传播到子input
元素.
I'm creating a custom input component that's forms compatible by implementing ControlValueAccessor
. This input component is a composition of one or more child inputs, but I'm having trouble getting the ng-invalid
CSS class to propagate to the child input
element.
我的自定义输入组件的模板如下:
My custom input component has a template like:
<label>Input:</label> <input type="text" [(ngModel)]="value" (blur)="onInputBlur()" />
课程是:
private _value: any;
public get value(): string {
return this._value;
}
public set value(newValue) {
this._value = newValue;
this.onChangeCallback(this._value);
}
public onInputBlur() {
this.onTouchedCallback();
}
private onChangeCallback = (x: any) => { };
private onTouchedCallback = () => { };
writeValue(obj: any): void {
this._value = obj;
}
registerOnChange(fn: any): void {
this.onChangeCallback = fn;
}
registerOnTouched(fn: any): void {
this.onTouchedCallback = fn;
}
setDisabledState ? (isDisabled: boolean): void {
}
然后我使用类似以下的反应形式绑定到自定义输入组件:
And I'm binding to the custom input component using a reactive form like:
<div [formGroup]="formGroup">
<my-editor [formControlName]="'myValue'"></my-editor>
</div>
div
和my-editor
元素都得到了ng-invalid
类的应用,但是我找不到一种很好的方法将该类应用于input
元素.
The div
and my-editor
elements both get the ng-invalid
class applied, but I can't find an elegant way to get that class applied to the input
element.
这是一个显示问题的Stackblitz. https://stackblitz.com/edit/angular-child-ng-invalid
Here's a Stackblitz showing the issue. https://stackblitz.com/edit/angular-child-ng-invalid
推荐答案
我通过使用以下使用'NgControl'的实现解决了您的问题,使用这种方法,您将使自定义输入模块化,可以在需要时使用,如果可以进一步提供帮助,请发表评论: https://stackblitz.com/edit/angular- sdrrbj?file = src%2Fapp%2Fapp.component.ts
I have resolved your issue by using the below implementation using 'NgControl', using this approach you will make your custom input modular which can be used as and when required, please do comment if I could help further: https://stackblitz.com/edit/angular-sdrrbj?file=src%2Fapp%2Fapp.component.ts
这篇关于角子组件ng-invalid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!