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',
  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);
  }
}

问题是当我将 Bootstrap 类应用于 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>

class is-valid 或 is-invalid 应用于 app-text-control 容器 html 而不是内部输入控件。有没有办法将在父级中设置的 ng-class 类传播到子 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>

在子组件中,您将拥有这些 isvalidisinvalid 属性,您可以将它们与 ngClass 一起使用。

关于css - 动态地将类应用于 Angular 自定义表单组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51194861/

相关文章:

css - 当我激活我自己的插件时 wordpress 中的字体问题

javascript - Bootstrap 跳转到折叠面板内的链接

html - 文本已缩放,如何撤消?

javascript - Angular2 路由与 Express 路由结合使用?

angular - "Expression has changed after it was checked"当子组件在 ngOnInit 上发出时

html - 全屏居中 html5 视频直播

javascript - 如何使用较少混合的图像路径变量

angular - Web服务调用未返回Angular 5 Http错误

angular - '$ 未定义' | Angular 6 中的服务器端渲染

javascript - 为什么我在接口(interface)和可观察对象方面遇到错误?