nickornotto
nickornotto

Reputation: 2156

How to disable element / change styling upon another field change in Angular

I have 2 fields:

<input type="text" name="quantity" #quantity="ngModel" [(ngModel)]="orderProduct.selectedProduct.quantity" required min="1" max="50">

and a checkbox

<label class="checkbox">
    <input type="checkbox" name="orderProduct.selectedProduct.Option" value="{{option.Value}}" [(ngModel)]="option.checked" /> <!-- disable checkbox -->
    <span class="checkmark"></span> <!-- change css style to this element -->
</label>

How can I disable/ enable the checkbox and change the styling to checkmark element if a user inputs the incorrect/ correct range of values (between min and max) in the quantity field?

I'm new to angular and struggling to find solution. I'm using Angular 5.

Upvotes: 1

Views: 281

Answers (1)

Niladri Basu
Niladri Basu

Reputation: 10624

There's disabled property in <input>. So, in disabled you can check the validity of your <input type="text" name="quantity" .. by using quantity.invalid like this:

<label class="checkbox">
    <input type="checkbox" name="orderProduct.selectedProduct.Option" value="{{option.Value}}" [(ngModel)]="option.checked" disabled="quantity.invalid"/> <!-- disable checkbox -->
    <span class="checkmark"></span> <!-- change css style to this element -->
</label>                      

There's two option to check the validity (If you don't want to use reactive forms):

  1. Pass custom validator to the <input>. Read more about it here and here.
  2. Use ngModelChange within <input> like <input (ngModelChange)="isInputValid($event)" name="quantity" .. and in your .ts file write this method to update a boolean (say isquantityValid) based on the validity of your input. Then use that variable to enable\disable the checkbox. Read More

To change the style conditionally do something like this:

<span [ngClass]="isquantityValid ? 'styleClass1' : 'styleClass2'">content</span>

Upvotes: 1

Related Questions