Reputation: 25
I want to add a style to each element in my *ngFor
<div class=greenBox *ngFor="let item of items;"
[ngStyle]="{
'top': item.Y,
'left': item.X
}">
{{item.description}}
</div>
when i do this as code above shows only the first elements style gets set:
<div class="greenBox ng-star-inserted" ng-reflect-ng-style="[object Object]" style="top: 0px; left: 0px;"> 0 </div>
<div class="greenBox ng-star-inserted" ng-reflect-ng-style="[object Object]"> 1 </div>
<div class="greenBox ng-star-inserted" ng-reflect-ng-style="[object Object]"> 2 </div>
<div class="greenBox ng-star-inserted" ng-reflect-ng-style="[object Object]"> 3 </div>
I expected to get a style attribute on each element.
Upvotes: 1
Views: 3144
Reputation: 5462
As per Angular doc:
The styles are updated according to the value of the expression evaluation:
- keys are style names with an optional
.<unit>
suffix (ie 'top.px', 'font-style.em'),- values are the values assigned to those properties (expressed in the given unit).
You can find complete reference here
So your modified code should be:
<div class=greenBox *ngFor="let item of items;"
[ngStyle]="{'top.px': item.Y, 'left.px': item.X}">
{{item.description}}
</div>
Upvotes: 1
Reputation: 9697
I have create a demo on Stackblitz
<div class="greenBox" *ngFor="let item of items;"
[ngStyle]="{
'top.px': item.y,
'left.px': item.x
}">
{{item.description}}
</div>
Upvotes: 1
Reputation: 3870
What does your items
object look like?
I created this StackBlitz that mimics your code (I simply replaced top
and left
with border
and background-color
for a quick visual check): https://stackblitz.com/edit/angular-rdb9tr
It works, so I'm guessing there may be an error in your items
object...
Upvotes: 1