Ashish Chauhan
Ashish Chauhan

Reputation: 536

Enabling/Disabling checkbox field with Angular2

I am dynamically rendering the checkbox and combobox fields and performing following functionality:

  1. based on the API response, if the checkbox field appears as selected then combobox appears as enable else it would be disable.
  2. If user select checkbox field then combo box should be enable else disabled

The combo box fields works work for the first case but not working in the second case. The state (enable or disable) cannot changes later on.

Here is my template snippet:

 < tr *ngFor="let widgetAttribute of _preferencesWidget">

 < td *ngFor="let subattribute of widgetAttribute.methods">

 < select *ngIf="subattribute.name == 'Email' && subattribute.type == 'LIST'" id="{{subattribute.name}}Check" class="selectpicker" data-max-options="1" (change)="validateCombo($event)"
                                                            [disabled]="!subattribute.enabled">
                                                                <option *ngFor="let subValue of subattribute.values" value="{{subValue.code}}" [selected]="subValue.code == subattribute.selected">{{subValue.description}}< /option>
                                                            < /select>
 < /td>
< /tr>

The generated id for checkbox is : InformationCheck and for combobox is : pensionMCheck

My component logic is:

 public validateCombo() {

     if (this.pensionCheck) {
         $('#pensionMCheck').prop('disabled', false);
         if ($('#pensionMCheck').val() === 'Y') {
             this.pensionMCheck = true;
         } else {
             this.pensionMCheck = false;
         }
    } else {
         this.pensionMCheck = false;
         $('#pensionMCheck').val('N');
         $('#pensionMCheck').prop('disabled', true);
         $('#pensionMCheck').prop('selectedIndex', 0);
    }

Upvotes: 1

Views: 2446

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657741

Bind the checkbox status to a property (isChecked) and bind enabled of <select> to the same property:

<input type="checkbox" [(ngModel)]="isChecked">
<select [(ngModel)]="selectedItem" [enabled]="!isChecked"

Upvotes: 1

Related Questions