How to make single checkbox select from mat-selection-list
. Similar to radio button which accepts one value from group of values.
Components >= 9.1.0
Selection list now supports a single selection mode directly. Enable it with the multiple input set to false.
<mat-selection-list [multiple]="false">...
Components < 9.1.0
You have to set SelectionModel for selectedOptions property of component reference on init.
@ViewChild(MatSelectionList, {static: true})
private selectionList: MatSelectionList;
ngOnInit() {
this.selectionList.selectedOptions = new SelectionModel<MatListOption>(false);
}
MatSelectionList api
This way you can define initially selected values too.
export declare class SelectionModel<T> {
constructor(_multiple?: boolean, initiallySelectedValues?: T[], _emitChanges?: boolean);
}
GitHub api
What you'd need to do is:
selectionChange
deselectAll()
method I modified the original example from the API page, added a ViewChild for the selection list and subscribe to the selectionChange
event.
ngOnInit(){
this.shoes.selectionChange.subscribe((s: MatSelectionListChange) => {
this.shoes.deselectAll();
s.option.selected = true;
});
// WARNING: Don't attempt to do the following to select the value
// it won't trigger the value change event so it will remain unchecked
// this.shoes.selectedOptions.select(s.option);
// If interested source is here :
// https://github.com/angular/material2/blob/fa4ddd0a13461b2f846e114fd09f8f4e21b814b1/src/lib/list/selection-list.ts
}
Working sample: https://stackblitz.com/edit/angular-i3pfu2-6n5cnt
See also: https://material.angular.io/components/list/api
To begin with, mat-selection-list
is not suitable for a single-value selection, as it veers away from its intent:
Checkboxes in a group are non-exclusive options; more than one checkbox in a group can be checked at any given time
What you're looking for is the radio-button element itself, because semantically it stands for:
A radio button is one of a group of controls representing mutually-exclusive choices
Unfortunately Angular Material does not include a mat-radio-list
component. But you can still achieve it by including a mat-radio-button
inside you mat-list-item
. This will provide best practice, as it denotes to the user that the list in view is intended for mutually-exclusive choices (unlike checkboxes that denote multiple-choice). And since the radio buttons are updating a single variable, you get exclusivity:
<mat-list role="list">
<mat-list-item role="listitem" *ngFor="let x of [0,1,2]; let i = index">
<mat-radio-button [value]="i" (change)="selection = $event.value">
Item {{x}}
</mat-radio-button>
</mat-list-item>
</mat-list>
Check a Stackblitz
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With