ID材料手风琴打开关闭面板

时间:2019-01-01 01:14:13

标签: angular angular-material accordion

我能够使用材质手风琴https://material.angular.io/components/expansion/overview#accordion通过分配的ID来控制,从而打开/关闭单个面板。

2 个答案:

答案 0 :(得分:0)

好的,我尝试了一种解决方法,StackBlitz HERE

我还没有找到使用ID进行面板控制的方法,但是可以使用变量。 在这里,我使用activePanel,它根据事件而取一个值(1表示button_1,2表示button_2,...)。

<button mat-raised-button (click)="activePanel = 1">Open 1</button>
<button mat-raised-button (click)="activePanel = 2">Open 2</button>
<button mat-raised-button (click)="activePanel = 3">Open 3</button>

在面板中使用ngOnChanges函数,它将根据您的变量打开面板。

ngOnChanges() {
    if(this.panelState2 == 2) {this.panelState = true;}
    else {this.panelState = false;}
}

panelState变量是使用[expanded]打开或关闭面板的布尔值。

<mat-expansion-panel [expanded]="panelState">
  <mat-expansion-panel-header>
    <mat-panel-title>
      Title Panel
    </mat-panel-title>
  </mat-expansion-panel-header>
  <p>Accedat huc suavitas quaedam oportet sermonum atque morum,...</p>
</mat-expansion-panel>

我希望这会对您有所帮助。

演示:

enter image description here

答案 1 :(得分:0)

好的,所以我尝试了另一种解决方案StackBlitz HERE

这次,我设法使用ID进行面板控制。 在这里,我在每个垫扩展面板上使用唯一的ID(对于panel_1,#first,对于panel_2,#second,...)。

<mat-accordion multi="true">
  <mat-expansion-panel #first></mat-expansion-panel>
  <mat-expansion-panel #second></mat-expansion-panel>
  <mat-expansion-panel #third></mat-expansion-panel>
</mat-accordion>

我还使用按钮来控制这些面板而无需与之交互。

<button mat-raised-button (click)="changeState1()">ON/OFF Panel_1</button>
<button mat-raised-button (click)="changeState2()">ON/OFF Panel_2</button>
<button mat-raised-button (click)="changeState3()">ON/OFF Panel_3</button>

在TypeScript代码中,您使用@ViewChild检索面板ID,以便对其进行控制。

@ViewChild('first') first: MatExpansionPanel;
@ViewChild('second') second: MatExpansionPanel;
@ViewChild('third') third: MatExpansionPanel;

然后,我创建了一个函数来根据其ID和状态,打开一个以关闭垫子扩展面板。

changeState1() {
  if(this.first.expanded){
    this.first.close();
  } else {
    this.first.open();
  }
}

changeState2() {...}

PS:<mat-accordion multi="true">允许同时打开多个面板。

演示:

enter image description here

相关问题