I am using Angular with PrimeNG in order to show a table. What I would like to happen is that when the page loads or the route fragment is changed, the table will scroll to the corresponding row. For example, if the URL is ending in /data?dataId=x#LC_8, it should scroll to the row with id LC_8.
For now I have the next typescript file:
export class DataComponent {
@ViewChild('dataTable', {static: true}) dataTable: Table;
data: Data[];
selectedData: Data;
constructor(private DataService: DataService, private route: ActivatedRoute) {
this.route.fragment.subscribe(() => {
let index: string = this.route.snapshot.fragment;
this.highlightRow(index);
this.scrollToSelectedRow();
});
}
ngOnInit(): void {
this.getData();
}
private getData(): void {
const dataId: string = this.route.snapshot.queryParamMap.get('dataId');
let index: string = this.route.snapshot.fragment;
this.dataService.getData({dataId}, new HttpContext()).subscribe(
data => {
this.data = data;
this.highlightRow(index);
this.scrollToSelectedRow();
});
}
private highlightRow(index: string) {
if (index) {
index = index.slice(3);
this.selectedData = this.data.find(
d => d.id.toString() == index);
}
}
private scrollToSelectedRow() {
if (this.selectedData && this.dataTable) {
const rowIndex = this.data.findIndex(lc =>
d.dataId === this.selectedData.id);
if (rowIndex !== -1) {
this.dataTable.scrollTo(rowIndex);
}
}
}
}
And the next HTML:
<h3>Data</h3>
<p-table #dataTable [value]="data" selectionMode="single" [(selection)]="selectedData">
<ng-template pTemplate="header">
<tr>
<th>ID</th>
<th>Info</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-data>
<tr [pSelectableRow]="data" id="LC_{{data.id}}">
<td>{{data.id}}</td>
<td>{{data.info}}</td>
</tr>
</ng-template>
</p-table>
I also tried with ngAfterViewInit(), but that did not help.