My specific requirement is as follows:
Whenever the parent element is clicked, its child elements should also be selected. It should also be possible to deselect any undesired elements. Upon button click, the selected parent and children names should be obtained as an object.
What I have done so far:
I have created a list of parents and children, provided checkboxes for the parents, and retrieved the parents' values after checking and unchecking them.
I am currently stuck on how to select the children within that parent and retrieve the values of both the parent and children.
Below is my code snippet:
.ts
@ViewChildren('myItem') item;
selectedIds = [];
display: any;
data: any;
ngOnInit(){
// dynamic JSON
this.data = {
"info": {
"laptop": {},
"config": {
"properties": {
"ram": {},
"processor": {},
"hdd": {}
}
},
"link": {},
"name": {},
"company": {
"properties": {
"model": {},
"maker": {"type": "integer"},
"country": {"type": "text"},
"enterprise": {}
}
}
}
};
this.display = this.data['info'];
console.log(this.display);
}
change(data, event){
if (event.target.checked === true) {
this.selectedIds.push({id: data, checked: event.target.checked});
console.log('Selected data ', JSON.stringify(this.selectedIds));
}
if (event.target.checked === false) {
this.selectedIds = this.selectedIds.filter((item) => item.id !== data);
}
}
getData(){
const filtered = this.selectedIds.filter(item => item.id)
console.log(JSON.stringify(filtered));
}
.html code
<ul class="list-group" *ngFor="let parent of display | keyvalue">
<li class="list-group-item">
<input type="checkbox" [value]="parent.key" [(ngModel)]="parent.check" #myItem (change)="change(parent.key, $event)">{{parent.key}}
</li>
<ng-container *ngIf="parent.check && parent.value.hasOwnProperty('properties')">
<ul *ngFor="let child of parent.value.properties | keyvalue">
<li>
{{child.key}}
</li>
</ul>
</ng-container>
</ul>
<hr>
<button class="btn btn-primary" (click)="getData()">Get Data</button>
My StackBlitz link