Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 how to apply dynamic styles?

Tags:

angular

Is it possible to apply dynamic top and left values for ngFor repeated span element in Angular 4?

like image 639
Anna Avatar asked Jan 12 '18 09:01

Anna


People also ask

How do you change dynamic styles?

color = "red"; you can apply the style change dynamically. Below is a function that turns an element's colour to red when you pass it the element's id . You could also use setAttribute(key, value) to set a style on an element. For example, you could set the colour of an element to red by calling element.


1 Answers

You can use:

  1. the [style.anything] binding, eg: <span [style.color]="red"></span>
  2. the [ngStyle]binding that allows specifying multiple CSS properties at once, eg: <span [ngStyle]="{'color': 'red', 'font-weight': condition? 'bold':'300'}"></span>
  3. the [className] binding to apply a CSS class name dynamically, eg: <span [className]="condition? 'redText': 'blueText'"></span>
  4. the [ngClass] binding that allows specifying multiple CSS classes at once, just like ngStyledoes for CSS properties, eg: <span [ngClass]="{'redText': condition1, 'blueText': condition2}"></span>

    [ngClass] receives an object as its input, and applies each one of that object's keys only if the respective value evaluates to true.

    For instance, if you're iterating over the array items_array:

    <span *ngFor="let i of items_array" [ngClass]="{'redText': i.shouldBeRed, 'blueText': i.shouldBeBlue}"> The span text </span>

    the CSS class of each element (i) will be:

    • redText if the attribute i.shouldBeRed evaluates to true (that is: it's true, 1, a non-empty string, or a non-null object;
    • blueText if the attribute i.shouldBeBlue evaluates to true;
    • redText blueText if both attributes evaluate to true.

In your case, I guess that [ngStyle] would be appropriate:

<span *ngFor="let i of items_array" [ngStyle]="{'top': expression1, 'left': expression2}"> The span content </span>

like image 143
Paolo Stefan Avatar answered Sep 20 '22 22:09

Paolo Stefan