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

时间:2019-06-12 18:24:09

标签: angular ngfor

我正在使用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;
  }
}

返回的屏幕截图:

Repeating property values in ngFor loop

2 个答案:

答案 0 :(得分:3)

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

如果您从此级别使用它,则它看起来像loadedTableData[i][property]

答案 1 :(得分:1)

item循环变量已经引用了loadedTableData数组的一项。您无需在i绑定中使用其他索引ngModel。您可以使用[(ngModel)]="item[property]"

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

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

以下是等效的属性绑定语法:

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