Angular 9|8|7 How to Check All/ Uncheck All Checkbox List

In this post, we will discuss a very common functionality on checkboxes, select and unselect all checkboxes in Angular applications. We will create a project in the latest Angular 9 version and create a dummy item list to demonstrate this.

This tutorial is updated and compatible with all Angular versions including 6,7,8 and 9

Select/ Unselect Checkbox List Items in Angular 9

In the app.component.ts file, we will define an object of items using which we will create a list. This object will have an id, value and a boolean to check if the current item is selected or not.

Also, Read Angular Material 8/7 | Check/ Uncheck Checkbox List with Indeterminate state using MatCheckboxModule

Add Functions in Component

Now add some functions in the app.component.ts file

checkUncheckAll() : This method will traverse items object and change the boolean value of isSelected attribute. if we set isSelected to true checkbox will be checked same vice versa for false value

isAllSelected(): This method will check if any of the items is checked using Javascript’s every function. The every() method checks if all elements in an array pass a test (provided as a function).
getCheckedItemList(): This method is getting selected or checked items and pushing in a new object checkedList
After adding functions above our component will look as below

 

HTML Checkbox List

In the app.component.html file, add following HTML code looping over list object checklist sing *ngFor

Don’t forget to import the FormsModule in app.module.ts, as we are using [(ngModel)] directive for two way binding.

The app.module.ts file will look like this.

That’s it now run the application by hitting $ ng serve --open to see it working.

 

Leave a comment

Your email address will not be published. Required fields are marked *