Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 353
Mike Upjohn Avatar asked Jul 12 '17 14:07

Mike Upjohn


People also ask

Can I use both class and ngClass?

You can use both class and ngClass as the first one gives you the opportunity to apply a class that you want to implement in all cases under any circumstances and the later to apply classes conditionally.

How do you add conditions to ngClass?

To add a conditional class in Angular we can pass an object to ngClass where key is the class name and value is condition i.e., true or false as shown below. And in the above code, class name will be added only when the condition is true.

What is the use of ngClass?

The ng-class Directive in AngularJS is used to specify the CSS classes on HTML elements. It is used to dynamically bind classes on an HTML element. The value for the ng-class has either string, an object, or an array. It must contain more than one class name, which is separated by space, in the case of a string.

What is the difference between ngClass and class?

ngClass is more powerful. It allows you to bind a string of classes, an array of strings, or an object like in your example. The above two lines of code is with respect to CSS class binding in Angular. There are basically 2-3 ways you can bind css class to angular components.


1 Answers

You can do this using the class binding:

<input type="email" class="form-control" [class.error-field]="error">
like image 103
Poul Kruijt Avatar answered Nov 09 '22 22:11

Poul Kruijt