28

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

3
  • Yes, what do you want to do? stackoverflow.com/questions/35269179/… Commented Jan 12, 2018 at 9:50
  • <span [style.top]="topvalue"></span> where topvalue is a variable. Commented Aug 20, 2019 at 6:16
  • [ngClass]="{'alert-card': hasError }" Commented Apr 12, 2022 at 7:55

1 Answer 1

53

You can use:

  1. the [style.anything] binding, to do something simple eg. <span [style.color]="red"></span>, or something more complicated like eg. bind a variable (here progress) to a percentage (width): [style.width.%]="progress";
  2. the [ngStyle] binding, allowing to specify several 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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.