html - 從陣列值更改 Css
我知道在 Angular 中你可以動態地給元素添加類,但我該如何更改屬性的值呢?我希望每個按鈕都是陣列中的下一個 spotColour。我覺得我的範例解釋得很好:
<button style="background-color: arrThemes[0]['spotColour']"></button>
<button style="background-color: arrThemes[1]['spotColour']"></button>
<button style="background-color: arrThemes[2]['spotColour']"></button>
arrThemes = [
{spotColour : 'rgb(238, 68, 136)', baseColour : 'rgb(80, 54, 78)'},
{spotColour : 'rgb(179, 165, 136)', baseColour : 'rgb(88, 67, 59)'},
{spotColour : 'rgb(87, 167, 82)', baseColour : 'rgb(47, 68, 46)'},
];
答案#1
試試像這樣的表達方式
<button style="{{ 'background-color: ' + arrThemes[0]['spotColour'] }}"></button>
或者更文明的方式使用 NgStyle
<button [ngStyle]="{'background-color': arrThemes[0]['spotColour']}"></button>
答案#2
使用 ngStyle 標籤來動態添加樣式
<button *ngFor="let item of arrThemes " [ngStyle]="{'background-color': item.spotColour }"></button>
