Currently, I am working on a project where I have successfully stored checkboxes dynamically using a JSON array of objects. However, I am facing an issue that requires your expertise. My goal is to allow the selection of only 5 checkboxes. Once this limit has been reached, I need to disable any unchecked checkboxes and apply specific CSS changes to those disabled checkboxes. I have attempted to implement this functionality but have encountered difficulties in changing the class of unselected checkboxes once the selection count hits 5.
<div class="pinnedtoolsbox" *ngFor="let item of menuList">
<div>
<div class="pinnedtoolbox-caption">
<div>
<img src="{{item.icon}}"/>
</div>
<div>
<span>{{item.title}}</span>
</div>
</div>
</div>
<div *ngFor="let sublist of item.submenus; let i=index" >
<label [ngClass]="sublist.selected ? 'submenulist_label_checked': 'submenulist_label'">
<div>
<img [src]="sublist.selected ? 'assets/icons/listmenuiconwhite.svg': 'assets/icons/listicon.svg'"/>
</div>
<div>
{{ sublist.menu }}
<input type="checkbox"
[(ngModel)]="sublist.selected"
[disabled]="disableCheckbox(sublist)"
(change)="changeSelection($event, sublist)"
style="display:none;">
</div>
</label>
</div>
</div>
component.ts file
private _jsonURL = 'assets/menus.json';
public getJSON(): Observable<any> {
return this.http.get(this._jsonURL);
}
[{"title":"one",
"submenus": [
{
"id":1, "menu": "home", "selected": false
},
{
"id":2, "menu": "about", "selected": false
},
]
},
{"title":"two",
"submenus": [
{
"id":1, "menu": "Status", "selected": false
},
{
"id":2, "menu": "Balance", "selected": false
},
]
},
]
checkboxList = [];
public maxElementCheckbox = 5;
changeSelection($event, item){
if ($event.target.checked) {
this.checkboxList.push(item);
}
else {
this.checkboxList.splice(this.checkboxList.indexOf(item), 1);
console.log("esle part");
}
console.log(this.checkboxList);
}
public disableCheckbox(id): boolean {
return this.checkboxList.length >= this.maxElementCheckbox && !this.checkboxList.includes(id);
}