【问题标题】:Using variable inside of ngFor在 ngFor 中使用变量
【发布时间】:2018-08-10 18:32:15
【问题描述】:

我有很多 ngFor 的表,我如何从 getList() 的项目中做 HTML 中的局部变量?

我需要用户#?

示例: <div *ngFor="let #item of getList()"></div> ?以及如何在下一个 ngFor HTML 中使用局部变量?

【问题讨论】:

  • 在此处添加您的 getList() 方法
  • 您能否分享更多代码并进一步解释您想要实现的目标?我不完全明白你想做什么。
  • 我在 table thead tr 中有 ngFor,我需要在表格正文中使用 ngFor 元素。例如 我需要在表体标签中使用这个项目。如何从 getList() 项中获取局部变量?

标签: angular ngfor


【解决方案1】:

HTML

<div *ngFor="let item of myList" #item></div>
  • item 指的是myList 中的每一项
  • #item 是对 DOM 中元素的引用

打字稿

export class YourComponent {

    get myList(): any[] {
        return this.mySpecialList;
    }

}

您可以使用get 函数myList 将自定义数组绑定到*ngFor(如果发生变化,该数组也会自动更新)

P.S.:我不太确定我是否正确理解了您的问题。让我知道这是否有帮助!

【讨论】:

  • 是的,我知道,但我不需要绑定 myList 而是绑定 item,因为我需要 item 变量而不是 myList。有另一个想法从 ngFor 的项目中获取变量?
  • 你不能用item.proporty来获取变量吗?
  • 是的,我使用 item.property 将变量导入 HTML,但我需要获取所有项目,因为我必须使用 *ngIf 并将 table body 标记中的 value.property 与 table thead 标记中的 item.property 进行比较。
  • 您可以尝试将索引添加到*ngFor&lt;div *ngFor="let item of getList(); let i = index"&gt;&lt;/div&gt;,然后您可以将itemotherList[i] 进行比较
  • 我不能,因为项目列表是 groupby 而 otherList[i] 不是,所以不能这样做,总结一下我必须有更多的 ngFor 和项目。
【解决方案2】:

我有表格示例:

<div class="card mb-4">
  <div class="card-body card-table">
    <div class="table-responsive">
      <table class="table table-striped table-bordered">
        <thead>
          <tr>
            <th class="align-middle">Przydział:</th>
            <th class="align-middle" *ngFor="let distinctStatus of groupByList(list, 'status')">{{distinctStatus.status}}</th>
          </tr>
        </thead>
        <tbody>
          <tr *ngFor="let distinctId of groupByList(list, 'id')">
            <td class="align-middle">{{distinctId.id}}</td>
            <td class="align-middle text-right" *ngFor="let distinctStatus of groupByList(list, 'status')">
              <span *ngFor="let value of groupByList(list, 'id', 'status')">
                <span *ngIf="value.id == distinctId.id && value.status == distinctStatus.status">{{value.number}}</span>
              </span>
            </td>
          </tr>
          <tr>
            <td class="align-middle font-weight-bold">Razem:</td>
            <td class="align-middle text-right font-weight-bold" *ngFor="let distinctStatus of groupByList(list, 'status')">
              <span *ngFor="let value of groupByList(list, 'status')">
                <span *ngIf="value.status == distinctStatus.status">{{value.number}}</span>
              </span>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</div>

我如何从 thead tr th 获取 distinctStatus 变量,因为我需要在 body tr td 中将此变量与 ngIf 一起使用(将 value.property 与 distinct.property 进行比较。现在我有很多 ngFor,因为我无法在 ngFor 范围之后获得 distinctStatus 变量。

【讨论】:

    猜你喜欢
    • 2020-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-12
    • 2019-08-22
    • 1970-01-01
    相关资源
    最近更新 更多