Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment [ngStyle] attr using ngFor index?

I'm trying to dynamically create several elements using ngFor and then set the top attribute depending on the amount drawn.

I'm wondering if there is a way to access the index of ngFor on the same div for ngStyle? i.e;

<div class="row" *ngFor="let d of data; let i = index;" [ngStyle]="{'top': mrTop*i}" >

If not, any suggestions how I can achieve something similar?

I would prefer to avoid adding another div like;

<div *ngFor="let d of data; let i = index;">
  <div class="testCase" [ngStyle]="{'top': mrTop*i}">{{d}}</div>
</div>

(Although this doesn't work either)

I am wondering if there is a way to attach an event listener to the loop event so that behind the scenes I can increment the mrTop variable for each div drawn?

Anyway, I'm not sure how best to approach this and hoping for some help/advice.

Plunk here

like image 305
alexc Avatar asked Dec 20 '16 08:12

alexc


Video Answer


2 Answers

Your mrTop variable is a string, you can't multiply it.

Try:

public mrTop = 10;

and then

<div [ngStyle]="{'top': mrTop*i + '%'}">

or

<div [style.top.%]="mrTop*i">
like image 105
Sasxa Avatar answered Sep 20 '22 16:09

Sasxa


There are several mistakes

'10%' * i // not valid number

public mrTop: 10; // defines mrTop as of type 10 which doesn't make sense
// it should be public mrTop= 10;

Ng style can look like

[ngStyle]="{'top': mrTop * i + '%'}"

Plunker example

like image 34
Günter Zöchbauer Avatar answered Sep 16 '22 16:09

Günter Zöchbauer