32
loading...
This website collects cookies to deliver better user experience
position: sticky
CSS property to make an element sticky. Read more about sticky positioning at MDN..sticky {
position: sticky;
left: 0;
}
top
, right
, bottom
, or left
should be specified.sticky
class to the column.sticky
class to both of the columns. This is how it looks if you did so:left:0
..company {
position: sticky;
left: 0px;
}
.manager {
position: sticky;
left: 120px; // <-- width of the company column
}
left
property value.left
value, we need to find the x
value of the column. If we look at the first column Company and get its offset from the left side.x
value to be 0
but we get 85
here. This is because the x
value is calculated from the left side of the window to the column. For getting the left threshold of the column with respect to the table, we need to find the x
value of the table. Once we get the table's offset, we can subtract it from the offset of the column.import { CommonModule } from '@angular/common';
import {
AfterViewInit,
Directive,
ElementRef,
NgModule,
Optional,
} from '@angular/core';
@Directive({
selector: '[stickyTable]',
})
export class StickyTableDirective {
constructor(private el: ElementRef) {}
get x() {
return (this.el.nativeElement as HTMLElement)?.getBoundingClientRect()?.x;
}
}
@Directive({
selector: '[sticky]',
})
export class StickyDirective implements AfterViewInit {
constructor(
private el: ElementRef,
@Optional() private table: StickyTableDirective
) {}
ngAfterViewInit() {
const el = this.el.nativeElement as HTMLElement;
const { x } = el.getBoundingClientRect();
el.style.position = 'sticky';
el.style.left = this.table ? `${x - this.table.x}px` : '0px';
}
}
@NgModule({
declarations: [StickyDirective, StickyTableDirective],
imports: [CommonModule],
exports: [StickyDirective, StickyTableDirective],
})
export class StickyDirectiveModule {}
StickyDirective
.constructor(
private el: ElementRef,
@Optional() private table: StickyTableDirective
) {}
StickyTableDirective
as @Optional()
so that we can add the StickyDirective
directive on other elements and it can automatically be sticky with the default value.<table stickyTable>
<tr>
<th sticky>Company</th>
<th sticky>Manager</th>
<th>Employees</th>
<th>Contractors</th>
<th>Jobs</th>
<th>Contracts</th>
<th>Vacancy</th>
<th>Offices</th>
</tr>
<ng-container *ngFor="let item of data">
<tr>
<td sticky style="min-width:200px">{{ item.company }}</td>
<td sticky>{{ item?.manager }}</td>
<td> {{ item?.employees }} </td>
<td> {{ item?.contractors }} </td>
<td> {{ item?.employees }} </td>
<td> {{ item?.contractors }} </td>
<td> {{ item?.employees }} </td>
<td> {{ item?.contractors }} </td>
</tr>
</ng-container>
</table>
stickyTable
directive to the table and the sticky
directive to the column.StickyTableDirective
to be able to use it on other elements as well.