This demo teaches purpose of ngModel and how to use ngModel with dropdown. ngModel is used to bind variable with HTML element. ngModel is two-way binding and used when user wants two-way data binding. Earlier we saw $event.target.value to get textbox value on keyup event of textbox. Here, you can get value of dropdown bound with variable and easily get value in TS file.
<!-- I've used $event.target.value because I have to pass same element value to same elemet change event -->
<!-- If my event element is different, I've to use ngModel -->
States: <br>
<select (change)="populateCity($event.target.value)" [(ngModel)]="selectedState" >
<option value="">Select State</option>
<option *ngFor="let s of State" [value]="s.id">{{s.name}}</option>
</select>
<br>
<br>
City: <br>
<select [(ngModel)]="selectedCity">
<option value="">Select City</option>
<option *ngFor="let c of dropdownCity" [value]="c.id">{{c.name}}</option>
</select>
<hr>
Selected State : {{selectedState}}<br>
Selected City : {{selectedCity}}
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
State: any = [
{ id: 1, name: "Gujarat" },
{ id: 2, name: "Maharastra" },
{ id: 3, name: "Rajasthan" }
]
City: any = [
{ id: 1, name: "Ahmedabad", state: 1 },
{ id: 2, name: "Rajkot", state: 1 },
{ id: 3, name: "Gandhinagar", state: 1 },
{ id: 4, name: "Mumbai", state: 2 },
{ id: 5, name: "Pune", state: 2 },
{ id: 6, name: "Udaipur", state: 3 },
{ id: 7, name: "Jaipur", state: 3 }
]
selectedState : any = "";
selectedCity : any = "";
//I've taken another Variable to bind city dropdown after filter. If I used same
// Variable, after second filter my city dropdown will not contains all values and
// Data will be null
dropdownCity: any = [];
populateCity(value) {
this.dropdownCity = this.City.filter(i => i.state == value);
}
}