How to prevent a mat-select from closing in a dynamically rendered mat-table with Angular Material 11?

35 views Asked by At

I have this table that shows different columns depending on the selected options in the mat-select:

  <table
    mat-table
    [dataSource]="dataSource"
    matSort>
    <ng-container
      *ngFor="let column of _displayedColumns"
      [matColumnDef]="column">
      <ng-container>
        <th
          mat-header-cell
          *matHeaderCellDef>
          <mat-select
            [formControl]="columnsSelector"
            multiple
            class="column-show-selector"
            (selectionChange)="columnChange($event)">               
            <mat-option
              *ngFor="let menuItem of matMenuItems"
              [value]="menuItem">
              {{ menuItem }}
            </mat-option>
          </mat-select>
        </th>
        //rest of code

And in the .ts, I have this code:

  stashedColumns: string[] = [];

  columnChange(e: any) {
    this.stashedColumns = e.value;
    const columnsSelectorIndex =
      this.displayedColumns.indexOf('columnsSelector');
    this.stashedColumns.splice(columnsSelectorIndex, 0, 'columnsSelector');
    this._displayedColumns = this.stashedColumns;
  }

In this code, the columns are created dynamically based on the value of _displayedColumns

When I check/uncheck an option in the mat-select, the value of _displayedColumns changes. This is what I want, as I want to filter the displayed columns, but the problem is that the mat-select is closing because of the re-render of the table.

Is it possible to achieve the same functionality, but keep the mat-select open, so that the user does not have to open the mat-select continuously? I only want the mat-select to close when the user clicks outside.

0

There are 0 answers