【问题标题】:(Angular) Set *ngFor " i " value as (data.id)(Angular) 将 *ngFor "i" 值设置为 (data.id)
【发布时间】:2019-05-20 07:54:21
【问题描述】:

当使用 *ngFor 时,我想在 'let i = ...' 中存储一个不同于 'index' 的值,因为我将使用它作为列表元素的 ID。

这基本上就是我想要的:

 <div *ngFor="let data of User; let i = {{data.id}}"></div>

我试过这样,也这样:

 <div *ngFor="let data of User; let i = (data.id)"></div>

或:

 <div *ngFor="let data of User; data.id as i"></div>

我最后一次尝试是使用 trackBy。但它惨遭失败

没有任何效果,应用程序停止。这甚至可能吗?怎么办?

编辑

所以,我被要求提供更多细节。

我正在使用这个 ngFor 来显示我的数据库中的一些信息。但它需要每个元素都有一个 ID。该 ID 必须与数据库中的相同。如果我只使用'i = index',则 ID 将来自(0 - 最后一个),但我不想要那个。我需要 ID 是我的数据库中的内容,这就是为什么,'i = index' 不可行,我需要像'i = data.id'这样的东西

【问题讨论】:

  • 我不知道您是否阅读了我的问题,但它与 stackoverflow.com/questions/35405618/ngfor-with-index-as-value-in-attribute/35405648#35405648 非常不同
  • 在我的例子中,我想把正在显示的数据作为“i”的值
  • 您是否有理由要为此使用i,而不是仅仅使用[id]="data.id" 之类的?
  • 不是真的,sintax 会是怎样的呢?因为 *ngFor="let data of User; [id]='data.codigo015'" 不起作用(对不起,我没用过这个)
  • @CH4B 你必须把它放在引号之外。

标签: angular ngfor


【解决方案1】:

你可以试试下面的

'$implicit.id' as i

演示https://stackblitz.com/edit/angular-8agswk

【讨论】:

    【解决方案2】:

    没有必要去那么麻烦,因为您已经可以直接将 id 绑定到值。例如

    <div *ngFor="let data of User" [id]="data.id"></div>
    

    【讨论】:

      猜你喜欢
      • 2019-02-08
      • 2016-09-10
      • 2023-04-10
      • 2020-05-22
      • 2020-11-08
      • 2018-11-29
      • 2020-01-01
      • 2018-12-16
      相关资源
      最近更新 更多