我正在尝试创建“多级” mat-select,我想同时使用复选框和单选按钮。
如何使用它来设置汽车属性的示例(假设收音机只能是Digital或FM):
单选按钮仅在选中“父”选项时出现,在这种情况下为单选。
<mat-form-field>
<mat-select [(value)]="viewValue" #multipleSelect (openedChange)="onMultipleChange($event, multipleSelect.selected)" multiple>
<ng-container *ngFor="let property of carProperties">
<!-- If the property does not have any subProperties, display the property. Else display the nested options (subProperties) -->
<mat-option *ngIf="!property.subProperties; else nestedOption" [value]="property.value">
{{property.value}}
</mat-option>
<ng-template #nestedOption>
<mat-checkbox #parentOption>
{{property.value}}
</mat-checkbox>
<ng-container *ngIf="parentOption.checked">
<ng-template #radioOptions>
<mat-radio-group (change)="radioChange($event)"> <!-- Not sure what the ngModel should be here -->
<mat-radio-button *ngFor="let subProperty of property.subProperties" [value]="subProperty.value">
{{subProperty.value}}
</mat-radio-button>
</mat-radio-group>
</ng-template>
</ng-container>
</ng-template>
</ng-container>
</mat-select>
</mat-form-field>
我已经创建了一个解决方案,但是当我选择一个单选按钮时,会出现此异常:
“值必须是多选模式下的数组 在getMatSelectNonArrayValueError(select.es5.js:116) 在MatSelect.push ..“
我认为这是因为mat-select在其单选按钮所在的结构中寻找更改。如何构造垫子组件以获得所需的行为?
答案 0 :(得分:1)
我认为您可能对此有点复杂了。代替使用if-else构造,只需在存在子属性时隐藏或显示复选框即可。这是应该工作的简化版本:
<mat-form-field>
<mat-select [(value)]="viewValue" #multipleSelect multiple>
<ng-container *ngFor="let property of carProperties">
<mat-option [value]="property.value">
{{ property.value }}
</mat-option>
<div *ngIf="property.subProperties && valueSelected(property.value)">
<mat-radio-group>
<mat-radio-button *ngFor="let subProperty of property.subProperties"
[value]="subProperty.value"
style="display: block; padding: 12px 12px 12px 32px;">
{{ subProperty.value }}
</mat-radio-button>
</mat-radio-group>
</div>
</ng-container>
</mat-select>
</mat-form-field>
在.ts文件中:
viewValue: string[] = [ ];
carProperties = [
{ value: 'Stereo' },
{ value: 'Radio',
subProperties: [
{ value: 'Digital' },
{ value: 'FM' }
]
}, { value: 'Child seats' },
{ value: 'Rear camera' }
];
valueSelected(value: string): boolean {
return this.viewValue.indexOf(value) !== -1;
}