angular-cli: Open/Close 来自 ts 文件的 MatExpansionPanel

angular-cli: Open/Close MatExpansionPanel from ts file

我有一个 angular-cli 组件,其中包含多个 mat-expansion-panel (https://material.angular.io/components/expansion/overview)。

我需要 open/close 来自 ts 文件的扩展面板,我不确定如何访问各个扩展面板上的属性。我收到错误

ERROR TypeError: Cannot read property 'open' of undefined

我正在尝试访问此元素

<mat-expansion-panel #first="matExpansionPanel">

使用

first: MatExpansionPanel;
...
this.first.open();

这是我的

import { Component, OnInit } from '@angular/core';
import { Category } from '@app/model/Enums';
import { ActivatedRoute } from '@angular/router';    
import { MatExpansionPanel } from '@angular/material';

@Component({
  selector: 'app-some-component',
  templateUrl: './some-component.component.html',
  styleUrls: ['./some-component.component.scss']
})

export class SomeComponent implements OnInit {

  sub: any;
  first: MatExpansionPanel; 
  second: MatExpansionPanel; 

  constructor(private activateRoute: ActivatedRoute) {
    this.sub = this.activateRoute.params.subscribe(params => {

      // Open the MatExpansionPanel with id "first"
      this.first.open();

      // Open the MatExpansionPanel with id "second"
      this.second.open();
  }

  ngOnInit() {
  }

}

这是我的 HTML

<mat-accordion>
    <mat-expansion-panel #first="matExpansionPanel">
        <mat-expansion-panel-header>
            <mat-panel-title>
                Title 1
            </mat-panel-title>
            <mat-panel-description>
            </mat-panel-description>
        </mat-expansion-panel-header>
        <p>Content</p>
    </mat-expansion-panel>
</mat-accordion>
<br />
<mat-accordion>
    <mat-expansion-panel #second="matExpansionPanel">
        <mat-expansion-panel-header>
            <mat-panel-title>
                Title 2
            </mat-panel-title>
            <mat-panel-description>
            </mat-panel-description>
        </mat-expansion-panel-header>
        <p>Content</p>
    </mat-expansion-panel>
</mat-accordion>

知道怎么做吗?

首先,您必须使用 @ViewChild.

实例化您的扩展面板
@ViewChild('first', {static: true, read: MatExpansionPanel}) first: MatExpansionPanel;

然后如果你想执行'open'功能,你只能在ngAfterViewInit功能中设置页面后才能执行。

ngAfterViewInit() {
  this.first.open();
}