Skip to content
Related Articles

Related Articles

How to use ngfor to make a dropdown in Angular from an array ?
  • Difficulty Level : Expert
  • Last Updated : 12 Mar, 2021

In this post, we will see how we can display the array elements in the drop-down menu using AngularJS. Sometimes we need to display dynamically fetched data and this is where features ngFor come into the scene. We can iterate over the array, apply conditions and display the data easily.

Using ngFor: NgFor is a built-in template directive that makes it easy to iterate over something like an array or an object and create a template for each item. 

Syntax:

<tag-name  *ngFor="let item of array">{{iter}}</tag-name>
<tag-name  *ngFor="let key of object">{{key}}</tag-name>

Prerequisites: NPM must be preinstalled.

Environment Setup:

  • Install angular :
npm install -g @angular/cli
  • Create a new Angular project:
ng new <project-name>
cd <project-name> 
  • Check the installation by running the project. You should see the angular landing page on http://localhost:4200/
ng serve -o

Creating drop down menu:

1. Create a new component:



ng g c dropdown

2. It will create a new directory with 4 new files. Open dropdown.component.ts and paste the following code:

dropdown.component.ts:

Javascript




import { Component } from '@angular/core';
  
@Component({
  selector: 'app-dropdown',
  templateUrl: './dropdown.component.html',
  styleUrls: ['./dropdown.component.css']
})
export class DropdownComponent {
  players = [
    "Sachin Tendulkar",
    "Ricky Ponting",
    "Virat Kohli",
    "Kumar Sangakkara",
    "Jacques Kallis",
    "Hashim Amla    ",
    "Mahela Jayawardene    ",
    "Brian Lara",
    "Rahul Dravid",
    "AB de Villiers"
  ]
  selected = "----"
  
  update(e){
    this.selected = e.target.value
  }
}

In above code, we have defined players array that contains the data that we will display in the drop down menu. Additionally we have a selected variable that we will use to display the selected element. The method update() takes an event and sets selected to its value.

3. Now add the following code into dropdown.component.html:

dropdown.component.html:

HTML




<h3>Choose Your Favorite Cricket Player</h3>
<select #cricket (change)="update($event)">
    <option value="default">----</option>
    <option *ngFor="let player of players" [value]="player">
        {{player}}
    </option>
</select>
  
<p>You selected {{selected}}</p>

We have created a drop-down menu that will use the players array. The options are populated using ngFor. The selected variable is used to display the selected option.

4. Finally add this component into app.component.html:

app.component.html:

HTML




<app-dropdown></app-dropdown>

5. Now run the project and open http://localhost:4200/ to see the results:

ng serve -o

Output

My Personal Notes arrow_drop_up
Recommended Articles
Page :