How to use ngfor to make a dropdown in Angular from an array ?

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:


import { Component } from '@angular/core';

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 = "----"

	this.selected =

3. Now add the following code into dropdown.component.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">

<p>You selected {{selected}}</p>

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


ng serve -o

Similar Posts:

    None Found

Leave a Reply

Your email address will not be published. Required fields are marked *