×

AngularJS Tutorial

AngularJs Questions

AngularJS Practice

How to Use ngfor to Make a Dropdown in Angular from an Array?

By IncludeHelp Last updated : September 11, 2024

In this article, we will discuss how to use ngFor in Angular to display array elements in a drop-down menu. It can be specifically useful when we want to show fetched data, such as "country names" or "states," in a drop-down menu.

What is *ngFor?

In Angular, the *ngFor is a structural directive that allows you to loop through a list or an array and render elements dynamically. It is used within Angular templates to repeat a block of HTML for each item in an array or list.

The syntax for *ngFor involves using the let keyword to declare a local variable representing each item in the iteration.

<tag_name *ngFor = "let item of array"></tag_name>

Using *ngFor loop

We will first cover the basic usage of the *ngFor loop in Angular. After that, we will proceed to more above topics:

Example

File: app.component.ts

import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
 numbers = [1, 2, 3, 4, 5];
}

File: app.component.html

<h1>Number Sequence</h1>
<ul *ngFor = "let n of numbers">
   {{n}}
</ul>

Output

The above program produces the following output:

Dropdown in Angular from an Array (1)

Dropdown Menu From an Array using *ngFor

In the following example, we will create an Angular program that generates a drop-down menu from an array using *ngFor:

Example

In this example, we will define an array named fruits in the TypeScript (.ts) file that contains the names of various fruits:

File: app.component.ts

import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
 fruits = [
   "Apple",
   "Banana",
   "Orange",
   "Grapes",
   "Kiwi",
   "Pear",
   "Mango"
 ]
}

In the following template file, we will define the <select> and <option> elements. Within the <option> element, we will use the *ngFor directive to loop through the array and bind each item to the value attribute. We will also use interpolation to display each item in the drop-down menu. Once you run the application and click on the drop-down field, the options will be displayed.

File: app.component.html

<h2>Drop-down menu</h2>
<p>Select fruit which you like more:</p>
<select>
   <option value="">Select...</option>
   <option *ngFor="let fruit of fruits" [value]="fruit">{{fruit}}</option>
</select>

Output

Following is the output of the above program:

Dropdown in Angular from an Array (2)

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.