Make a Material table header fix

If you see the below code, you’ll find out that I’ve removed the data rows from the first table and header row from the second table. and then added a tableHeader and tableData ids to both table.
1<table2 mat-table3 [dataSource]="dataSource"4 class="mat-elevation-z8"5 id="tableHeader"6>7 <ng-container matColumnDef="position">8 <th mat-header-cell *matHeaderCellDef>No.</th>9 </ng-container>10
11 <ng-container matColumnDef="name">12 <th mat-header-cell *matHeaderCellDef>Name</th>13 </ng-container>14
15 <ng-container matColumnDef="weight">16 <th mat-header-cell *matHeaderCellDef>Weight</th>17 </ng-container>18
19 <ng-container matColumnDef="symbol">20 <th mat-header-cell *matHeaderCellDef>Symbol</th>21 </ng-container>22
23 <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>24</table>25
26<table27 mat-table28 [dataSource]="dataSource"29 class="mat-elevation-z8"30 id="tableData"31>32 <ng-container matColumnDef="position">33 <th mat-header-cell *matHeaderCellDef>No.</th>34 <td mat-cell *matCellDef="let element">{{element.position}}</td>35 </ng-container>36
37 <ng-container matColumnDef="name">38 <th mat-header-cell *matHeaderCellDef>Name</th>39 <td mat-cell *matCellDef="let element">{{element.name}}</td>40 </ng-container>41
42 <ng-container matColumnDef="weight">43 <th mat-header-cell *matHeaderCellDef>Weight</th>44 <td mat-cell *matCellDef="let element">{{element.weight}}</td>45 </ng-container>46
47 <ng-container matColumnDef="symbol">48 <th mat-header-cell *matHeaderCellDef>Symbol</th>49 <td mat-cell *matCellDef="let element">{{element.symbol}}</td>50 </ng-container>51
52 <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>53</table>
Now, we’ll get the width of each column from the second table and reflect them in the first to fix the header.
1const headerTable = document.querySelector('#tableHeader')2const dataTable = document.querySelector('#tableData')3
4/**5 * Get width of each column named "dataWidths" and6 * Fix first and last column width by subtraction 24px7 * as left and right padding was styled into the first and last column of the table8 * */9const dataWidths = [...dataTable.children[1].children[0].children].map(10 cell => cell.offsetWidth11)12dataWidths[0] = dataWidths[0] - 2413dataWidths[dataWidths.length - 1] = dataWidths[dataWidths.length - 1] - 2414
15const headerColumns = [...headerTable.children[0].children[0].children]16headerColumns.map(column => {17 column.style.width = dataWidths[count] + 'px'18 count++19})
🙏