1

How do I dynamically add SCSS styles reading from an Angular array? We have an angular array with following members.

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

It contains members {food, true}, {car, true}, {book, false}, {desk, true}, etc Following members with true, need certain styling. All members in array, with true should create the following.

SCSS:

.food{
background-color:blue
}

.car{
background-color:blue
}

.desk{
background-color:blue
}
1
  • 1
    You can not "add" SCSS rules at runtime, because SCCS compiles to CSS on build time. Can you please explain use-case of your approach in more details? Commented Dec 10, 2019 at 1:10

1 Answer 1

1

Considering this is your Component 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}
  ];
}

This is your CSS File:

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

.food {
  background-color:blue
}

.car {
  background-color:blue
}

.desk {
  background-color:blue
}

You can use ngClass to make this work:

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

Here's a Working Sample Code for your ref.

Sign up to request clarification or add additional context in comments.

1 Comment

how do I pass as blob to a child components, i know ngfor, just don't want it only tie to the li line element, see I have elements below in child components, will use :host later to apply the stylings generated

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.