Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Create Dynamic Row With Custom MultiSelect Dropdown In Angular 8

0.00/5 (No votes)
2 Jan 2020 1  
In this tip, you will learn how to create dynamic Row with Custom MultiSelect Dropdowns in Angular 8.

Introduction

In this tip, we will learn how to create dynamic row and custom multiselect dropdowns using Angular 8.

Angular multiselect dropdown component for web applications is easy to integrate and use. It can bind to any custom data source.

How Will It Work?

Multi dropdown checkbox is already available in Angular, called ng-multiselect-dropdown, but here we are not using that. We are creating our own, plus we will give the functionality to select only two values in a checkbox. This means, when we try to select more than two values, it will remove the first value and a select third.

Prerequisites

  • Basic knowledge of Angular
  • Visual Studio Code must be installed
  • Angular CLI must be installed
  • Node JS must be installed

Using the Code

Step 1

Let us create an Angular project, using the following npm command:

ng new multiSelectCheckbox

Step 2

Open the newly created project in Visual Studio code and install bootstrap in this project.

Now, open styles.css file and add Bootstrap file reference. To add reference in styles.css file, add this line:

npm install bootstrap --save

Step 3

Now, let's create a new component, by using the following command:

ng g c home

Step 4

Now create a new class, to create class, use the following command:

ng generate class blankRow

Now, open the class and add the following code:

export class BlankRow {
        RollNo:number;
        Name:string;
        Medium:any;
        Class:any;
        Section:any;
        Books:any=[];
        SelectedBooks:any=[];
        Subject=[];
        SelectedSubject=[];
        }

Step 5

Now, open home component.ts file and add the following code in this file:

import { Component,OnInit } from '@angular/core';  
import { BlankRow } from '../models/blankRow';  

@Component({  
    selector: 'app-home',  
    templateUrl: './home.component.html',  
    styleUrls: ['./home.component.css']  
})  
export class HomeComponent implements OnInit {  
    blankRowArray: Array < BlankRow > = [];  
    blankRowData = new BlankRow();  
    hideMultiSelectDropdownAll: boolean[] = [];  
    hideMultiSelectDropdown: boolean[] = [];  
    hideMultiSelectedSubjectDropdown: boolean[] = [];  
    hideMultiSelectedSubjectDropdownAll: boolean[] = [];  
    tempData = [];  
    savedSubjects = [];  
    Books = [];  
    Subject = [];  

    constructor() {}  

    ngOnInit() {  
        this.Subject = [{  
            value: "English",  
            IsChecked: false  
        }, {  
            value: "History",  
            IsChecked: false  
        }, {  
            value: "Geography",  
            IsChecked: false  
        }, {  
            value: "Hindi",  
            IsChecked: false  
        }, {  
            value: "Marathi",  
            IsChecked: false  
        }, {  
            value: "Civics",  
            IsChecked: false  
        }, {  
            value: "Science",  
            IsChecked: false  
        }, {  
            value: "Mathematics",  
            IsChecked: false  
        }];  
        this.Books = [{  
            value: "CBSE Class 10 English Literature Reader Book",  
            IsChecked: false  
        }, {  
            value: "CBSE Class 10 English Book",  
            IsChecked: false  
        }, {  
            value: "CBSE Class 10th Maths Book",  
            IsChecked: false  
        }, {  
            value: "CBSE Class 10th Hindi Book",  
            IsChecked: false  
        }, {  
            value: "CBSE Class 10 Science Book",  
            IsChecked: false  
        }, {  
            value: "Class 10 CBSE Geography Book",  
            IsChecked: false  
        }, {  
            value: "Class 10th Economics Book",  
            IsChecked: false  
        }, {  
            value: "CBSE Class 10 Sanskrit Book",  
            IsChecked: false  
        }];  
    }  
    addBlankRow() {  
        const blankRowData = new BlankRow();  
            blankRowData.RollNo = 0,  
            blankRowData.Name = '',  
            blankRowData.Medium = 0,  
            blankRowData.Class = 0,  
            blankRowData.Section = 0,  
            blankRowData.Books = [],  
            blankRowData.Subject = [],  
            blankRowData.SelectedSubject = [{  
                IsChecked: false  
            }, {  
                IsChecked: false  
            }, {  
                IsChecked: false  
            }, {  
                IsChecked: false  
            }, {  
                IsChecked: false  
            }, {  
                IsChecked: false  
            }, {  
                IsChecked: false  
            }, {  
                IsChecked: false  
            }],  
            blankRowData.SelectedBooks = [{  
                IsChecked: false  
            }, {  
                IsChecked: false  
            }, {  
                IsChecked: false  
            }, {  
                IsChecked: false  
            }, {  
                IsChecked: false  
            }, {  
                IsChecked: false  
            }, {  
                IsChecked: false  
            }, {  
                IsChecked: false  
            }],  
            this.blankRowArray.push(blankRowData)  
    }  
    openMultiSelectDD(i) {  
        for (var x = 0; x < this.blankRowArray.length; x++) {  
            this.hideMultiSelectDropdownAll[x] = false;  
            this.hideMultiSelectedSubjectDropdownAll[x] = false;  
            this.hideMultiSelectedSubjectDropdown[x] = false;  
        }  
        this.hideMultiSelectDropdownAll[i] = true;  
        this.hideMultiSelectDropdown[i] = !this.hideMultiSelectDropdown[i];  
    }  
    openMultiSelectDDForSubject(i) {  
        for (var x = 0; x < this.blankRowArray.length; x++) {  
            this.hideMultiSelectedSubjectDropdownAll[x] = false;  
            this.hideMultiSelectDropdownAll[x] = false;  
            this.hideMultiSelectDropdown[x] = false;  
        }  
        this.hideMultiSelectedSubjectDropdownAll[i] = true;  
        this.hideMultiSelectedSubjectDropdown[i] = !this.hideMultiSelectedSubjectDropdown[i];  
    }  
    //MultiSelect DropDown For Books    
    booksChecked(list: any, i, x, isChecked: boolean) {  
        let selectedBooks = list.value;  
        if (isChecked) {  
            this.blankRowArray[i].Books.push(selectedBooks);  
            this.blankRowArray[i].SelectedBooks[x].IsChecked = true;  
        } else {  
            this.blankRowArray[i].Books = 
                 this.blankRowArray[i].Books.filter(obj => obj !== selectedBooks);  
            this.blankRowArray[i].SelectedBooks[x].IsChecked = false;  
        }  
    }  

    //On Subject Checked    
    onSubjectChecked(list: any, i, x, isChecked: boolean) {  
        let selectedSubject = list.value;  
        if (this.blankRowArray[i].Subject.length < 2) {  
            if (isChecked) {  
                if (this.blankRowArray[i].Subject.length == 0) {  
                    this.tempData = [];  
                }  
                if (this.tempData.length < 2) {  
                    this.tempData.push(x);  
                }  
                if (this.tempData.length == 2) {  
                    let saveSub = this.tempData.join(',');  
                    this.savedSubjects[i] = saveSub;  
                    console.log(this.savedSubjects[i]);  
                }  
                this.blankRowArray[i].Subject.push(selectedSubject);  
                this.blankRowArray[i].SelectedSubject[x].IsChecked = true;  
                this.Subject[x].IsChecked = true;  
            } else {  
                this.tempData.filter(obj => obj !== x);  
                this.blankRowArray[i].Subject = 
                     this.blankRowArray[i].Subject.filter(obj => obj !== selectedSubject)  
                this.blankRowArray[i].SelectedSubject[x].IsChecked = false;  
            }  
        } else {  
            if (isChecked) {  
                this.blankRowArray[i].Subject[0] = this.blankRowArray[i].Subject[1];  
                this.blankRowArray[i].SelectedSubject[x].IsChecked = true;  
                let saveSub0 = this.savedSubjects[i].split(',')[0] ? 
                               this.savedSubjects[i].split(',')[0] : this.tempData[0];  
                let saveSub1 = this.savedSubjects[i].split(',')[1] ? 
                               this.savedSubjects[i].split(',')[1] : this.tempData[1];  
                var temp = saveSub0;  
                this.tempData[0] = saveSub1;  
                this.tempData[1] = x;  
                this.blankRowArray[i].SelectedSubject[temp].IsChecked = false;  
                this.Subject[x].IsChecked = true;  
                this.blankRowArray[i].Subject[1] = selectedSubject;  
                this.savedSubjects[i] = this.tempData.join(',');  
            } else {  
                var temp = this.tempData.find(a => a == x);  
                this.tempData = [];  
                this.tempData[0] = temp;  
                this.blankRowArray[i].Subject = 
                     this.blankRowArray[i].Subject.filter(obj => obj !== selectedSubject)  
                this.blankRowArray[i].SelectedSubject[x].IsChecked = false;  
            }  
        }  
    }  
    deleteRow(index) {  
        this.blankRowArray.splice(index, 1);  
    }  
}  

deleteRow method is use to delete created row.

deleteRow(index) {    
   this.blankRowArray.splice(index, 1);    
 }
addBlankRow() {  
    const blankRowData = new BlankRow();  
    blankRowData.RollNo = 0,  
        blankRowData.Name = '',  
        blankRowData.Medium = 0,  
        blankRowData.Class = 0,  
        blankRowData.Section = 0,  
        blankRowData.Books = [],  
        blankRowData.Subject = [],  
        blankRowData.SelectedSubject = [{  
            IsChecked: false  
        }, {  
            IsChecked: false  
        }, {  
            IsChecked: false  
        }, {  
            IsChecked: false  
        }, {  
            IsChecked: false  
        }, {  
            IsChecked: false  
        }, {  
            IsChecked: false  
        }, {  
            IsChecked: false  
        }],  
        blankRowData.SelectedBooks = [{  
            IsChecked: false  
        }, {  
            IsChecked: false  
        }, {  
            IsChecked: false  
        }, {  
            IsChecked: false  
        }, {  
            IsChecked: false  
        }, {  
            IsChecked: false  
        }, {  
            IsChecked: false  
        }, {  
            IsChecked: false  
        }],  
        this.blankRowArray.push(blankRowData)  
}  

addBlankRow method is used to add a new blank row on the click of the Add new Row button.

openMultiSelectDD(i) {
    for (var x = 0; x < this.blankRowArray.length;x++) {
        this.hideMultiSelectDropdownAll[x] = false;  
        this.hideMultiSelectedSubjectDropdownAll[x] = false;  
        this.hideMultiSelectedSubjectDropdown[x] = false;  
    }
    this.hideMultiSelectDropdownAll[i] = true;  
    this.hideMultiSelectDropdown[i] = !this.hideMultiSelectDropdown[i];  
}

openMultiSelectDD method is used to open dropdowns (related to books) when it gets clicked. I used "for" loop here, to close all particular dropdowns and open only selected ones.

openMultiSelectDDForSubject(i) {  
    for (var x = 0; x < this.blankRowArray.length; x++) {  
        this.hideMultiSelectedSubjectDropdownAll[x] = false;  
        this.hideMultiSelectDropdownAll[x] = false;  
        this.hideMultiSelectDropdown[x] = false;  
    }  
    this.hideMultiSelectedSubjectDropdownAll[i] = true;  
    this.hideMultiSelectedSubjectDropdown[i] = !this.hideMultiSelectedSubjectDropdown[i];  
}  

openMultiSelectDDForSubject method is used to open dropdown (related to subject) when it gets clicked. I used "for" loop here to close all particular dropdowns and opened only the selected one.

//MultiSelect DropDown For Books    
booksChecked(list: any, i, x, isChecked: boolean) {  
    let selectedBooks = list.value;  
    if (isChecked) {  
        this.blankRowArray[i].Books.push(selectedBooks);  
        this.blankRowArray[i].SelectedBooks[x].IsChecked = true;  
    } else {  
        this.blankRowArray[i].Books = 
             this.blankRowArray[i].Books.filter(obj => obj !== selectedBooks);  
        this.blankRowArray[i].SelectedBooks[x].IsChecked = false;  
    }  
}  

In the above code, I have used some parameters, which I will explain one by one.

  • list: It stores the selected value from the checkbox.
  • i: It stores the current blank row index value.
  • x: It stores the current checkbox index value.
  • isChecked: It stores the boolean value of the checkbox (for checked 'true' and for unchecked 'false').

If Checked, then it will push into an array and assign SelectedBooks.Ischecked as true. It can check or uncheck all checkboxes:

//On Subject Checked    
onSubjectChecked(list: any, i, x, isChecked: boolean) {  
    let selectedSubject = list.value;  
    if (this.blankRowArray[i].Subject.length < 2) {  
        if (isChecked) {  
            if (this.blankRowArray[i].Subject.length == 0) {  
                this.tempData = [];  
            }  
            if (this.tempData.length < 2) {  
                this.tempData.push(x);  
            }  
            if (this.tempData.length == 2) {  
                let saveSub = this.tempData.join(',');  
                this.savedSubjects[i] = saveSub;  
                console.log(this.savedSubjects[i]);  
            }  
            this.blankRowArray[i].Subject.push(selectedSubject);  
            this.blankRowArray[i].SelectedSubject[x].IsChecked = true;  
            this.Subject[x].IsChecked = true;  
        } else {  
            this.tempData.filter(obj => obj !== x);  
            this.blankRowArray[i].Subject = 
                 this.blankRowArray[i].Subject.filter(obj => obj !== selectedSubject)  
            this.blankRowArray[i].SelectedSubject[x].IsChecked = false;  
        }  
    } else {  
        if (isChecked) {  
            this.blankRowArray[i].Subject[0] = this.blankRowArray[i].Subject[1];  
            this.blankRowArray[i].SelectedSubject[x].IsChecked = true;  
            let saveSub0 = this.savedSubjects[i].split(',')[0] ? 
                           this.savedSubjects[i].split(',')[0] : this.tempData[0];  
            let saveSub1 = this.savedSubjects[i].split(',')[1] ? 
                           this.savedSubjects[i].split(',')[1] : this.tempData[1];  
            var temp = saveSub0;  
            this.tempData[0] = saveSub1;  
            this.tempData[1] = x;  
            this.blankRowArray[i].SelectedSubject[temp].IsChecked = false;  
            this.Subject[x].IsChecked = true;  
            this.blankRowArray[i].Subject[1] = selectedSubject;  
            this.savedSubjects[i] = this.tempData.join(',');  
        } else {  
            var temp = this.tempData.find(a => a == x);  
            this.tempData = [];  
            this.tempData[0] = temp;  
            this.blankRowArray[i].Subject = 
                 this.blankRowArray[i].Subject.filter(obj => obj !== selectedSubject)  
            this.blankRowArray[i].SelectedSubject[x].IsChecked = false;  
        }  
    }  
}  

In this method, we can only check a maximum of two values. If we select a third value, then the first value is replaced with the third and so on.

Step 6

Now, open home.component.html file and add the following code in this file:

<div>     Add Blank Row  </div>

<p>  </p>

<div class="col-12 col-md-12">     
<div class="card">       
<div class="card-body">         
<div class="table-responsive cnstr-record">           
<table class="table table-bordered">
	<tbody>
		<tr>
			<td>                               </td>
			<th width="30">Roll No             </th>
			<th width="100">Student Name       </th>
			<th width="50">Medium              </th>
			<th width="70">Class               </th>
			<th width="50">Section             </th>
			<th width="80">Books               </th>
			<th width="60">Subject             </th>
			<th width="50">Delete Row          </th>
		</tr>
		<tr>
			<td>
			--Choose-- English Hindi Marathi
			--Choose-- Fifth Sixth Seventh Eight Ninth Tenth
			--Choose-- Section A Section B Section C Section D Section E 
			<div style="width:  329px !important">                     
			<div class="body">                       
			<div>                                      {{bookList.value}}
			<div style="width:  162px !important">                     
			<div class="body">                       
			<div>                                      {{subjectList.value}}
			</div>
			</div>
			</div>
			</div>
			</div>
			</div>
			</td>
			<td align="center">                   Delete Row
			<p> </p>

Step 7

Now, open home.component.css file and add the following code in this file.

<select>
.tooltip {  
    position: absolute;  
    z-index: 3000;  
    border: 1px solid #b7b086;  
    background-color: white;  
    color: #000!important;  
    padding: 5px 15px 5px 10px;  
    opacity: 1;  
    width: 350px;  
}  
</select>

Step 8

Now, open app.module.ts file and add the following code in this file:

<select>
import { BrowserModule } from '@angular/platform-browser';  
import { NgModule } from '@angular/core';  
import { FormsModule } from '@angular/forms';  
import { AppComponent } from './app.component';  
import { RouterModule } from '@angular/router';  
import { AppRoutingModule } from './app-routing.module';  
import { HomeComponent } from './home/home.component';  
@NgModule({  
  declarations: [  
    AppComponent,  
    HomeComponent,  
  ],  
  imports: [  
    BrowserModule,  
    RouterModule,  
    FormsModule,  
    AppRoutingModule  
  ],  
  providers: [  
  ],  
  bootstrap: [AppComponent]  
})  
export class AppModule { }  
</select>

Step 9

Now, run the project, by using 'npm start' or 'ng serve' command.

Create Dynamic Row With Custom MultiSelect Dropdowns In Angular 8

Click on Add Blank Row button and it creates a new row.

Create Dynamic Row With Custom MultiSelect Dropdowns In Angular 8

Step 10

Now, click on the subject textbox.

Create Dynamic Row With Custom MultiSelect Dropdowns In Angular 8

Step 11

Create Dynamic Row With Custom MultiSelect Dropdowns In Angular 8

Conclusion

In this article, I discussed how we can create dynamic rows and custom multiselect dropdowns in Angular 8 applications.

I am just a beginner and eager to learn new things not just related to technology, but in all aspects.

"Never stop learning, because life never stops teaching" .....by Gautam Buddha.

Please give your valuable feedback/comments/questions about this article. Please let me know if you liked and understood this article and how I could improve it.

History

  • 3rd January, 2020: Initial version

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here