Angular 7/6 | Parent Child Checkbox List Structure with Expand Collapse

In this post we will discuss on How to Create a Checkbox List having parents and child structure, using single data object.

What we will do here?

– Create a list with parents and children each having a checkbox.
– Parents having controls to expand/ collapse respective children.
– Expand/ Collapse All control on top of the list.
– Select/ Unselect All control on top of the list.

Let’s begin with a new Angular Project.

If you don’t have node.js (and npm) installed on your system, you can download it here.

Make sure you have the latest version of Angular installed

Create a new project

Add FormsModule in Application Module

First, we will import FormsModule in app.module.ts, as this module is required for ngModel.

 

Add Methods and Define Objects in AppComponent

In app.component.ts, we will define some variables and an object to create a list.

Here we have used a single data variable of type any. In data, we have defined other attributes and List object as data.ParentChildchecklist. In this object, we have id of parents and its childList object is having its own id and parent attribute. This id relation will help in the checkbox and expand/collapse functionality. Other methods used already having inline comments to tell its function.

Show Checkbox List in View

Next, we need to add HTML in app.component.html, replace below code in the file.

Here we have two lists of parent their respective child list with corresponding checkboxes set to a boolean value given in ngModel.

Why we used (ngModelChange) instead of (click) listener on Input?

We need to use (ngModelChange) as (click) will not work as expected, when we use (click), it got fired and completed before a value of ngModel changes which is not expected behavior.

Pinch of CSS styles in app.component.scss

To make it look beautiful we have used bootstrap.css and some custom CSS in app.component.scss. For icons, we used FontAwsome library

Add this bootstrap.css and FontAwsome.css file in index.html

In app.component.scss replace following code:

After completing all the steps above Application will look like this

Let me know if yo fae any issue somewhere in implementing this.

Happy coding 🙂

Thanks for visiting :) Let me know if you have some suggestions or feedback for this post in the comment section. Looking for any tutorial or demo on FreakyJolly, just drop me a message here

Leave a Reply

avatar
  Subscribe  
Notify of