首页 > 解决方案 > 带有选项组的角度材料多选下拉列表仅从每个组中选择一项?

问题描述

我正在尝试使用选项组实现多选下拉列表,并且用户只能从多选下拉列表中的每个组中选择一个项目。

<mat-form-field class="kb-article-filter-field" floatLabel="never">
                <mat-select name="searchSettings" multiple>
                  <mat-optgroup *ngFor="let group of textSearchTypes" [label]="group.name">
                    <mat-option *ngFor="let option of group.options" [value]="option.value">
                      {{option}}
                    </mat-option>
                  </mat-optgroup>
                </mat-select>
              </mat-form-field>

textSearchTypes = [
    {
        name: 'searchName', 
        options: [
            { name: 'test', value: 'test' },
            { name: 'test1', value: 'test1' },
            { name: 'test2', value: 'test2' }
        ]
    },
    {
        name: 'searchId', 
        options: [
            {name:'testId', value:'testId'},
            {name:'testId1', value:'testId1'},
            {name:'testId2', value:'testId1'}
        ]
    }
  ];

任何人都可以帮助如何在多选下拉列表中从每个组中只选择一个项目吗?

标签: javascriptangular-materialangular7

解决方案


将 valueChange 事件附加到您的 mat-select。在您附加的方法中,您执行以下操作:

  • 如果您的组中选择了一个项目,请禁用该组中的其他项目。
  • 如果您的组中没有选择任何项目,请启用该组中的所有项目。

selectionChanged() {
  // Perform enable / disable for your options
}
<mat-form-field class="kb-article-filter-field" floatLabel="never">
  <mat-select name="searchSettings" multiple (valueChange)=selectionChanged()>
    <mat-optgroup *ngFor="let group of textSearchTypes" [label]="group.name">
      <mat-option *ngFor="let option of group.options" [value]="option.value">
        {{option}}
      </mat-option>
    </mat-optgroup>
  </mat-select>
</mat-form-field>


推荐阅读