1

I'm wanting to apply a conditional class to an element on the page.

Currently it's working with the following code:

ng-class="{ 'vfnz-form--error' : loginForm.username.$invalid  }

This applies a invalid class if the input field is invalid. I'm wanting to apply a "valid" class when the user input field is valid.

Is this possible to achieve in the same line of code?

Here is a fiddle example: JSFIDDLE

1 Answer 1

5

You could just do it in many ways, one simple way would be to use an object with bracket notation.

Example:-

ng-class="{ true: 'vfnz-form--error', false : 'vfnz-form--good'  }[loginForm.username.$invalid]"

Or (since it cannot be both invalid and valid):-

ng-class="{'vfnz-form--error' : loginForm.username.$invalid, 'vfnz-form--good' : loginForm.username.$valid}"

And if you want to do it only if form is dirty you could yes add condition to check for $pristine/$dirty but you could also make use of the class angular adds on the inputs (and on the form as well) i.e ng-pristine/ng-dirty so you could define the rule with these class names to make it more specific.

ex:-

.vfnz-form--error .ng-dirty.something{/*apply bad rules*/} 
Sign up to request clarification or add additional context in comments.

6 Comments

This is close to what I want, the only thing is the field onload is set to invalid without a user inputting a value. Does this need to check for $pristine?
Yes, you could check for $dirty, basically you could have your css rule itself define that.
Can I do this by adding && !loginForm.username.$dirty ?
This is correct: { 'vfnz-form--error' : loginForm.username.$invalid && !loginForm.username.$pristine, 'vfnz-form--valid' : loginForm.username.$valid }
Yes it should be, Actually i am not able to open your fiddle. :( Infact what i am saying is angular adds a class ng-dirty to the input you can actually have your css rules written accordingly instead of adding one more condition in ng-class. i.e .vfnz-form--error .ng-dirty.something{/*apply bad rules*/}
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.