Search code examples
cssangulartypescriptangular-forms

Angular - Apply custom css to invalid FormControl, not FormGroup?


I use the Angular docs css classes for representing valid/invalid input:

.ng-valid[required], .ng-valid.required  {
    border-left: 5px solid #42A948; /* green */
}

.ng-invalid:not(form)  {
    border-left: 5px solid #a94442; /* red */
}

But when I have nested FormControls (Inside FormGroups):

this.form = this.fb.group({
    ies_Cabecera: this.fb.group({
        cab_DatosEstablecimiento: this.fb.group({
            cab_NIFEs: this.nifEs = this.fb.control('', Validators.required)
        })
    })
});

And the cab_NIFEs is not valid, I get this unexpected behaviour:

enter image description here

The css is also applied to the FormGroup.

This is the html:

<form [formGroup]="form" class="form" (ngSubmit)="onSubmit()">
    <div formGroupName="ies_Cabecera">
        <div formGroupName="cab_DatosEstablecimiento"  class="clear">
            <h3>Datos</h3>
            <div class="col-xs-4">
                <label>NIF Establecimiento *</label>
                <input class="form-control" type="text" [formControl]="nifEs">
            </div>
        </div>
    </div>
</form>

How can I make the css be applied only to the invalid FormControl, not to the FormGroups?


Solution

  • Finally solved applying the following css:

    .form-control.ng-valid:not(form)  {
        border-left: 5px solid #42A948; /* green */
    }
    
    .form-control.ng-invalid:not(form)  {
        border-left: 5px solid #a94442; /* red */
    }
    

    This forces the element to be a FormControl to be css applied.