2017-04-04 33 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”'。但你应该已经注意到该选项被选中了 –

相关问题