Angular mat-selection-list, How to make single checkbox select similar to radio button?

后端 未结 14 1701
北恋
北恋 2021-02-18 21:22

How to make make single checkbox select from mat-selection-list. Similar to radio button which accepts one value from group of values.

14条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-18 21:39

    Bit late to the party, but here's a solution I came up with using a directive to extend the mat-selection-list behaviour.

    import { SelectionModel } from "@angular/cdk/collections";
    import { Directive, Host, Input, OnChanges } from "@angular/core";
    import { MatListOption, MatSelectionList } from "@angular/material/list";
    
    @Directive({
        selector: "mat-selection-list[multiple]"
    })
    export class MatSelectionListMultipleDirective implements OnChanges {
        private matSelectionList: MatSelectionList;
    
        @Input()
        public multiple: boolean;
    
        constructor(@Host() matSelectionList: MatSelectionList) {
            this.matSelectionList = matSelectionList;
        }
    
        public ngOnChanges(): void {
            if (this.multiple) {
                this.matSelectionList.selectedOptions = new SelectionModel(true, this.matSelectionList.selectedOptions.selected);
            }
            else {
                let selected = this.matSelectionList.selectedOptions.selected.splice(0, 1);
                this.matSelectionList.selectedOptions = new SelectionModel(false, selected);
            }
        }
    }
    

    Which you can use like this...

    
    ...
    
    

    Ideally we would have a radio control instead of the checkbox, but I think this workaround is OK until the angular material team support this officially.

提交回复
热议问题