[英]Using mat-option AND mat-radio-button in a mat-select or mat-selection-list
我正在嘗試創建一個“多級”mat-select,我想同時使用復選框和單選按鈕。
它是如何用於設置汽車屬性的示例(假設無線電只能是數字或FM):
只有在選中“父”選項時才會出現單選按鈕,在本例中為Radio。
<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>
我已經創建了一個解決方案但是當我選擇一個單選按鈕時,我會得到這個異常:
“在MatSelect.push的getMatSelectNonArrayValueError(select.es5.js:116)中,值必須是多選模式中的數組..”
我認為這是因為mat-select在其結構中尋找變化,其中放置了單選按鈕。 如何構建墊組件以獲得所需的行為?
我想你可能有點過分復雜了。 當存在子屬性時,只需隱藏或顯示復選框,而不是使用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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.