Using Data-binding with Angular 2 to disable a button

I received a question from a customer new to AngularJS asking for the right way to disable a button until at least one checkbox was checked. The customer’s first thought was to recognize an event on the checkbox and react to it, but this is not necessary with the data-binding feature of Angular.

You can use 2-way data-binding on the checkbox to a Boolean property on the component. So, as soon as the user modifies the checkbox, the change is reflected in the component. Also, use 1-way data-binding on the disabled property of the button to a method on the component that returns the condition you want to test. In this case the method returns true if any items have been selected.

Component Template

<table class="table"> <thead> <tr> <th>Select</th> <th>Name</th> </tr> </thead> <tbody> <tr *ngFor="let item of items"> <td><input type="checkbox" [(ngModel)]="item.chosen"></td> <td>{{item.name}}</td> </tr> </tbody> </table> <button [disabled]="noneSelected()">OK</button>

Component Class

import {Component} from '@angular/core' @Component({ selector: 'my-test', templateUrl: 'app/home/test.component.html' }) export class TestComponent { items = [ { name: 'Fred', chosen: false }, { name: 'Barney', chosen: false }, { name: 'Dino', chosen: false } ]; noneSelected() { return !this.items.some(item => item.chosen); } }

Note: This code has been tested with RC6 of Angular 2.