我正在尝试使用带有一组单选按钮的mat-accordion
,每个面板一个。如果选择了单选按钮,则展开该面板,关闭其他单选按钮,然后按预期取消选择其他单选按钮。
我的单选按钮按预期工作,但面板在点击时会正常伸缩;我试图让他们只有在选中单选按钮的情况下才能展开。
我试过禁用面板,但这会禁用它的内容,包括单选按钮。
我怎么能让它只根据它的单选按钮状态展开/折叠?
<mat-accordion hideToggle="true">
<mat-expansion-panel>
<mat-expansion-panel-header>
<mat-radio-button
(change)="onChange($event)"
name="services"
id="service1"
value="service1"
>
<mat-panel-title> Service 1</mat-panel-title>
</mat-radio-button>
</mat-expansion-panel-header>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Rem, possimus
aliquam sunt dolorem nam saepe esse laboriosam eius quae quaerat!
</mat-expansion-panel>
<mat-expansion-panel>
<mat-expansion-panel-header>
<mat-radio-button
(change)="onChange($event)"
name="services"
id="service2"
value="service2"
>
Service 2</mat-radio-button
>
</mat-expansion-panel-header>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Rem, possimus
aliquam sunt dolorem nam saepe esse laboriosam eius quae quaerat!
</mat-expansion-panel>
</mat-accordion>
{{ selectedService }}
组件:
selectedService = 'service1';
onChange(event) {
event.source.checked = true;
this.selectedService = event.source.value;
}
Stacklitz演示
您必须禁用mat-expansion-panel
(它仍然可以通过编程方式打开(。此外,你必须修复一些CSS样式,因为出于某种原因,当你点击单选按钮时,它会向上移动
.fix-radio-position .mat-expansion-panel
.mat-expansion-panel-header mat-panel-description
.mat-radio-button {
line-height: 2;
}
现在将css类应用于手风琴元素:
<mat-accordion class="fix-radio-position" hideToggle="true">
...
</mat-accordion>
您必须通过添加disabled
属性来禁用面板,并在每个面板上放置一个模板引用变量,这样我们就可以通过单击单选按钮将它们作为参数传递:
<mat-expansion-panel #panel1 disabled>
...
</mat-expansion-panel>
<mat-expansion-panel #panel2 disabled>
...
</mat-expansion-panel>
稍微更改onChange
事件的签名,以便可以将父面板作为参数传递:
<mat-radio-button (change)="onChange($event, panel1)">Service 1</mat-radio-button>
...
<mat-radio-button (change)="onChange($event, panel2)">Service 2</mat-radio-button>
最后,您的onChange
方法变为:
onChange(radio: MatRadioChange, panel: MatExpansionPanel) {
panel.open();
}