I have one array that contain all the office list. another array is user selected list. so now I want to display all officelist and if the value in selected list is the same with office list then the checkbox will be checked. This is how I did it.
Code
<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>
My officeLIST
this.officeLIST = [
{ "office_id": "1", "officename": "Sun Dept" },
{ "office_id": "2", "officename": "Moon" },
{ "office_id": "3", "officename": "Stars" }
]
allOffice.office array
"office": [
{
"office_id": "1",
"officename": "Sun Dept"
},
{
"office_id": "2",
"officename": "Moon Dept"
}
]
use this solution.this works fine for me. I have done all the things in constructor .if you want this in a method simply use the code block inside the constructor.
this is my ts file:
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);
}
this is my html:
<div *ngFor="let item of newArray">
<input type="checkbox" [checked]="item.checked"> {{item.officename}}
</div>