我有一个包含所有办公室列表的数组.另一个数组是用户选择列表.所以现在我想显示所有的官方列表,如果所选列表中的值与office列表相同,则将选中该复选框.这就是我做到的.码
<div *ngFor="let item of officeLIST">
<div *ngFor="let officeDATA of allOffice.office">
<div *ngIf="item.office_id == officeDATA.office_id">
<input #officeArray type="checkbox" id="officeArray" name="officeArray" class="form-control" value="{{item.officename}}"
checked> {{(item.officename == "" ? "--No data--" : item.officename)}}
</div>
<div *ngIf="item.office_id != officeDATA.office_id">
<input #officeArray type="checkbox" id="officeArray" name="officeArray" class="form-control" value="{{item.officename}}"> {{(item.officename == "" ? "--No data--" : item.officename)}}
</div>
</div>
</div>
结果是
我的办公室列表
this.officeLIST = [
{ "office_id": "1", "officename": "Sun Dept" },
{ "office_id": "2", "officename": "Moon" },
{ "office_id": "3", "officename": "Stars" }
]
allOffice.office数组
"office": [
{
"office_id": "1",
"officename": "Sun Dept"
},
{
"office_id": "2",
"officename": "Moon Dept"
}
]
最佳答案 使用这个解决方案.这对我来说很好.我已经在构造函数中完成了所有的事情.如果你想在方法中使用构造函数中的代码块.
这是我的ts文件:
officeLIST: Array<any> = [
{ "office_id": "1", "officename": "Sun Dept" },
{ "office_id": "2", "officename": "Moon" },
{ "office_id": "3", "officename": "Stars" }
];
office: Array<any> = [
{
"office_id": "1",
"officename": "Sun Dept"
},
{
"office_id": "2",
"officename": "Moon Dept"
}
];
newArray: Array<any> = [];
constructor() {
for (var i = 0; i < this.officeLIST.length; i++) {
var ismatch = false; // we haven't found it yet
for (var j = 0; j < this.office.length; j++) {
if (this.officeLIST[i].office_id == this.office[j].office_id) {
// we have found this.officeLIST[i]] in this.office, so we can stop searching
ismatch = true;
this.officeLIST[i].checked = true;// checkbox status true
this.newArray.push(this.officeLIST[i]);
break;
}//End if
// if we never find this.officeLIST[i].office_id in this.office, the for loop will simply end,
// and ismatch will remain false
}
// add this.officeLIST[i] to newArray only if we didn't find a match.
if (!ismatch) {
this.officeLIST[i].checked = false;// checkbox status false
this.newArray.push(this.officeLIST[i]);
} //End if
}
console.log(this.newArray);
}
这是我的HTML:
<div *ngFor="let item of newArray">
<input type="checkbox" [checked]="item.checked"> {{item.officename}}
</div>