2017-04-04 32 views
0

我試圖將背景顏色綁定到選定標籤的當前項目。無法設置選擇標籤的當前項目的角度爲2的綁定背景顏色

我認爲它必須工作,因爲我真的將顏色參考對象分配給綁定到ngModel的currentColorDefinitin變量。

但它不起作用,爲什麼?

HTML

<select style="width:150px;" class="form-control" [(ngModel)]="currentColorDefinition"> 
    <option [style.background-color]="item.backgroundcolor" *ngFor="let item of colorDefinitions" [ngValue]="item"> 
    </option> 
</select> 

組件

colorDefinitions: Color[] = [ 
new Color("#000000", "#FFFFFF"), // black 
new Color("#FF0000", "#FFFFFF"), // yellow 
]; 
currentColorDefinition: Color; 
this.currentColorDefinition = this.colorDefinitions[0]; 
+0

是什麼選擇的? –

+0

這就是我的意思。所選顏色不可見。但是,當我打開/單擊下拉列表時,colorDefinitions數組綁定正確且可見。 – Pascal

+0

它顯示你設置爲選項的空值。 –

回答

0

這工作我用引導4.適合高興我設計的休息權,因爲這個下拉我還有一個按鈕,現在我可以換兩個按鈕一個按鈕組:-)

<div ngbDropdown> 
    <button [style.background-color]="currentColorDefinition.backgroundcolor" class="btn" id="dropdownMenu1" 
     ngbDropdownToggle>Farbe</button> 
    <div class="dropdown-menu" aria-labelledby="dropdownMenu1"> 
     <button style="height:20px;" name="colorer" (click)="setColor(item)" 
     class="dropdown-item" *ngFor="let item of colorDefinitions" [value]="item" [style.background-color]="item.backgroundcolor">{{item.foregroundcolor}}</button> 
    </div> 
</div> 
0

這似乎只能用原始值的工作:

型號:

export class Color { 
    first: string; 
    second: string; 

    constructor(f : string, s : string) { 
     this.first=f; 
     this.second =s; 
    } 
} 

HTML:

<select [(ngModel)]="currentColorDefinition.first"> 
    <option *ngFor="let item of colorDefinitions" 
      [selected]="currentColorDefinition.first == item.first ? true : null" 
      [value]="item.first" 
      [style.background-color]="item.first"> 
      {{item.first}} 
    </option> 
</select> 
+0

這很奇怪,因爲我之前和之後已經使用了帶有複雜對象的select-tag,所以currentItem可以工作! – Pascal

+0

你的代碼不起作用!選定的項目沒有顏色! – Pascal

+0

有一個錯誤。我已經用'[style.background-color] =「item.first」'替換了'[style.background-color] =「item.backgroundcolor」'。但你應該已經注意到該選項被選中了 –

相關問題