简体   繁体   中英

Angular how to make table header sticky

I am making a p-table that needs to make the title of it stick to the top while scrolling down to see the data below. Now, I've researched some sites that said instead of using <td/> , we should use <tr/> . I changed the wrapping layer of html to <tr/> but still doesn't work. I also tried different ways of css writing but they all fail to show the result. I have been stuck in the problem for a whole day. Any ideas on my codes is a great help.

Here are my codes: (html)

<div>
  <p-table [columns]="columnName" [value]="reslts" selectionMode="single" [autoLayout]="true" class="table">
    <ng-template pTemplate="colgroup" let columns>
      <colgroup>
        <col *ngFor="let col of columns" [style.width]="col.width">
      </colgroup>
    </ng-template>

    <ng-template pTemplate="header" let columns>
      <tr>
        <th
          class="p-1"
          *ngFor="let col of columns"
          [style.width]="col.width"
          [pSelectableColumn]="col.field"
        >
          {{col.header}}
        </th>
      </tr>
    </ng-template>

    <ng-template 
      pTemplate="body" 
      let -rowData let-columns="columns" 
      let-rowIndex="rowIndex"
    >
      <tr [pSelectableRow]="rowData">
        <td> {{rowData.Monday}}</td>
        <td>{{rowData.Tuesday}}</td>
        <td>{{rowData.Wednesday}}</td>
        ........
      </tr>
    </ng-template>
  </p-table>
</div>

my css code:

.td.header{
 position:sticky;
 top:0px;
}

try this

<div class="table-container">
    <!-- table markup -->
</div>

<style>
    .table-container {
        position: relative;
        /* max-height: some value; */
    }

    .td.header {
        position: absolute;
        top: 0px;

        /* if header shrinks due to absolute positioning */
        /* left: 0px; */
        /* right: 0px; */

        /* or  */
        /* width: 100%; */

        /* if header goes below content */
        /* z-index: some high enough value; */
    }
</style>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM