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 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.
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.
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.
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.
You can do this using the class binding:
<input type="email" class="form-control" [class.error-field]="error">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With