【问题标题】:How to use ngFor index variable in HTML element attribute value calculation?如何在 HTML 元素属性值计算中使用 ngFor 索引变量?
【发布时间】:2019-03-10 06:06:38
【问题描述】:

我是 Angular 的新手,我四处搜索,但找不到我的问题的答案。

我已经在我的类中定义了一个变量,并计划在模板中使用它。

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

在模板中,我有以下代码:

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

我的意图是通过公式(i+1)*10px 计算 CSS 高度。上面的 sn -p 中的语法不正确。正确的实现方式是什么?

【问题讨论】:

    标签: angular ngfor


    【解决方案1】:

    只需删除方括号[]。下面更新一个

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

    看看StackBlitz

    【讨论】:

    • 我知道这一点。我的问题是如何使用 i for [style.height] 进行计算。
    【解决方案2】:

    你需要这样的东西,

    <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

    【讨论】:

      【解决方案3】:

      您可以使用[style.height.px] 一个明确告诉单位的属性,因此在您的情况下是px,然后使用您的公式计算数字:

      <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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-01-20
        • 2017-08-07
        • 2017-05-19
        • 2016-08-12
        • 2020-04-14
        • 2017-11-14
        • 2023-01-31
        • 1970-01-01
        相关资源
        最近更新 更多