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
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
Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Dec 20, 2016 at 8:02 alexcalexc 1,3102 gold badges18 silver badges46 bronze badges 3- Have you tried it? I don't see why it wouldn't work. – Günter Zöchbauer Commented Dec 20, 2016 at 8:06
- @GünterZöchbauer I have, but it doesn't seem to be working. Unless I've missed something - I included a plunk as an example which demonstrates the test case – alexc Commented Dec 20, 2016 at 8:08
- I missed that link (as always if they are not emphasized) |-/ – Günter Zöchbauer Commented Dec 20, 2016 at 8:10
2 Answers
Reset to default 6Your 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">
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