Diskdrive
Diskdrive

Reputation: 18835

How to access the ID of the elements inside ViewChildren?

I have a series of mat-expansion-panels created from a ngFor loop.

<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>

I'm using ViewChildren to reference them in my .ts code because I'm trying to expand one of them.

  @ViewChildren("expPanels")
  expPanels :QueryList<MatExpansionPanel>;

The reason for that is because I'm trying to select one of them and expand it programmatically.

const selectedPanel = this.expPanels.find(e => e.id == '5exp');   
selectedPanel.expanded=true;

However selectedPanel is always null.

Looking inside this.expPanels, I can see the id isn't what I set in [attr.id], it is something like "cdk-accordion-child-300".

How can I filter by id or some other attribute in my ViewChildren's QueryList to get the panel I want to expand?

Upvotes: 1

Views: 2510

Answers (1)

kai
kai

Reputation: 6887

I have not found a clean solution because if i query the ElementRef, i was unable to access the expanded instance property of MatExpansionPanel and if i query the component instance, i was unable to access the dom element. So i queried both:

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

  @ViewChildren("expPanels")
  expPanels: QueryList<MatExpansionPanel>;

and then used the dom elements to find the correct index and then use this index to toggle the right component instance.

  const selectedPanelIdx = this.expPanelElems
    .toArray()
    .findIndex(e => e.nativeElement.id === "5exp");
  this.expPanels.toArray()[selectedPanelIdx].expanded = true;

It works but i have to admit its not really clean. It would be simpler if you can lookup the index in your data array which is used inside ngFor:

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

Upvotes: 5

Related Questions