[英]Angular - using ngFor to create an accordion menu. Needs to auto-close and open another upon click
[英]Angular Material expansion panel API in ngFor, how to auto-close
我最近在我的 angular 项目中添加了 Angular Material 手风琴组件。 在 API 中,他们使用提供的示例来自动关闭面板: https : (opened) = panelStateOpen
<-- 看这里(在模板中执行(opened) = panelStateOpen
并在成分)
我这样做了,但是因为我循环遍历menuItems
的信息,有两个组件,然后注入我的扩展面板,所以panelOpenState
不正确。
现在,我有
<mat-accordion *ngFor="let menuItem of menuItems">
<confmenu menuItem={{menuItem}}></confmenu>
</mat-accordion>
在我的父模板和我的 confmenu(子模板)中:
<mat-expansion-panel (opened)="panelOpenState=true" (closed)="panelOpenState=false">
<mat-expansion-panel-header>
<mat-panel-title>
{{menuItem}}
</mat-panel-title>
<mat-panel-description>
{{menuDescription}}
</mat-panel-description>
</mat-expansion-panel-header>
<mat-form-field>
<mat-select (change)="selectConfig($event.value)">
<mat-option *ngFor="let option of menuOptions" [value]="option" (click)="selectConfig(option)">
{{option}}
</mat-option>
</mat-select>
</mat-form-field>
</mat-expansion-panel>
在孩子的组件中,我有panelOpenState = false;
整个 ts 是
/** @title Basic menu */
@Component({
selector: 'confmenu',
templateUrl: './confmenu.component.html',
styleUrls: ['./confmenu.component.scss']
})
export class ConfigurationMenu implements OnInit, OnDestroy {
@Input() menuItem: string;
panelOpenState = false;
constructor() {}
ngOnInit() {
}
ngOnDestroy() {
//blank for now
}
selectConfig(value:string){
this.selectedConfig = value;
this._menuService.changeSelectedConfig(this.selectedConfig);
this._menuService.populateSelectedConfigConfigurations(this.selectedConfig);
}
}
关于如何使面板在单击另一个面板时关闭的任何想法? 现在,它们都在单击另一个时保持打开状态。
最简单的自动关闭项目列表在 mat-expansion 面板中表示 - 是存储面板项目的当前打开 id。
组件.html
<ng-container *ngFor="let item of items">
<mat-expansion-panel
[expanded]="item.id === currentOpenedItemId"
(opened)="handleOpened(item)"
>
</ng-container>
组件.ts
...
currentOpenedItemId: number;
public handleOpened(item): void {
this.currentOpenedItemId = item.id;
}
您也可以在获取数据时设置初始值 - 打开第一个面板
使用此示例https://stackblitz.com/angular/olmedrdbamo?file=src%2Fapp%2Fexpansion-steps-example.ts使用 *ngFor 索引作为“步骤”
<mat-accordion *ngFor="let menuItem of menuItems; let index = index">
<confmenu menuItem={{menuItem}} [index]="index"></confmenu>
</mat-accordion>
添加@Input() index: number;
到组件
你可以像这样调整那个样本
<mat-expansion-panel [expanded]="step === index" (opened)="setStep(index)" hideToggle>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.