1

我正在使用材料在 Angular 9 项目中工作。

我有一个内部mat-accordian有几个mat-expansion-panels 的组件。在constructor这个组件中,我router.events查看url. 然后,我根据 url 路由中的内容设置要扩展的扩展面板。

问题是当我这样做时,面板在页面加载时只是打开(这是有道理的)。但是,我希望为我设置为打开的扩展面板播放动画(加载页面后)。有没有办法做到这一点?

我将提供我的代码,如果这有助于显示我在做什么:

组件.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}`]);
  }
...

组件.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>

我将不胜感激任何帮助和建议。谢谢!

4

1 回答 1

2

构造函数将首先运行。因此,您仍然可以在构造函数中获取路由信息,但是,您应该在 ngAfterViewInit() 生命周期挂钩而不是构造函数中设置扩展面板属性之一。

所以像:

   ...
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;
    }
}
...
于 2020-04-29T13:52:55.670 回答