我尝试将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循环中的Name字段将更新以匹配,但是更新ngFor循环中的Name字段不会更新测试中的一个。
我正在组件中使用get / set属性来代理实际的存储位置,但是我的理解是get / set属性应与普通属性具有相同的作用(并且使用normal属性具有相同的一种方法绑定行为)。
因此,如何正确地迭代要绑定到的一组属性?
[[0]看起来是值类型。在这种情况下,[ID, Name, Nickname]
仅使用其值而不绑定到原始变量。如果仍然需要绑定,则应考虑将它们转换为引用类型。
例如,您可以将它们放入对象中,例如人员或选项,然后迭代对象属性:*ngFor
How to iterate object keys using *ngFor
在Angular 6.1中引入了KeyValuePipe,它允许您迭代对象属性:
options: {[key: number]: string} = {ID: '1', Name: 'bar', Nickname: 'foo'};
<div *ngFor="let item of options | keyvalue">
文档:<div *ngFor="let item of object | keyvalue">
{{item.key}}:{{item.value}}
</div>