【发布时间】: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
-
ID、Name和Nickname变量中存储的数据是什么? -
一种可能的解决方法是使用一组属性名称,如this stackblitz 所示。
-
@ConnorsFan 你能回答吗?这几乎正是我想要的。我觉得应该有更好的方法来迭代更复杂的情况下的 ngModel 可绑定属性,但现在至少
this[prop]方法有效。
标签: javascript angular ngfor angular-ngmodel