Angular 4 - Conditional CSS Classes

I am working on an Angular 4 application where we present a login to the user. Login may fail and we will return with an error: -

.subscribe(error => {
            this.error = error;
        });

      

This shows fine and we show the following: -

<div *ngIf="error">
   <p class="error-message">{{ error.ExceptionMessage }}</p>
</div>

      

Above is the standard input field for username and password with class. I would like to add a class to it error

without doing the following: -

<div *ngIf="error">
    <input type="email" class="form-control" />
</div>
<div *ngIf="!error">
    <input type="email" class="form-control error-field" />
</div>

      

Is there a better way than rendering the input twice, on each side of the if?

Thank!

+3


source to share


3 answers


You can do it using class binding:



<input type="email" class="form-control" [class.error-field]="error">

      

+6


source


Yes, it's better to use the attribute ngClass

like this:



<input type="email" [ngClass]="{'form-control': true, 'error-field': error}" />

      

+4


source


I believe you are looking for NgClass or NgStyle: https://angular.io/api/common/NgClass https://angular.io/api/common/NgStyle

+2


source







All Articles