Angular 子组件 ng-invalid [英] Angular child component ng-invalid

查看:25
本文介绍了Angular 子组件 ng-invalid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过实现 ControlValueAccessor 创建一个与表单兼容的自定义输入组件.此输入组件是一个或多个子输入的组合,但我无法将 ng-invalid CSS 类传播到子 input 元素.

我的自定义输入组件有一个模板,如:

<input type="text" [(ngModel)]="value" (blur)="onInputBlur()"/>

课程是:

private _value: any;公共获取值():字符串{返回 this._value;}公共设置值(新值){this._value = newValue;this.onChangeCallback(this._value);}公共 onInputBlur() {this.onTouchedCallback();}私有 onChangeCallback = (x: any) =>{ };私人 onTouchedCallback = () =>{ };writeValue(obj: any): void {this._value = obj;}registerOnChange(fn: any): void {this.onChangeCallback = fn;}registerOnTouched(fn: any): void {this.onTouchedCallback = fn;}设置禁用状态?(isDisabled: boolean): void {}

我正在使用响应式表单绑定到自定义输入组件,例如:

<my-editor [formControlName]="'myValue'"></my-editor>

divmy-editor 元素都应用了 ng-invalid 类,但我找不到一种优雅的方法将该类应用于 input 元素.

这是显示问题的 Stackblitz.https://stackblitz.com/edit/angular-child-ng-invalid

解决方案

我已经通过使用NgControl"的以下实现解决了您的问题,使用这种方法您将使您的自定义输入模块化,可以在需要时使用,如果我能提供进一步帮助,请发表评论:https://stackblitz.com/edit/angular-sdrrbj?file=src%2Fapp%2Fapp.component.ts

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

解决方案

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

这篇关于Angular 子组件 ng-invalid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆