0

I am very new to Angular and trying to learn. I am stuck here in form_validation. I am able to add a class when there is an error in that field but I am not getting if suppose there is no error then I need to add another class. This is what I have wrote

<input type="text" 
[class.is-invalid]="name.invalid && (name.dirty || name.touched) && name.errors.minlength" minlength="5" 
required 
name="name" 
#name="ngModel" 
[(ngModel)]="account.name" 
placeholder="Enter your Account name" 
class="form-control">

in the above code, i am able to add is-invalid class but in the else condition, I also want to add is-valid class. Any suggestions ?

1 Answer 1

2

You can have multiple [class.<css-class>] directives on a component, e.g.:

<div
[class.is-invalid]="..."
[class.is-valid]="..."
>
...
</div>

An alternative is using the [ngClass] directive:

<div
[ngClass]="condition ? 'is-invalid' : 'is-valid'"
>
...
</div>
Sign up to request clarification or add additional context in comments.

2 Comments

I have used like this [ngClass]="name.invalid && (name.dirty || name.touched) && name.errors.minlength ? 'is-invalid' : 'is-valid'" But the problem is by default is-valid class is added. Any solution for that ?
If name.invalid is false - which it is before the user changes the field - is-valid will be used. So your condition has 3 outcomes: untouched, valid, invalid. Note that you can also bind a method to [ngClass]: [ngClass]=getClass(). In getClass in your component you can then implement a more complex method that returns values for all 3 cases. Cheers

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.