12

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!

3 Answers 3

19

You can do this using the class binding:

<input type="email" class="form-control" [class.error-field]="error">
Sign up to request clarification or add additional context in comments.

Comments

13

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

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

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.