Imagine I have a small form and use reactive approach For example, I have two inputs
...
<input formControlName="name" name="name" type="text" class="form-control">
<input formControlName="amount" name="amount" type="text" class="form-control">
...
I want to track changes and add bootstrap classes 'is-valid'/ 'is-invalid' for appropriate cases. The problem is that the only way I see I can do it is this:
<input formControlName="name" name="name" type="text" class="form-control"
[ngClass]="name.invalid && name.touched ? 'is-invalid' : ''">
In ts file:
ngOnInit() {
...
this.name = this.shoppingListForm.get('name');
}
Is there a better approach. What is really annoying for me is a lot of "mud" in html.
So, if form should has default style, it means the page was loaded and input wasn't touched
I found out that I can do this, but still guess there is a better approach. By "better" I mean that won't make html so dirty
<input formControlName="name" name="name" type="text" class="form-control"
[ngClass]="{'is-invalid': name.invalid && name.touched,
'is-valid': name.valid, '': name.untouched}"
Any help is appreciated)
As @Muhammed stated below, the best way to do what I need is to do it through css
Just small contribution of mine in case of bootstrap 4.
The problem is that it adds border shadow, so the complete solution for me is this: for invalid input
input.ng-invalid.ng-touched{
border-color: rgba(255,10,29,1) !important; box-shadow: none !important;
}
if it is focused, then make border look good
input.ng-invalid.ng-touched:focus{
box-shadow: 0 0 0 0.2rem rgba(255,10,29,0.25) !important;
}
You don't need to add the any class related to form control state change angular do this by default you just need to add a style related to these classes
input.ng-invalid.ng-touched {
border: 1px solid red;
}
this class indicate the input control is invalid and toched , this mean you just need to work on the style.
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