Angular materials tree – how to have some checkboxes exclusive with each other and others can be checked simultaneously
Problem Description:
I am following this to get tree based dropdowns with checkboxes in my app. My code uses the code from example 1 to build the checkbox trees, the only difference being the data.
I want to have it so that for some of the data, only one checkbox option can be selected (meaning the other choices are deselected when checked) and other data allows as many checkboxes as the user wants. In the demo material from the above it allows as many checks as you want, and my current implementation works in the same way.
For example see the following data:
const TREE_DATA = {
Groceries: {
'Almond Meal flour': null,
'Organic eggs': null,
'Protein Powder': null,
'Fruits' : {
'Apple' : null,
'Berries' : null,
'Orange' : null,
'Quantity:' :{
'10 grams' : null,
'20 grams' : null,
'30 grams' : null,
},
},
},
Other : {
'Lawnmower' : null,
'Demister' : null,
'Trowel' : null,
};
From this example, if I wanted only the data under "Quantity" to use radio buttons (meaning only 1 can be checked at a time) but the rest of the data used checkboxes that allowed for multiple selection, how could I go about this?
Thanks
Solution – 1
Within the
mat-tree-node
element I added both a mat-checkbox and mat-radio-button, with each of these containing a if statement
*ngIf="isQuantityOption(node)"
where isQuantityOption where works as such
isQuantityOption(node: TodoItemFlatNode): boolean{
return (this.getParentNode(node)?.item == 'Quantity:');
}
This means that for each node in my array it is check whether the parent node is "Quantity:". If so, it creates a radio button rather than a checkbox