我有两个数组
firstArray= [{id: 1, name:'firstValue1'}, {id:2, name:'firstValue2'}]
secondArray= [{ "num": 1, "fullName": SecondValue1 , id:1}]
我想显示这样的数据
firstValue1 -------->> SecondValue1
firstValue2 -------->>
如何在[(ngModel)]或输入或选择框中填充这两个数组?
感谢您的时间和回复!
答案 0 :(得分:0)
将secondArray
保留为Array
而不是将其转换为HashMap
示例
firstArray = [
{ id: 1, name:'firstValue1' },
{ id: 2, name:'firstValue2' }
];
secondArray = {
'1': { "num": 1, "fullName": "SecondValue1", id: 1 },
'2': { "num": 1, "fullName": "SecondValue2", id: 2 },
}
html
<div *ngFor="let item of firstArray">
<p>{{item.name}} --> {{secondArray[item.id]?.fullName}}</p>
</div>
答案 1 :(得分:0)
如果您不想手动向secondArray
添加索引,请尝试一下:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
firstArray = [
{ id: 1, name: 'firstValue1' },
{ id: 2, name: 'firstValue2' }
];
secondArray = [
{ "num": 1, "fullName": 'SecondValue1', id: 1 },
{ "num": 2, "fullName": 'SecondValue2', id: 2 }
];
getSecondArrayItem(id) {
return this.secondArray.find(item => item.id === id);
}
}
在模板中:
<div *ngFor="let item of firstArray">
<p>{{item.name}} --> {{ getSecondArrayItem(item.id)?.fullName }}</p>
</div>
这是您推荐的Working Sample StackBlitz。