2017-08-01 69 views
1

我正在使用material angular select component。當我點擊選擇器時,我可以看到圖標,但問題是當我選擇一個選項時,它只顯示值而不顯示圖標。如何在角度2/4材質設計選擇部件上添加圖像

在代碼重寫<md-option>去除<img>標籤並添加{{bodyStyle.viewValue}}

app.component.html

<div class="form-control form-control--center">     
<md-select [(ngModel)]="selectedBodystyle" floatPlaceholder="never" name="bodyStyle"> 
    <md-option *ngFor="let bodyStyle of bodyStyles" [value]="bodyStyle.value"> 
     <img src="{{bodyStyle.icon}}" alt="{{bodyStyle.viewValue}}"> 
      {{bodyStyle.viewValue}} 

    </md-option> 
</md-select> 
</div> 

app.component.ts此刻

selectedBodystyle: string; 
    bodyStyles = [ 
    { value: 'Mercedez' , viewValue: 'Mercedez', icon: "http://lorempixel.com/50/50/transport/" }, 
    { value: 'Ferrari' , viewValue: 'Ferrari' , icon: "http://lorempixel.com/50/50/transport/" }, 
    { value: 'BMW'  , viewValue: 'BMW'  , icon: "http://lorempixel.com/50/50/transport/" } 
    ]; 

更新

我試圖在viewValue屬性添加圖像像

{ value: 'Ferrari' , viewValue: '<img src="http://lorempixel.com/50/50/transport/" alt="Ferrari">Ferrari' } 

,但它加載以純文本格式的HTML它被選中後不顯示圖像

這是它選擇一個選項後顯示的內容,它刪除了圖片,它只顯示了viewValue的內容

enter image description here

+0

有一個開放的PR,這將簡化此爲您https://github.com/angular/material2/pull/3341。我不確定沒有組件工廠和一些詭計是可能的 –

+0

我一直在嘗試一些如何在中傳遞圖像,因爲這是它被選中的內容。您的鏈接..謝謝 –

回答

3

更新(顯示圖標旁邊的MD-菜單beta.8):

你可以把一個單獨的<img>標籤旁邊md-menu並從所選菜單項使用圖像src。請注意,爲此,value需要綁定整個對象,而不是對象屬性。

HTML:

<div class="form-control form-control--center"> 
<i *ngIf="selectedIcon"><img [src]="selectedIcon" alt="selectedIcon" style="margin-bottom: -15px"></i> 
<md-select [(ngModel)]="selectedBodystyle" 
      floatPlaceholder="never" 
      name="bodyStyle" 
      (change)="optionSelected($event)"> 
    <md-option *ngFor="let bodyStyle of bodyStyles" [value]="bodyStyle"> 
     <img [src]="bodyStyle.icon" [alt]="bodyStyle.viewValue"> 
      {{bodyStyle.viewValue}} 
    </md-option> 
</md-select> 
</div> 

TS:

export class SelectFormExample { 
    selectedBodystyle: string; 
    selectedIcon; 
    bodyStyles = [ 
    { value: 'Mercedez' , viewValue: 'Mercedez', icon: "http://lorempixel.com/40/40/transport/" }, 
    { value: 'Ferrari' , viewValue: 'Ferrari' , icon: "http://lorempixel.com/30/30/transport/" }, 
    { value: 'BMW'  , viewValue: 'BMW'  , icon: "http://lorempixel.com/50/50/transport/" } 
    ]; 

    optionSelected(event){ 
    // console.log(event.value.icon); 
    this.selectedIcon = event.value.icon; 
    } 
} 

Plunker demo

原文:

使用[src]="bodyStyle.icon"代替src="{{bodyStyle.icon}}"

我建議你也是這樣做的,也是alt="{{bodyStyle.viewValue}}"。更改爲[alt]="bodyStyle.viewValue"

+1

我的代碼完全像你的闖入者一樣...我需要的是在被選中後顯示圖標 –

+1

哦,有點困難。我會努力... – Nehal

+1

我更新了這個問題,我嘗試了一些東西,但沒有工作 –

0

這是一個在黑暗中拍攝,但嘗試

<img [src]="bodyStyle.icon"... 
+0

我試過這個選項的問題是選擇一個選項後顯示的值而不是圖像 –

相關問題