简体   繁体   中英

Angular 4 - Conditional CSS Classes

I'm working on an Angular 4 app, where we present the user with a login. The login may fail, and on return, we listen for the error:-

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

This shows fine and we show this:-

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

Above this is a standard input field for username and password with a class. I wanted to be able to add an error class to this 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?

Thanks!

You can do this using the class binding:

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

yeah there's a better way using ngClass attribute like this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM