Helene
Helene

Reputation: 421

Hide/show options of optgroup (angular material) with a click

I have a list of interventions, interv1, interv2, interv3 ... for each of these interventions, i have a list of elements, it gives this following :

<mat-optgroup *ngFor="let interv of listIntervDiag" [label]="interv.name" [disabled]="interv.disabled">
         <mat-option *ngFor="let element of interv.listElement" [value]="option">
                      {{ element }}
         </mat-option>
</mat-optgroup>

I would like to do a tree (like here https://material.angular.io/components/tree/overview) but in the select element.

At the beginning I show only my OptGroup, when click on one of these group options, I want to show the list of elements related to (the options)

Is it possible to do that ?

maybe not ... I guess the solution could be to do 2 select, and according to the selection of the first select it shows differents element in the second one (which is disable if nothing is selected in the first one).

Thanks for your help

Upvotes: 1

Views: 2654

Answers (2)

Arturo Muller
Arturo Muller

Reputation: 31

Adding to the hide show response to stop the list from scrolling when you select items. Add cdk virtual scrolling

  <mat-select [value]="selections | async" multiple >
    <cdk-virtual-scroll-viewport [itemSize]="10">
      <mat-optgroup *cdkVirtualFor="let interv of listIntervDiag"; let i = index;">
        <mat-label (click)="activeToggler(i)">{{interv.name}}</mat-label>
        <mat-option [class.active]="i === activeClassIndex"
        *ngFor="let childOption of interv.children" [value]="childOption">
          {{childOption.name}}
        </mat-option>
      </mat-optgroup>
    </cdk-virtual-scroll-viewport>
  </mat-select>

& css

cdk-virtual-scroll-viewport {
  height: 256px;
}

Upvotes: 2

Ravi Chandhar P.B
Ravi Chandhar P.B

Reputation: 31

In mat-option tag

[class.active]="i === activeClassIndex"

In mat-optgroup tag

*ngFor = "let interv of listIntervDiag let i = index;" (click)="activeToggler(i)"

In .ts file

activeToggler(selectedIndex) {
    this.activeClassIndex = (this.activeClassIndex == selectedIndex) ? null : selectedIndex;
   }

in.css file

.mat-optgroup {
    .mat-option {
         display: none;
          &.active {
              display: flex !important;
          }
    }
 }

Upvotes: 3

Related Questions