Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open the first attached expansion panel in an Angular Material accordion

Obviously you can use the input expanded on an Angular Material expansion panel to default a particular panel to be opened upon loading. However, I have an accordion where all of the expansion panels are generated dynamically, and all are optional, but I would like for the first panel to be opened.

I could go through each of my ngFors that use templates to generate the panels to see if it exists and then on the first index add the attribute, but there are several loops that pull in templates and it seems messy. I would like to be able to grab some property from the mat-accordion after the view has completed to see which is the first one attached to the accordion and add the attribute, but it looks like it isn't possible. Anyone know if there is some way to do this?

like image 680
Aaron Hazelton Avatar asked Oct 26 '18 15:10

Aaron Hazelton


People also ask

What is accordion in angular material?

An accordion is a component with one or more expandable sections. CDK accordion provides a foundation upon which you can build your own custom accordion component. CDK accordion provides logic for the accordion interaction pattern without any styles.

Can't bind to expanded since it isn't a known property of Mat accordion?

The solution, in this case, is simple. Note that expandedHeight applies to the HEADER, not the accordion. So the fix is to move the attribute to the panel component.


Video Answer


2 Answers

You can use first variable, I made an stackblitz, you can see here.

You can do as this way:

<mat-accordion class="example-headers-align">
  <mat-expansion-panel *ngFor="let item of [1,2,3]; first as isFirst" [expanded]="isFirst">
    <mat-expansion-panel-header>
      <mat-panel-title> {{item}} </mat-panel-title>
    </mat-expansion-panel-header>
    {{item}}
  </mat-expansion-panel>
</mat-accordion>

You can see here the use of the *ngFor variables for more information.

like image 200
Kalamarico Avatar answered Oct 04 '22 11:10

Kalamarico


Have you tried using the ngFor "first" local variable? In this way:

<mat-accordion>
    <mat-expansion-panel *ngFor="let elem of elements; let isFirst = first" [expanded]="isFirst">
         <!--- Something Here --->
    </mat-expansion-panel>
</mat-accordion>
like image 13
DLM Avatar answered Oct 04 '22 10:10

DLM