Search code examples
javascriptangulardata-bindingweb-component

How do I bind a checkbox to a select disabled property using ngx data binding?


I am building an angular 6 app and I would like to bind a show/hide logic of a select to a checkbox input. I am not sure where is my problem. I guess I would need an observable, but I wonder whether there is a way to do it directly (directly as without using a variable in my typescript code).

import { Component, Input } from '@angular/core';

@Component({
    selector: 'hello',
    template: `<label><input #bl id="checkBox" type="checkbox"> ere</label>
      <br/>
      <span>{{bl.checked}}</span>
      <br/>
      <select id="bl_select" class="select" *ngIf="(bl.checked)">
        <option value="0">All</option>
        <option value="1">Else</option>
      </select>`,
  styles: []
})
export class HelloComponent  {
}

You can find a MCVE on stackblitz.com.

Related to How do I bind a checkbox to a select disabled property using angular data binding? but with ngx.

This was a common use of data-binding back in my wpf days :)


Solution

  • This appears to do what you want (see this stackblitz):

    <input #bb type="checkbox" [(ngModel)]="bb.checked">
    <select class="select" [hidden]="!bb.checked">
    

    It also works with an ad hoc property added to the input element (e.g. showSelect). As long as data binding is set on the check box, the view will be updated (see this stackblitz).

    <input #bb type="checkbox" [(ngModel)]="bb.showSelect">
    <select class="select" [hidden]="!bb.checked">
    

    That being said, binding to a model defined in the component class is more in line with the Angular way of doing things:

    <input type="checkbox" [(ngModel)]="showSelect">
    <select class="select" [hidden]="!showSelect">
    
    export class HelloComponent {
      showSelect= false;
    }