I have a filter component inside the header of each column of my mat-table
, if filtering is enabled for this column. The component has UI and logic to configure and apply filters of different types (number, text, date, selection).
The problem is, that the filter is reset (the filter component is re-rendered) when I hide/show a dynamic column (for example for buttons) although the rest stays the same. This loses all filter data. I also can’t save the filter data outside of the filter component, because I can differentiate between removing the component because filtering was disabled or re-rendering. Both times ngOnDestroy
is called. So I don’t know when to keep the data and reapply it and when to delete it.
Is there a way to prevent recreation of columns that are present before and after hiding/showing a dynamic column:
I created a minimal reproducible example. In this I don’t want the counter in the column header to increase after the first time.
When any component is under a “*ngIf” condition, when condition becomes false it’s destroyed, when condition becomes true the variables are initialized and execute the “ngOnInit”.
The typical is not use *ngIf="condition"
else [style.display]="!condition?'none':null"
-see that in style.display we use the opposite of condition.
When we have a mat-table the “*ngIf” are when we change the displayColumns
We can use some like:[style.display]="dynamicColumns.indexOf(column)<0?'none':null"
to have like
allPossible:string[]=['buttonColumns'] //<--here all
dynamicColumns:string[]=[]
<ng-container *ngFor="let column of allPossible" [matColumnDef]="column">
<th [style.display]="dynamicColumns.indexOf(column)<0?'none':null"
mat-header-cell *matHeaderCellDef>{{ column }}</th>
<td [style.display]="dynamicColumns.indexOf(column)<0?'none':null"
mat-cell *matCellDef="let element">
<button *ngIf="column === 'buttonColumn'" mat-button>Action</button>
</td>
</ng-container>
And always displayColumns are the “meta”+”dynamicColumns”
3