我正在开发模板驱动方法的应用程序。以下是我的项目结构。
parent.component.ts
parent.component.html
child.component.ts
child.component.html
child.ts
child.ts:
export class child {
public childValue: address[];
}
export class address {
public state: string;
public city: string;
}
child.component.ts
<div *ngFor="let item of ValueItem; let i=index">
<label> {{item.name}}</label>
<input name="city" [(ngModel)]="address[i].state"/>
</div>
当我尝试将地址对象的状态字符串映射到ngModel
时,我无法做到并且显示错误&#34;无法读取属性&#39; state&#39;未定义&#34;。是否可以将对象数组中的对象映射到ngModel
?如果是这样,怎么办呢?
答案 0 :(得分:1)
总之,是的!可以将对象数组中的对象映射到ngModel 您提供了此模板代码。
<div *ngFor="let item of ValueItem; let i=index">
<label> {{item.name}}</label>
<input name="city" [(ngModel)]="address[i].state"/>
</div>
我假设ValueItem
的类型为address[]
,并确保它包含一些数据。
如果是这样,您应该能够通过以下方式访问数据:
<div *ngFor="let item of ValueItem">
<label> {{item.city}}</label>
<input name="city" [(ngModel)]="item.state"/>
</div>
如果我们看看发生了什么。 *ngFor="Let item of ValueItem;
允许我们遍历数组,并允许我们通过item
访问该对象,在这种情况下类型为address
。我们从早些时候就知道address
有2个属性state
和city
。所以要使用它们我们可以简单地使用例如item.state
。
希望这会有所帮助。