如何从ngFor循环访问项目中的属性?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (57)

我正在使用ngFor指令迭代从SQL后端获取的数据。数据被过滤为行,并以JSON格式构建。

我想在循环中访问CURRENT索引的属性值并将其绑定到ngModel指令,但是当我尝试时,我将LAST索引的值复制到我的所有行中。

<form #updateRowForm="ngForm" class="update-row-form">
<table mdbTable #tableEl="mdbTable" class="table table-bordered
table-responsive-md table-striped text-center">
<thead>
    <tr>
    <th *ngFor="let head of loadedTableData[0] | keys;">{{head}}</th>
    </tr>
</thead>
<tbody>
    <tr *ngFor="let item of loadedTableData; let i = index;">
    <td *ngFor="let property of item | keys;" class="form-group">

    <!--the below will produce undefined for ngModel -->
    <!-- but if I use the below syntax for placeholder attribute, it displays the correct data. Problem is, I need to set this as a default value, hence use of ngModel -->

        <input #editRowProp mdbInput
            [(ngModel)]="item[i][property]"
            class="form-control"
            name="{{property}}"
            placeholder="{{item[property]}}"
            type="text">
    </td>
    <td>
        <button type="button" mdbBtn class="btn btn-primary
            rounded
            btn-sm my-0"
            (click)="updateRow(updateRowForm, item)">Update</button>
            <hr>
        <button type="button" mdbBtn class="btn btn-danger
            rounded
            btn-sm my-0" (click)="deleteRow(item)">Remove</button>
    </td>
    </tr>
</tbody>
</table>

迭代数据的示例:

[{TaxCode: "1A", TaxDescription: "testing"},{TaxCode: "A1", TaxDescription: "Costa Rica Baggage Inspection Fee"},{TaxCode: "A6", TaxDescription: "Tunisia Tourism Tax"},{TaxCode: "A7", TaxDescription: "Bolivia Passenger Service Charge"},{TaxCode: "AA", TaxDescription: "Dominican Republic Departure Tax"},{TaxCode: "AB", TaxDescription: "Haiti Airport Departure Tax"}, {TaxCode: "DR", TaxDescription: "Egypt Airport Facility Charge"}]

键管文件:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'keys'
})
export class KeysPipe implements PipeTransform {
  transform(value: any, args?: any): any {
    const keys = [];
    for (const key in value) {
      keys.push(key);
    }
    return keys;
  }
}

返回的屏幕截图:

在ngFor循环中重复属性值

提问于
用户回答回答于

item循环变量已经指的项目loadedTableData阵列。您不需要ingModel绑定中使用其他索引。你可以用[(ngModel)]="item[property]"

由于输入字段位于a内form,因此请确保每个输入name都是唯一的。实现这一目标的一种方法是将循环索引iproperty值组合在name

<input [(ngModel)]="item[property]" name="{{ 'input_' + property + '_' + i }}" ... >

这是等效的属性绑定语法:

<input [(ngModel)]="item[property]" [name]="'input_' + property + '_' + i" ... >
用户回答回答于

使用当前布局,您使用的所有内容都<td>与具有多个属性的一个项目相关联。数组的索引与loadedTableData

如果你从这个级别使用它,它看起来像 loadedTableData[i][property]

扫码关注云+社区

领取腾讯云代金券