alexc
alexc

Reputation: 1310

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

Upvotes: 9

Views: 2633

Answers (2)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657118

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

Upvotes: 4

Sasxa
Sasxa

Reputation: 41254

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">

Upvotes: 6

Related Questions