When using Reactive Forms with Angular, how can I attach the validation classes (e.g. ng-invalid, ng-touched, etc) on a wrapper element. I've tried using formControlName
on the div, but it doesn't work due to an error because the div doesn't have a valueAccessor.
I need the validation classes to appear on an element other than the actual input that is tied to the Form Control. Is there a way to use formControlName or something similar to accomplish this?
I know how to do it by using ngClass, but that's a lot of clutter.
This way works, but I'm looking for a cleaner, succinct way to handle this:
<div class="validate-panel" [ngClass]="{
'ng-dirty': form.controls.field1.dirty,
'ng-pristine': form.controls.field1.pristine,
'ng-touched': form.controls.field1.touched,
'ng-untouched': form.controls.field1.untouched,
'ng-valid': form.controls.field1.valid,
'ng-invalid': form.controls.field1.invalid}">
<input formControlName="field1"/>
</div>
I want my markup to look more like this:
<div class="validation-panel" formControlName="field1">
<input formControlName="field1"/>
</div>
<div [ngClass]="{'validation-panel': myForm.get('field1').valid}">
? – Amit Chigadani[ngClass]
with or condition – Abhishek