How to make a multi-select dropdown using Angular 11/10 ?
In this article, we will learn to build the multiple selection drop-down menu in Angular. To accomplish this task, we require Angular 10 or the Angular 11 version. Sometimes we need to display dynamically fetched multi-selected data in a drop-down menu, for this, we will use the npm @ng-select/ng-select package as a multi-select drop-down menu. The package is used to provide a set method that gives an option for a drop-down menu & also provides the change events to fetch the value of the selected option. To build a multiple-select drop-down menu using Angular, we will follow the below steps in sequence.
<ng-select [items]="item-name" bindLabel="name" placeholder="Select item" appendTo="body" [multiple]="true" [(ngModel)]="selected"> </ng-select>
Prerequisites: NPM must be preinstalled.
npm install -g @angular/cli
Create a new Angular project
ng new <project-name>
Check the installation by running the project. You should see the angular landing page on http://localhost:4200/
ng serve -o
Project Structure: After completing the above steps, our project structure will look like the following image:
Creating drop-down multi-select:
Create a new application. We will use the below command to create a new application.
ng new geeksforgeeks-multiSelect
Install @ngselect npm package. In order to use the drop-down menu, we will follow the below command to install the @ngselect package from the npm.
npm install --save @ng-select/ng-select
Example: Import NgSelectModule and FormsModule inside the app.module.ts file. Here, in order to use ngSelect in the application. we need to import NgSelectModule and FormsModule in the app.module.ts file.
Import CSS file: We need to import a CSS of NgSelectModule. We will use a default.theme.css which is in ng-select/themes folder. This will provide us with a multi-select drop-down design. We will use this import CSS file inside the style.css.
Rendering the content: Here, we will update our layout or view file to render our content. Here, we are using the app.component.html file for updating or viewing our content like this:
Run the application: In this step, we are ready to run the application. A similar output can be seen as shown below.