Angular Checkbox tutorials with latest examples


This tutorials explains about checkbox tutorials with examples for following

  • two way binding example
  • Dynamic Checkbox list
  • Get checkbox value in Angular
  • How to find checkbox is checked or not

prerequisite

First, Create an angular application1on using Angular cli - ng commands,

Once, Application is created, dependencies are installed, You can start import FormsModule

Import FormsModule and ReactiveFormsModule in Application Module, This modules are required to have input form binding works in Angular application.

import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { FormsModule, ReactiveFormsModule } from "@angular/forms";

import { AppComponent } from "./app.component";
import { HelloComponent } from "./hello.component";

@NgModule({
  imports: [BrowserModule, FormsModule, ReactiveFormsModule],
  declarations: [
    AppComponent,
    HelloComponent,
    
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

Angular checkbox two way binding example

Two way binding in Angular provides passing data from html to typescript component and vice verse.

This can be achieved with simple ngModel syntax - [()]

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

which is equivalent to property [] and event binding() syntax

<input [ngModel]="isAccepted"(isAcceptedChange)="isAccepted==$event"type="checkbox" 
name="isAccepted" />

In typescript component

@Input() ngModel;
@Output() isAcceptedChange = new EventEmitter();

Complete example html code:

<h3>
  Checkbox Basic Two way binding Example
</h3>
<div>
  <input [(ngModel)]="isAccepted" type="checkbox" name="isAccepted" />Is
  Accepted

  <h1>{{ isAccepted }}</h1>
  >
</div>

In Typescript component,

  • Declare property variable with type and optional default value.
import { Component, OnInit } from "@angular/core";

@Component({
  selector: "app-checkbox-component-basic",
  templateUrl: "./checkbox-component-basic.component.html",
  styleUrls: ["./checkbox-component-basic.component.css"]
})
export class CheckboxComponentBasicComponent implements OnInit {
  constructor() {}
  isAccepted = true;

  ngOnInit() {}
}

This is how two way binding works in Angular checkbox in input forms

Dynamic Checkbox list

This example explains about typescript has a json object which has list of values , and create a dynamic checkbox.

IN Typescript create a interface to hold the list of values.

export interface Role {
  id: number;
  name: string;
  checked?: boolean;
}

In the typescript component, Roles object is initialized with data. However this can be retrieved from database calling Http GET Service . This will not be covered here.

You can have Role object checked value with true or false to have checkbox checked by default. And also written getter- selectedCheckboxList which retrieves the user selected checkbox json object.

import { Component, OnInit } from "@angular/core";
import { Role } from "../role";

@Component({
  selector: "app-dynamic-checkbox-list",
  templateUrl: "./dynamic-checkbox-list.component.html",
  styleUrls: ["./dynamic-checkbox-list.component.css"]
})
export class DynamicCheckboxListComponent implements OnInit {
  public roles: Role[];

  constructor() {}

  ngOnInit() {
    this.roles = [
      {
        id: 1,
        name: "users",
        checked: true
      },
      {
        id: 2,
        name: "admin",
        checked: false
      },
      {
        id: 3,
        name: "support",
        checked: true
      },
      {
        id: 4,
        name: "manager",
        checked: false
      }
    ];
  }
   get selectedCheckboxList() {
    return this.roles.filter(item => item.checked);
  }
}

In Html template,

  • Iterate roles object using *ngFor loop
  • Added input checkbox with binding iterated checked property, which works two way binding
  • Added the label with object name value
  • Display the json object with selected list of checkbox values.
<h1>
  Dynamic Checkbox List Example
</h1>
<ul>
  <li *ngFor="let role of roles">
    <input type="checkbox" [(ngModel)]="role.checked" />
    <label>{{role.name}}</label>
  </li>
</ul>

And the select Object is

<pre>{{this.selectedCheckboxList | json}}</pre>

This way, how we bind dynamic checkbox from json object and get the selected checkbox list.

How to get checkbox value using change event handler?

Sometimes, we need to tracking the checkbox state changes.

Like a JavaScript event hander, Angular provides change event.

In Html template, Added (change) to input element with event handler - termsChange. This accepts $event parameter.

<input (change)="termsChange($event)" value="terms" type="checkbox" /> Terms

In Typescript component,

Provide the function with parameter of any type.

Selected checkbox value can get using target.checked property

  termsChange(selected: any): void {
 console.log(
      selected.target.name,
      selected.target.value,
      selected.target.checked
    );
      }

Inside a function, Retrieved checkbox name and value and checked or not This way, You can get the selected check box value in Angular and also called function while checkbox is checked

How can you know checkbox is checked or not? Inside a change call-back handler, write the following lines of code

if(selected.target.checked){
    //checked
    // own logic
}
else{
    // not checked
    // logic 
}

Stackblitz example

you can find this post complete code example at

Conclusion

This tutorials covered angular checkbox tutorails with ngmodal binding,dynamic list, retrieve value with examples

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.