Angular mat-selection-list,如何使单个复选框选择类似于单选按钮?

use*_*427 15 angular-material angular

如何从mat-selection-list中选择make single复选框.类似于单选按钮,它从值组中接受一个值.

hov*_*ado 25

这与材料5-7一起使用:

@ViewChild(MatSelectionList, {static: true})
private selectionList: MatSelectionList;

ngOnInit() {
    this.selectionList.selectedOptions = new SelectionModel<MatListOption>(false);
}
Run Code Online (Sandbox Code Playgroud)


Sim*_*ver 13

我不明白是谁想出了selectionChange现在的工作方式.我不明白为什么没有明显的方法使它成为一个选择,我也不明白为什么我不能禁用该复选框.

你需要做的是:

  • 听着 deselectAll()
  • selectionChange方法清除所有
  • 再次将其设置为选中状态

我从API页面修改了原始示例,为选择列表添加了ViewChild并订阅了该selectionChange事件.

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
}
Run Code Online (Sandbox Code Playgroud)

工作样本:https: //stackblitz.com/edit/angular-i3pfu2-6n5cnt

另见:https: //material.angular.io/components/list/api


Asa*_*nat 6

首先,mat-selection-list不适合单值选择,因为它偏离了其意图

组中的复选框是非排他性选项;可以在任何给定时间选中一个组中的多个复选框

您正在寻找的是单选按钮元素本身,因为在语义上它代表

单选按钮是代表互斥选择的一组控件之一

遗憾的是,Angular Material不包含mat-radio-list组件。但是您仍然可以通过将mat-radio-button内部包含在内来实现它mat-list-item。这将提供最佳实践,因为它向用户表明视图中的列表旨在用于相互排斥的选择(与表示多项选择的复选框不同)。并且由于单选按钮正在更新单个变量,因此您具有排他性:

<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>
Run Code Online (Sandbox Code Playgroud)

检查堆叠闪电战

  • 我同意,如果是单选,则应该使用单选按钮而不是复选框 - 毕竟,这就是单选样式的要点 - 但“mat-radio-button”在“mat-”内部工作这有点巧合list-item`,如果您使用更高级的功能,可能会崩溃。例如,尝试将“matListIcon”添加到您的列表中 - 现在单选按钮被限制在“行容器”内,并且一旦您单击它就会变得疯狂。我认为我们需要一个“mat-radio-list”。 (2认同)