Angular child component ng-invalid

Deadly 提交于 2020-01-15 20:21:08

问题


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()" />

The class is:

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>

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.

Here's a Stackblitz showing the issue. https://stackblitz.com/edit/angular-child-ng-invalid


回答1:


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



来源:https://stackoverflow.com/questions/51093972/angular-child-component-ng-invalid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!