Выполнение прокрутки строк таблицы данных углового материала при сохранении липкого заголовка - PullRequest
0 голосов
/ 30 мая 2019

Демонстрация стека Blitz

У меня проблемы с выяснением того, как заставить мой код работать так, как нужно.

Как показывает демонстрация, у меня есть таблица, в которой при нажатии кнопки добавления добавляется новая строка. Как только строки таблицы достигают определенной высоты (например, после добавления 5 строк), мне нужна вертикальная полоса прокрутки для отображения, и в то же время мне нужно поддерживать липкий заголовок. В основном мне нужно установить строки таблицы на фиксированную высоту.

Прикрепленный снимок экрана показывает, где я хочу отображать полосу прокрутки. Извиняюсь за шаткую изюминку.

HTML выглядит так

<div class="table-container">
  <table mat-table [dataSource]="dataSource">
    <ng-container matColumnDef="category">
      <th mat-header-cell *matHeaderCellDef >Category</th>
      <td mat-cell *matCellDef="let code" >
        <mat-form-field class="code">
          <mat-select>
            <mat-option *ngFor=" let category of categories" [value]="category.code" class="dropdownpPopUp"  (keydown.ArrowDown)="onDown()">{{category.code}}</mat-option>
          </mat-select>
        </mat-form-field>
      </td>
    </ng-container>
    <ng-container matColumnDef="type">
      <th mat-header-cell *matHeaderCellDef>Type</th>
      <td mat-cell *matCellDef="let code" >
        <mat-form-field class="type">
          <mat-select >
            <mat-option *ngFor=" let type of types" [value]="type.code" class="dropdownpPopUp"  (keydown.ArrowDown)="onDown()">{{type.code}}</mat-option>
          </mat-select>
        </mat-form-field>
      </td>
    </ng-container>
    <ng-container matColumnDef="additionalCode" class="parent" >
      <th mat-header-cell *matHeaderCellDef>Additional Code</th>
      <td mat-cell *matCellDef="let element" class="parent" >
        <mat-form-field class="type">
          <input matInput (keyup)="toggleLookup($event)" autocomplete="off" (keydown.ArrowDown)="onDown()">
        </mat-form-field>
        <div *ngIf="expanded" class="child">Yah it expanded
          <button (click)="expanded = false">Close</button>
        </div>
      </td>
    </ng-container>
    <ng-container matColumnDef="ref">
      <th mat-header-cell *matHeaderCellDef>Reference</th>
      <td mat-cell *matCellDef="let element" >
        <mat-form-field>
          <input matInput [(ngModel)]="element.type"  (keydown.ArrowDown)="onDown()" autocomplete="off">
        </mat-form-field>
      </td>
    </ng-container>
    <ng-container matColumnDef="add">
      <th mat-header-cell *matHeaderCellDef>
        <button mat-icon-button (click)="addRow()" matTooltip="Add Row">
          <mat-icon>add</mat-icon>
        </button>
      </th>
      <td mat-cell *matCellDef="let code; let i = index;">
        <button mat-icon-button (click)="removeAt(i)" matTooltip="Remove Row">
          <mat-icon>clear</mat-icon>
        </button>
      </td>
    </ng-container>
    <tr mat-header-row *matHeaderRowDef="columns"></tr>
    <tr mat-row *matRowDef="let rows; columns: columns;"></tr>
  </table>
   <div *ngIf="dataSource.filteredData.length > 0" > <mat-paginator [pageSizeOptions]="[5]" showFirstLastButtons class="paginator"></mat-paginator></div>
</div>

Функция добавления компонента

addRow() {
    this.doAddRow();
    this.expanded = false;
  }
  private doAddRow() {
    ELEMENT_DATA.push({ code: '', type: '', reference: '' });
    this.dataSource = new MatTableDataSource(ELEMENT_DATA);
  }

enter image description here

Ответы [ 2 ]

0 голосов
/ 30 мая 2019

На самом деле, угловой материал документация охватывает это.

Используя position: sticky style, строки и столбцы таблицы могут быть исправлено, чтобы они не покидали область просмотра даже при прокрутке. Таблица предоставляет входные данные, которые будут автоматически применять правильный CSS стиль, чтобы строки и столбцы стали липкими.

Вам просто нужно внести следующие изменения в ваш тег <tr> с помощью директивы mat-header-row.

<tr mat-header-row *matHeaderRowDef="columns; sticky: true"></tr>

Кроме того, вам необходимо отредактировать класс контейнера вокруг таблицы, чтобы включить следующие свойства:

.table-container {
  height: 400px;
  overflow: auto;
  /*
  other CSS properties
   */
}

Это позволит вашему материалу иметь клейкий заголовок. Вот демоверсия 1018 *, предоставленная официальной документацией.

0 голосов
/ 30 мая 2019

что вам нужно сделать, это добавить div за пределы вашего стола и предоставить min-height собственность.

app.component.css

.main-table{
  max-height:42vh;
  overflow-y:scroll;
  overflow-x:hidden;
}

app.component.html

<ol>
  <li>Select + to add rosw</li>
</ol> 
<p>After 5 new rows added a vertical scroll bar should aprear and when srolling the header row should still be visible</p>
<div class="table-container">
  <div class="main-table">
  <table mat-table [dataSource]="dataSource">
    <ng-container matColumnDef="category">
      <th mat-header-cell *matHeaderCellDef >Category</th>
      <td mat-cell *matCellDef="let code" >
        <mat-form-field class="code">
          <mat-select>
            <mat-option *ngFor=" let category of categories" [value]="category.code" class="dropdownpPopUp"  (keydown.ArrowDown)="onDown()">{{category.code}}</mat-option>
          </mat-select>
        </mat-form-field>
      </td>
    </ng-container>
    <ng-container matColumnDef="type">
      <th mat-header-cell *matHeaderCellDef>Type</th>
      <td mat-cell *matCellDef="let code" >
        <mat-form-field class="type">
          <mat-select >
            <mat-option *ngFor=" let type of types" [value]="type.code" class="dropdownpPopUp"  (keydown.ArrowDown)="onDown()">{{type.code}}</mat-option>
          </mat-select>
        </mat-form-field>
      </td>
    </ng-container>
    <ng-container matColumnDef="additionalCode" class="parent" >
      <th mat-header-cell *matHeaderCellDef>Additional Code</th>
      <td mat-cell *matCellDef="let element" class="parent" >
        <mat-form-field class="type">
          <input matInput (keyup)="toggleLookup($event)" autocomplete="off" (keydown.ArrowDown)="onDown()">
        </mat-form-field>
        <div *ngIf="expanded" class="child">Yah it expanded
          <button (click)="expanded = false">Close</button>
        </div>
      </td>
    </ng-container>
    <ng-container matColumnDef="ref">
      <th mat-header-cell *matHeaderCellDef>Reference</th>
      <td mat-cell *matCellDef="let element" >
        <mat-form-field>
          <input matInput [(ngModel)]="element.type"  (keydown.ArrowDown)="onDown()" autocomplete="off">
        </mat-form-field>
      </td>
    </ng-container>
    <ng-container matColumnDef="add">
      <th mat-header-cell *matHeaderCellDef>
        <button mat-icon-button (click)="addRow()" matTooltip="Add Row">
          <mat-icon>add</mat-icon>
        </button>
      </th>
      <td mat-cell *matCellDef="let code; let i = index;">
        <button mat-icon-button (click)="removeAt(i)" matTooltip="Remove Row">
          <mat-icon>clear</mat-icon>
        </button>
      </td>
    </ng-container>
    <tr mat-header-row *matHeaderRowDef="columns"></tr>
    <tr mat-row *matRowDef="let rows; columns: columns;"></tr>
  </table>
  </div>
   <div *ngIf="dataSource.filteredData.length > 0" > <mat-paginator [pageSizeOptions]="[5]" showFirstLastButtons class="paginator"></mat-paginator></div>
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...