ineedtoknow
ineedtoknow

Reputation: 1654

Set Expansion Panel to be expanded, but also show animation

I'm working in an Angular 9 project, using material.

I have a component with a mat-accordian with several mat-expansion-panels inside. In the constructor of this component, I look at the router.events to view the url. Then, I set which expansion panel I want to expanded depending on what's in the url route.

The issue is when I do this, the panel is simply open when the page loads (which makes sense). However, I want the animation to play for the expansion panel I set to be open (after the page is loaded). Is there a way to do this?

I'll provide my code, if that helps show what I'm doing:

component.ts:

...
export class Component implements OnInit {
  routerSubscription: Subscription;
  expandPanel1 = false;
  expandPanel2 = false;

  constructor(private router: Router) {
    this.routerSubscription = this.router.events
      .pipe(filter(event => event instanceof NavigationEnd))
      .subscribe(event => {
        if (event["url"].includes("/panel-1")) {
          this.expandPanel1 = true;
        } else {
          this.expandPanel2 = true;
        }
      });
  }
...
setRoute(path: string) {
    this.router.navigate([`home/${path}`]);
  }
...

component.html:

<mat-accordion>
  <mat-expansion-panel [expanded]="expandPanel1" (opened)="setRoute('panel-1')">
    <mat-expansion-panel-header>
      <mat-panel-title>
        Panel 1
      </mat-panel-title>
    </mat-expansion-panel-header>
    panel text filler
  </mat-expansion-panel>
  <mat-expansion-panel [expanded]="expandPanel2" (opened)="setRoute('panel-2')">
    <mat-expansion-panel-header>
      <mat-panel-title>
        Panel 2
      </mat-panel-title>
    </mat-expansion-panel-header>
     panel text filler
  </mat-expansion-panel>
</mat-accordion>

I'll appreciate any help and advise. Thanks!

Upvotes: 1

Views: 1724

Answers (1)

cvb
cvb

Reputation: 793

The constructor will run first before anything else. So you could still get the route info in the constructor but, you should set one of the expandedPanel properties inside of the ngAfterViewInit() lifecycle hook instead of the constructor.

So something like:

   ...
export class Component implements OnInit, AfterViewInit {
  routerSubscription: Subscription;
  expandPanel1 = false;
  expandPanel2 = false;
  urlInfo: string;

  constructor(private router: Router) {
    this.routerSubscription = this.router.events
      .pipe(filter(event => event instanceof NavigationEnd))
      .subscribe(event => {
        urlInfo = event["url"];

      });
  }
...
setRoute(path: string) {
    this.router.navigate([`home/${path}`]);
  }

ngAfterViewInit(){
    if (this.urlInfo.includes("/panel-1")) {
         this.expandPanel1 = true;
    } 
    else {
        this.expandPanel2 = true;
    }
}
...

Upvotes: 2

Related Questions