I'm working in a side panel filter for my page, I have the parent checkbox (Select all) and the children checkboxes(specific filters).
Here is what I want, if I select a children I want the parent checkbox to be partially checked, see image below:
Currently this is my code, my parent checkbox ngModel is set to "dataSource.data.length == selectedAssetTypeFilters.length"
<mat-panel-title>
<mat-checkbox [(ngModel)]="dataSource.data.length == selectedAssetTypeFilters.length" (click)="$event.stopPropagation()" (keydown)="$event.stopPropagation()" (change)="onSelectAll($event, 'assettype')" title="Select All">Data Asset Type</mat-checkbox> </mat-panel-title> </mat-expansion-panel-header>
<div >
<mat-tree [dataSource]="dataSource" [treeControl]="treeControl" >
<!-- This is the tree node template for leaf nodes -->
<mat-tree-node *matTreeNodeDef="let node" matTreeNodeToggle>
<li >
<mat-checkbox [(ngModel)]="node.checked" (change)="onFilterUpdate(node, 'assettype');" title="{{node.label}}">
How can I do this?
CodePudding user response:
Use the [indeterminate]
property of the mat checkbox and bind it with a variable which would go true when at least one child is selected and would go false when all children are selected.
<mat-checkbox [(ngModel)]="node.checked" [intermediate]="childChecked"(change)="onFilterUpdate(node, 'assettype');" title="{{node.label}}">
https://material.angular.io/components/checkbox/overview#check-indeterminate
CodePudding user response:
In this case, you do not want to use two way binding on the parent checkbox since the condition you're passing in is a comparison expression, rather than a variable that can be set.
- One-way bind [checked] to the parent checkbox to set its checked state when all items are selected in the list (replace [(ngModel)] binding in your example)
- One-way bind [indeterminate] to the same checkbox, with the bound condition being
dataSource.data.length <= selectedAssetTypeFilters.length && dataSource.data.length > 0
(good to extract this to a getter to keep the template clean) - Keep the (change) event listener on the parent checkbox to select/deselect all based on its value once clicked.