2

I'm new to Angular and I searched around but can't find the answer to my question.

I have defined a variable in my class and plan to use it in the template.

public colors = ['red', 'green', 'blue', 'yellow'];

In the template, I have below code:

<div *ngFor="let c of colors; index as i">
    <div [style.width]="'100px'" [style.height]="{{(i+1)*10}}px" [style.backgroundColor]="c">{{c}}</div>
</div>

My intention is to calculate the CSS height by the formula (i+1)*10px. The syntax in the upper snippet is not correct. What's the correct way to implement it?

3 Answers 3

3

You need something like this,

<div *ngFor="let c of colors; index as i">
    <div [style.width]="'100px'" [style.height]="(i+1)*10+'px'" [style.backgroundColor]="c">{{c}}</div>
</div>

STACKBLITZ DEMO

Sign up to request clarification or add additional context in comments.

Comments

2

Just remove square brackets []. Here is updated one below

<div *ngFor="let c of colors; let i  =  index">
    <div  style.height="{{(i+1)*10}}px" [style.backgroundColor]="c">{{c}}</div>
</div>

Have a look StackBlitz

1 Comment

I know this. My question is how to do the calculation using i for [style.height].
1

You can use [style.height.px] an attribute which explicitly tells unit, So in your case its px and then use your formula to calculate number:

<div *ngFor="let c of colors; index as i">
    <div [style.width]="'100px'" [style.backgroundColor]="c" [style.height.px]="((i+1)*10)">
      {{c}} {{i*10}}
    </div>
</div>

StackBlitz

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.