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

后端 未结 14 1714
北恋
北恋 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:30

    What you'd need to do is:

    • Listen for selectionChange
    • Clear all with deselectAll() method
    • Set it as selected again

    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/fa4ffffd0a13461b2f846e114fd09f8f4e21b814b1/src/lib/list/selection-list.ts
    }
    

    Working sample: https://stackblitz.com/edit/angular-i3pfu2-6n5cnt

    See also: https://material.angular.io/components/list/api

提交回复
热议问题