Angular 2 - 动态添加内联CSS [style.color]

时间:2017-03-21 21:25:20

标签: css angular

我有一个我循环的数组。我的对象包括颜色。 我想循环数组并使用内联CSS动态设置颜色。

我试过了:

[ngStyle]="{ 'color': 'item.value'}" 
[style.color]={{item.value}}
[style.color]="{{item.value}}"

如何设置颜色?

export class ColorSelectorComponent  {

    private color: string = "rgb(236,64,64)";
    private color2: string = "rgb(236,64,64)";
    private color3: string = "rgb(236,64,64)";
    private color4: string = "rgb(236,64,64)";
    private color5: string = "rgba(45,208,45,1)";
    private color6: string = "#1973c0";
    private color7: string = "#f200bd";

    private arrayColors: any = {};
    private selectedColor: string = 'color';

    constructor(private cpService: ColorPickerService) {

        console.log(this.arrayColors);
        this.arrayColors['color'] = '#2883e9';
        this.arrayColors['color2'] = '#e920e9';
        this.arrayColors['color3'] = 'rgb(255,245,0)';
        this.arrayColors['color4'] = 'rgb(236,64,64)';
        this.arrayColors['color5'] = 'rgba(45,208,45,1)';
    }

}

我的compontent HTML

<ul>
    <li *ngFor="let item of arrayColors | keys">           
        <div class="color-drop" [style.color]="{{item.value}}" ></div>
         Key: {{item.key}}, value: {{item.value}}
    </li>
</ul>

1 个答案:

答案 0 :(得分:0)

以下是3种方式

<p [style.color] = "result > 30 ? 'blue' : 'green'"> Hello Color World! </p>
<p bind-style.color = "result > 30 ? 'blue' : 'green'"> Hello Color World! </p>
<p style.color = "{{result > 30 ? 'blue' : 'green'}}"> Hello Color World! </p>  

http://www.concretepage.com/angular-2/angular-2-ngstyle-and-style-binding-example

上找到了它