要解决Angular Material手风琴在首次渲染时不会关闭的问题,可以通过设置默认打开的面板索引来强制关闭它。
首先,在组件的类中添加一个变量来保存默认打开的面板索引:
import { Component } from '@angular/core';
@Component({
selector: 'app-accordion',
templateUrl: './accordion.component.html',
styleUrls: ['./accordion.component.css']
})
export class AccordionComponent {
defaultPanelIndex: number = -1;
}
然后,在HTML模板中为手风琴组件绑定defaultPanelIndex
变量:
Panel 1
This is the content of panel 1.
Panel 2
This is the content of panel 2.
在上述示例中,[selectedIndex]="defaultPanelIndex"
将defaultPanelIndex
变量绑定到手风琴组件的selectedIndex
属性上。defaultPanelIndex
的初始值为-1,这将导致所有面板都关闭。当手风琴首次渲染时,会强制关闭所有面板。
如果你想要默认打开一个面板,只需将defaultPanelIndex
设置为该面板的索引即可。例如,将defaultPanelIndex
设置为0将默认打开第一个面板。
defaultPanelIndex: number = 0;
这样,当手风琴首次渲染时,第一个面板将被打开,其他面板将保持关闭状态。