0

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:

link to example image

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 class="filter-content">

<mat-tree [dataSource]="dataSource" [treeControl]="treeControl" class="example-tree">

<!-- This is the tree node template for leaf nodes -->

<mat-tree-node *matTreeNodeDef="let node" matTreeNodeToggle>

<li class="mat-tree-node">

<mat-checkbox [(ngModel)]="node.checked" (change)="onFilterUpdate(node, 'assettype');" title="{{node.label}}">

How can I do this?

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.