Search This Blog

Thursday, September 10, 2020

Binding Y/N to Angular Checkbox

By default, Angular and Material checkboxes bind to boolean properties.


export class MyComponent {

    isActive:boolean = true

}

<input type="checkbox" [(ngModel)]="isActive"/>

 

<mat-checkbox [(ngModel)]="isActive">Check me</mat-checkbox>



But what if you have a string indicating a boolean state, especially if we are using databases not supported boolean. For example, we often use “Y”, “N” as boolean indicators in the database. Let’s explore a few ways of doing this.


Using Checked and Change Event Binding

We can separately bind the checked property and the change event for the checkbox.



export class MyComponent {

    strValue: String = "Y"

}


<input type="checkbox"

  [checked]="strValue === 'Y'" 

  (change)="strValue = $event.target.checked ? 'Y' : 'N'"/>


Using Property Accessor

Another approach is to define a new property in the component that simply maps the String or number values to boolean using property accessors.



export class MyComponent {

    isActive: number = 1

 

  get isActiveBool() {

    return this.isActive == 1

  }

 

  set isActiveBool(newValue:boolean) {

    this.isActive = newValue ? 1 : 0

  }

}

This will define a new property called isActiveBool which is just the isActive property converted to a boolean. Now you can bind this new property to a checkbox.


<input type="checkbox" [(ngModel)]="isActiveBool"/>

 

<mat-checkbox [(ngModel)]="isActiveBool">Check me</mat-checkbox>


I find this second approach cleaner. It also gives you a chance to do more complex mapping from any data type to boolean.