Reputation: 1297
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!
Upvotes: 12
Views: 15381
Reputation: 71891
You can do this using the class binding:
<input type="email" class="form-control" [class.error-field]="error">
Upvotes: 19
Reputation: 1678
yeah there's a better way using ngClass
attribute like this:
<input type="email" [ngClass]="{'form-control': true, 'error-field': error}" />
Upvotes: 13
Reputation: 31
I believe you are looking for NgClass or NgStyle: https://angular.io/api/common/NgClass https://angular.io/api/common/NgStyle
Upvotes: 2