我有一个自定义表单组件,我想为其动态应用类。
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>
在子组件中,您将拥有这些 isvalid
和 isinvalid
属性,您可以将它们与 ngClass
一起使用。
关于css - 动态地将类应用于 Angular 自定义表单组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51194861/