如何 *ngFor 超过一组 ngModel 可绑定属性

How to *ngFor over set of ngModel bindable properties

我正在尝试将 *ngFor 用于一组相同的输入,除了输入应绑定到的 属性。

<mat-form-field *ngFor="let prop of [ID, Name, Nickname]">
    <input matInput type="text" placeholder="prop.key" #propInput [(ngModel)]="prop">
    <button mat-icon-button matSuffix mat-icon-button *ngIf="propInput.value" (click)="prop='';">
        <mat-icon>close</mat-icon>
    </button>
</mat-form-field>

 <!-- bind test -->
<input matInput type="text" placeholder="Name Test" #propInput [(ngModel)]="Name">

prop.key 不起作用,但这是一个单独的问题。

这是联机组件:

import { Component } from '@angular/core';
import { EntitySrcService } from '../entity-src.service';

@Component({
  selector: 'app-entity-table',
  templateUrl: './entity-table.component.html',
  styleUrls: ['./entity-table.component.less']
})

export class EntityTableComponent {

  constructor(
    private entitySrc: EntitySrcService
    ) {}

  public get ID(): string {
    return this.entitySrc.id;
  }

  public set ID(value: String) {
    this.entitySrc.id = value;
  }

  public get Name(): string {
    return this.entitySrc.name;
  }

  public set Name(value: String) {
    this.entitySrc.name = value;
  }

  public get Nickname(): string {
    return this.entitySrc.altName;
  }

  public set Nickname(value: String) {
    this.entitySrc.altName = value;
  }

}

在大多数情况下,这似乎按预期工作,但 [(ngModel)] 绑定似乎只读取 属性 而不是写入它。因此,例如,如果我更新绑定测试输入,ngFor 循环中的名称字段会更新以匹配,但更新 ngFor 循环中的名称字段不会更新测试中的名称字段。

我在组件中使用 get/set 属性来代理到实际存储位置,但我的理解是 get/set 属性 应该与普通 属性(并且使用普通的 属性 具有相同的单向绑定行为)。

那么我该如何正确地迭代我想要绑定的一组属性呢?

看起来[ID, Name, Nickname]是值类型。在这种情况下 *ngFor 只是使用它们的值而不绑定到原始变量。 如果您仍然需要绑定,您应该考虑将它们转换为引用类型。

例如,您可以将它们放入对象中,例如 person 或 options,并使用 KeyValuePipe 迭代对象属性:

options: {[key: number]: string} = {ID: '1', Name: 'bar', Nickname: 'foo'};

<div *ngFor="let item of options | keyvalue">

在 Angular 6.1 中引入了 KeyValuePipe,它允许您迭代对象属性:

<div *ngFor="let item of object | keyvalue">
  {{item.key}}:{{item.value}}
</div>

文档:https://angular.io/api/common/KeyValuePipe

数组[ID, Name, Nickname]包含三个属性的值,而不是它们的引用。双向绑定将修改数组项而不是原始属性(要使其工作,您必须按索引引用项并按索引跟踪数组,如 所示)。

要实现组件属性的双向绑定,您可以使用 属性 名称数组,并使用 this[prop]:

引用每个 属性
<mat-form-field *ngFor="let prop of ['ID', 'Name', 'Nickname']">
  <input [(ngModel)]="this[prop]" ... >
  ...
</mat-form-field>

有关演示,请参阅 this stackblitz