Binding String and Number 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 string or integer numbers indicating a boolean state. For example, we often use “Y”, “N”, 1 and 0 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'"/>

For Material checkbox the $event variable has a different type. You need to directly access the checked property.

export class MyComponent {
    intValue: number = 1
}
<mat-checkbox 
  [checked]="intValue === 1" 
  (change)="intValue = $event.checked ? 1 : 0">Check me
</mat-checkbox>

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.

Advertisements

ReactJS from Scratch

ReactJS ships a tool called create-react-app that can generate a new project for you. This gets one started very quickly. But I see several problems with a generated project:

  1. The build process is heavily abstracted. Meaning, it hides how Webpack and Babel are used and configured.
  2. It launches a web server that uses Websocket to automatically refresh a web page when you modify any code.

These may sound like conveniences rather than problems. But neither will be acceptable in most real life projects. We need to be able to configure Webpack and Babel the we like. Also, most likely we will need to go through a regular web server like Nginx etc.

This is also inconvenient for someone who is new to ReactJS and Webpack. So many things are hidden away from you that you think you are not quite learning how the system operates.

In this article I will create a ReactJS project from scratch. We will use Webpack and Babel. We will learn how to configure them.

Continue reading

Module Loading in Angular 2

Typescript uses the ES6 import and export syntax to load modules. The syntax is quite easy to work with. But what happens at runtime is far from simple. Browsers do not fully support ES6 yet. Which means that these import and export statements need to be somehow transpiled into ES5. This is where things get complicated. In today’s post I will discuss how module loading works using three approaches:

  • Using SystemJS
  • Using Webpack
  • Using Webpack through Angular CLI

Continue reading

Form Validation Using AngularJS

A common use case for client side form validation is this:

  1. After the form is submitted, show all invalid input fields using a special color.
  2. If the form is invalid then do not take any action.

AngularJS documentation on form does a good job explaining how to highlight an invalid input field after it gains and loses keyboard focus. But it doesn’t show how to do that for all invalid input fields (irrespective of if it gained input focus) and only after the form is submitted.

Also, in many cases, you will be asked to highlight a div that surrounds an input field and not the input field itself. AngularJS applies styles like ng-invalid to the input field itself and hence will not meet that requirement.

Showing Error Highlight

First, we will write a controller method that will determine if error highlight should be shown for an input field. It will go something like this:

$scope.showError = function(inputName) {
  var form = $scope.myForm;

  return (form.$submitted || form[inputName].$touched) && 
    !form[inputName].$valid;
}

Basically it returns true if the field is invalid and only if the field lost focus or the form was submitted.

Create a style to highlight invalid input.

input.error {
      background: red;
}

In the HTML template use the class if error highlight should be shown.

<form name="myForm" novalidate>
  <input type="text" ng-model="user.name" name="uName" 
    ng-class="{error: showError('uName')}" required="" />
</form>

You can also show an error message if you like:

<input type="text" ng-model="user.name" name="uName" 
    ng-class="{error: showError('uName')}" required="" />
<br />
<div ng-show="showError('uName')">Tell us your name.</div>

Is the Form Valid?

To see if the form is completely valid use the $valid property of the form. It will be set to false if at least one input field in the form is invalid. An example form submit handler will look like this:

$scope.update = function() {
      console.log("Form submitted");
      if ($scope.myForm.$valid) {
        console.log("The form is valid.");
      } else {
        console.log("Form is invalid");
      }
};

See a working example in Plunker.