0
votes

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>
1
Do you want something like this <div [ngClass]="{'validation-panel': myForm.get('field1').valid}"> ?Amit Chigadani
@JosephGabriel [ngClass] with or conditionAbhishek
see updates to question.Joseph Gabriel
You'll have to create your own directive that takes a control as input and sets what you want on the class. There isn't a built in feature for this.Reactgular

1 Answers

0
votes

you can use Angular Reactive form validation on div like

<div class="error" id="error" *ngIf="form.get('control-name').touched && !registerForm.get('control-name').valid">
                 <p>{{ registerForm.get('control-name').hasError('required') ? 'error msg' : ' '}}
                 </p>
</div>

you can get all ng-touched and ng-valid all in form.get('control-name') method and you can use it with *ngIf on div.

on component side you can build your form using formbuilder

 this.form = _formBuilder.group({
      'control-name': ['', Validators.compose([Validators.required, Validators.minLength(8)
    });

hope this helps