2017-06-10 8 views
0

citylistコンポーネントテンプレートのドロップダウンリストがあります。角度2の選択したドロップダウンリストの値にテキストをバインド

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

、街の配列は、このようなものです:都市クラスのオブジェクトはIDを持って

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

私がしたいのは、ドロップダウンリストから選択した都市を単にパラのタグの中に印刷することです。 可能であれば、これはどのようにしてngModel?モデル変更イベントを作成する必要がありますか?これを行うための

+0

あなたは既に[(ngModel)] = "selectedCity"と[ngValue] = "cty"を試しましたか? –

+1

https://plnkr.co/edit/XyDaCjlthy8N0QNmE2NM?p=preview – yurzui

+0

Easy-peasy @yurzui!完璧なソリューション。あなたはまた、どのように '?'作品ですか? – sagarpat

答えて

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

あなたは以下のような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; 
} 

はそれが役に立てば幸い!

+0

ngModelChangeで正常に動作します。助けてくれてありがとう! – sagarpat

関連する問題