angular

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:

dropdown.component.ts:

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
}
}

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

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">
		{{player}}
	</option>
</select>

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

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

app.component.html:

<app-dropdown></app-dropdown>
ng serve -o

Similar Posts:

    None Found

Leave a Reply

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