I have 2 array of object, one compareJson and other checkboxesDataList ,so on select of checkbox I am comparing the id of both json and getting the filtered value of checkboxesDataList in console.log(matches); I am getting the correct value here. Now I want to pre compare both the json based on id on page load and make pre selected the checkbox. For example C001 and C003 are common in both json so only those data from checkboxesDataList will be pre selected. Here is the code
https://stackblitz.com/edit/angular-fst6jp?file=src%2Fapp%2Fapp.component.ts,
app.component.html
<hello name="{{ name }}"></hello>
<p>
Start editing to see some magic happen :)
</p>
<ul class="checkbox-items">
<li *ngFor="let item of checkboxesDataList">
<input type="checkbox" [(ngModel)]="item.isChecked" (change)="changeSelection()">{{item.label}}
</li>
</ul>
<button (click)="submit()">Submit</button>
<div *ngFor="let item of compareJson">Item listed - {{item.details}}</div>
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Angular';
selectedItemsList: any[] = [];
checkedIDs: any[] = [];
compareJson = [
{
id: 'C001',
details: 'Photography details'
},
{
id: 'C001',
details: 'Writing details'
},
{
id: 'C003',
details: 'Painting Details'
}
];
checkboxesDataList = [
{
id: 'C001',
label: 'Photography'
},
{
id: 'C002',
label: 'Writing'
},
{
id: 'C003',
label: 'Painting'
}
];
ngOnInit() {}
changeSelection() {
this.checkedIDs = [];
this.selectedItemsList = this.checkboxesDataList.filter((value, index) => {
return value.isChecked;
});
console.log(this.selectedItemsList);
let i;
for (i = 0; i < this.selectedItemsList.length; i++) {
console.log(this.selectedItemsList[i].id);
this.checkedIDs.push(this.selectedItemsList[i].id);
}
const matches = this.compareJson.filter(object =>
this.checkedIDs.includes(object.id)
);
console.log(matches);
}
submit() {
const matches = this.compareJson.filter(object =>
this.checkedIDs.includes(object.id)
);
console.log(matches);
}
}