2017-12-11 18 views
0

目的:カスタムドロップダウンは、バインドするアイテムソースとして任意のデータを受け入れる必要があります。 オブジェクトのプロパティに基づいて、 の値を*ngForに設定しようとしています。もしitemsourceが文字列の配列ならば、私はちょうど*ngFor="let item in itemSource"と言うことができます。今、itemSourceが*ngFor=let item in itemSourceを変更せずにプロパティを持つオブジェクトである場合、どうすれば実現できますか?コンポーネントコードでlet item in itemSourceの項目値を変更することはできますか?ここで角度(5):カスタムドロップダウンコンポーネント

<select class="form-control" name="test1" [(ngModel)]="model" (change)="onModelChange($event.target.value)"> 
        <option value="">Select state</option> 
        <option *ngFor="let item of itemSource" 
        [ngValue]="item.id" >{{item}}</option> 
       </select> 

がplunkである:あなたのコンポーネントでhttps://plnkr.co/edit/xFvvJ559idGxQMhDD6Ya?p=preview

答えて

0

、私はあなたがあなたのドロップダウンリストの右側に表示さ@input()プロパティを持っていると仮定しますか?その仮定から 、のは、この例を見てみましょう:

@Input() initialItemSource; 
itemSource; 

ngOnInit(){ 
    if(this.initialItemSource){ 
     if(typeof this.initialItemSource === 'object' && typeof this.initialItemSource.length === "number"){ 
     let obj:any = {}; 
     this.initialItemSource.forEach((el,index) =>{ 
      obj[index] = el;    
     }); 
     this.itemSource = obj; //Now itemSource is an object; 
     }else if(typeof this.initialItemSource === 'object'){ 
      this.itemSource = this.initialItemSource; 
     } 
    } 
} 

は今、私はitem.idを取り除き、itemSourceに置き換えテンプレート

<select class="form-control" *ngIf="itemSource" name="test1" 
     [(ngModel)]="model" (change)="onModelChange($event.target.value)"> 
     <option value="">Select state</option> 
     <option *ngFor="let item of itemSource" 
     [ngValue]="item" >itemSource[item]</option> 
</select> 

お知らせ[アイテム]からあなたitemSourceを消費する必要がありますプロパティIDは常に存在するとは限りません。

基本的に、カスタムコンポーネントには操作するプロパティが必要です。オブジェクトの場合は、プロパティがIDであるプロパティの値を表示します。 配列の場合、オブジェクトに変換し、インデックスがids(ngValue)の値をリストします

関連する問題