1

我在citylist组件模板中有一个下拉列表。

<select [(ngModel)]="selectedCity.id">
 <option *ngFor="let cty of cityarray" [ngValue]= "cty.id"> 
    {{cty.name}}
 </option>
</select>
<p> </p> <!--selected city name -->

城市的数组是这样的:

cityarray = [new Cities(1,'Berlin'),
          new Cities(2,'London'),
          new Cities(3,'Portland'),
          new Cities(4,'Zurich'),
          new Cities(5,'Cardiff') ]

其中 Cities 类对象有一个id和一个name

我想要的是简单地打印从 para 标签内的下拉列表中选择的城市。如果可能,如何使用ngModel来完成?还是我必须编写模型更改事件?

4

2 回答 2

1

您可以连接 ngModelChange 事件,如下所示:

<select [(ngModel)]="selectedCity.id" (ngModelChange)="setCity($event)">
   <option *ngFor="let cty of cityarray" [ngValue]= "cty.id"> 
    {{cty.name}}
   </option>
</select>
<p>{{selectedCity}} </p>

零件

selectedCity:any;
setCity($event){
 this.selectedCity = this.cityarray.filter(c => return c.id == $event)[0].name;
}

希望能帮助到你!!

于 2017-06-10T08:00:25.123 回答
0

这样做的奇怪方法是:

<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>
于 2017-06-10T07:53:27.227 回答