Angular 如何访问ViewChildren中元素的ID?

Angular 如何访问ViewChildren中元素的ID?,angular,angular-material,Angular,Angular Material,我有一个从ngFor循环创建的一系列mat扩展面板 <mat-expansion-panel *ngFor="let num of countArray" [attr.id]="num + 'exp'" #expPanels> <mat-expansion-panel-header> <mat-panel-title> {{num}} </mat-pa

我有一个从ngFor循环创建的一系列mat扩展面板

<mat-expansion-panel *ngFor="let num of countArray" [attr.id]="num + 'exp'" #expPanels>
    <mat-expansion-panel-header>
        <mat-panel-title>
            {{num}}
        </mat-panel-title>
    </mat-expansion-panel-header>
</mat-expansion-panel>
但是,selectedPanel始终为空

查看this.expPanels内部,我可以看到id不是我在[attr.id]中设置的,它类似于“cdk-accordion-child-300”


如何在我的ViewChildren's QueryList中按id或其他属性进行筛选以获得我想要展开的面板?

我没有找到一个干净的解决方案,因为如果我查询
ElementRef
,我无法访问
MateExpansionPanel
expanded
实例属性,如果我查询组件实例,我无法访问dom元素。所以我问了两个问题:

  @ViewChildren("expPanels", { read: ElementRef })
  expPanelElems: QueryList<ElementRef>;

  @ViewChildren("expPanels")
  expPanels: QueryList<MatExpansionPanel>;
它能用,但我得承认它并不干净。如果您可以在数据数组中查找索引(在
ngFor
中使用)会更简单:

const selectedPanelIdx = this.countArray.findIndex(n => n === 5)

我没有找到干净的解决方案,因为如果我查询
ElementRef
,我无法访问
MatExpansionPanel
expanded
实例属性,如果我查询组件实例,我无法访问dom元素。所以我问了两个问题:

  @ViewChildren("expPanels", { read: ElementRef })
  expPanelElems: QueryList<ElementRef>;

  @ViewChildren("expPanels")
  expPanels: QueryList<MatExpansionPanel>;
它能用,但我得承认它并不干净。如果您可以在数据数组中查找索引(在
ngFor
中使用)会更简单:

const selectedPanelIdx = this.countArray.findIndex(n => n === 5)

你只试过[id]吗?是的。同样的东西你只试过[id]吗?是的。同样的事情
const selectedPanelIdx = this.countArray.findIndex(n => n === 5)