Css 将类动态应用于角度自定义表单组件

Css 将类动态应用于角度自定义表单组件,css,angular,Css,Angular,我有一个自定义表单组件,我想动态地将类应用到它 import { Component, forwardRef, Injector } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; import { BaseInput } from './base-input'; @Component({ selector: 'app-text-control',

我有一个自定义表单组件,我想动态地将类应用到它

import { Component, forwardRef, Injector } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { BaseInput } from './base-input';

@Component({
  selector: 'app-text-control',
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => TextControlComponent),
    multi: true
  }],
  styles: [':host { display: inline-block }'],
  template: `
    <ng-container *ngIf="ctx.isEditing">    
    <input class="form-control"
    [value]="value"
    (change)="value=$event.target.value" (keyup)="value=$event.target.value" >
    </ng-container>
    <ng-container *ngIf="!ctx.isEditing">    
    {{value}}
    </ng-container>
  `
})
export class TextControlComponent extends BaseInput<string> implements ControlValueAccessor {
  constructor(injector: Injector) {
    super(injector);
  }
}
从'@angular/core'导入{Component,forwardRef,Injector};
从'@angular/forms'导入{ControlValueAccessor,NG_VALUE_ACCESSOR};
从“/base input”导入{BaseInput};
@组成部分({
选择器:“应用程序文本控件”,
供应商:[{
提供:NG_值访问器,
useExisting:forwardRef(()=>TextControlComponent),
多:真的
}],
样式:[':主机{显示:内联块}'],
模板:`
{{value}}
`
})
导出类TextControlComponent扩展BaseInput实现ControlValueAccessor{
建造师(注入器:注入器){
超级注射器;
}
}
问题是,当我将引导类应用于html中的组件时,容器将应用类,而不是子html元素

 <app-text-control formControlName="test" [ngClass]="{
        'is-valid' : test.valid && (test.dirty || test.touched)  ,
        'is-invalid' : test.invalid && (test.dirty || test.touched)  
      }" ></app-text-control>

类有效或无效,应用于应用程序文本控件容器html而不是内部输入控件。有没有办法将父html中设置的ng类传播到子html


我希望能够动态地将类附加到自定义组件中控件上的html,如果可能,最好使用ngClass指令。我是否必须编写一个自定义属性(例如[myNgClass]=…),才能在我的父自定义表单控件上工作?

不确定这是最好的方法,但您可以这样做:

<app-text-control formControlName="test" [isvalid]="test.valid && (test.dirty || test.touched)" [isinvalid]="test.invalid && (test.dirty || test.touched)" ></app-text-control>


在子组件中,您将拥有这些
isvalid
isinvalid
属性,您可以将它们与
ngClass

一起使用,这可能是我实现这一点的唯一方法,理想情况下,我不想为可能要在自定义表单控件中设置的额外类编写代码(对于我想要潜在添加的每个类,我都需要一个属性)但这是我目前为止最好的选择!!你也可以为类名设置一个属性,但是你需要在每次
测试对象更改时更新它…不是最佳的。有人知道是否可以动态评估父组件上设置的类,这也会满足此要求吗?