簡體   English   中英

Angular Typescript:從數組中添加動態 CSS 讀取

[英]Angular Typescript: Add Dynamic CSS reading from Array

如何動態添加從 Angular 數組讀取的 SCSS 樣式? 我們有一個帶有以下成員的角數組。

class ItemList{
    productName: string;
    highlight: boolean;
}

它包含成員{food, true}, {car, true}, {book, false}, {desk, true}, etc成員為true,需要一定的樣式。 數組中的所有成員,true 應創建以下內容。

社會保障:

.food{
background-color:blue
}

.car{
background-color:blue
}

.desk{
background-color:blue
}

考慮到這是您的組件 TS:

import { Component, VERSION } from '@angular/core';
import { Item } from './model';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular ' + VERSION.full;
  items: Array<Item> = [
    { productName: 'food', highlight: true},
    { productName: 'car', highlight: true},
    { productName: 'book', highlight: false},
    { productName: 'desk', highlight: true}
  ];
}

這是你的 CSS 文件:

.title {
  font-family: sans-serif;
}

.food {
  background-color:blue
}

.car {
  background-color:blue
}

.desk {
  background-color:blue
}

您可以使用ngClass來完成這項工作:

<ul>
  <li 
    *ngFor="let item of items"
    [ngClass]="item.highlight ? item.productName : ''">
    {{ item.productName }}
  </li>
</ul>

這是您的參考的工作示例代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM