【问题标题】:How to *ngFor over set of ngModel bindable properties如何 *ngFor 超过一组 ngModel 可绑定属性
【发布时间】:2020-01-27 21:09:04
【问题描述】:

我正在尝试将*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 属性应该与普通属性的行为相同(并且使用普通属性具有相同的属性)方式绑定行为)。

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

【问题讨论】:

  • 你能发布你的 json 对象结构吗,如果可能的话,创建一个 stackblitz
  • IDNameNickname变量中存储的数据是什么?
  • 一种可能的解决方法是使用一组属性名称,如this stackblitz 所示。
  • @ConnorsFan 你能回答吗?这几乎正​​是我想要的。我觉得应该有更好的方法来迭代更复杂的情况下的 ngModel 可绑定属性,但现在至少 this[prop] 方法有效。

标签: javascript angular ngfor angular-ngmodel


【解决方案1】:

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

例如,您可以将它们放入对象中,例如人员或选项,并使用 KeyValuePipe 迭代对象属性: How to iterate object keys using *ngFor

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

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

【讨论】:

  • 本例中的项目不能绑定到[(ngModel)]
【解决方案2】:

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

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

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

【讨论】:

  • 我不需要键值对。我特别希望在一组要绑定到 ngModel 的属性上使用 ngFor。
【解决方案3】:

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

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

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

请参阅this stackblitz 以获取演示。

【讨论】:

    猜你喜欢
    • 2019-05-18
    • 1970-01-01
    • 2019-02-28
    • 2018-03-25
    • 2018-03-20
    • 2018-11-11
    • 2018-11-23
    • 1970-01-01
    • 2017-07-19
    相关资源
    最近更新 更多