I am currently working on a custom form component where I need to dynamically apply classes to it.
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);
}
}
The challenge arises when applying bootstrap classes to the component in the HTML as the container receives the classes instead of the child HTML element.
<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>
The situation is such that the class is-valid or is-invalid gets applied to the app-text-control container HTML rather than the inner input control. Is there a way to propagate the ng-class classes set in the parent to the child HTML?
I aim to be able to dynamically assign classes to the HTML within my custom component, preferably utilizing the ngClass directive if feasible. Does this require creating a custom attribute (e.g., [myNgClass]=....) for it to function correctly within my parent custom form control?