Reputation: 11
I have a drop down list in a citylist component template.
<select [(ngModel)]="selectedCity.id">
<option *ngFor="let cty of cityarray" [ngValue]= "cty.id">
{{cty.name}}
</option>
</select>
<p> </p> <!--selected city name -->
And the array of city is like this:
cityarray = [new Cities(1,'Berlin'),
new Cities(2,'London'),
new Cities(3,'Portland'),
new Cities(4,'Zurich'),
new Cities(5,'Cardiff') ]
where Cities class object has an id and a name.
What I want is to simply print the city selected from the drop down inside the para tags. If possible, How can this be done using ngModel? or do I have to write a model change event?
Upvotes: 1
Views: 1835
Reputation: 4294
You can hook up ngModelChange event like below:
<select [(ngModel)]="selectedCity.id" (ngModelChange)="setCity($event)">
<option *ngFor="let cty of cityarray" [ngValue]= "cty.id">
{{cty.name}}
</option>
</select>
<p>{{selectedCity}} </p>
component
selectedCity:any;
setCity($event){
this.selectedCity = this.cityarray.filter(c => return c.id == $event)[0].name;
}
Hope it helps!!
Upvotes: 1
Reputation: 58573
Odd way of doing this is :
<select [(ngModel)]="selectedCity.id">
<option *ngFor="let cty of cityarray" [ngValue]= "cty.id">
{{cty.name}}
</option>
</select>
<ng-container *ngFor="let cty of cityarray">
<p *ngIf='selectedCity.id === cty.id'>
{{cty.name}}
</p>
</ng-container>
Upvotes: 1