As a newcomer to the world of programming, I am currently tackling a table that includes form fields for filtering purposes.
My goal is to dynamically hide or show table columns based on whether a form field has a value or not.
In my table.component.ts file:
form:FormGroup = new FormGroup({
titleFormControl: new FormControl('')})
I then define the columns like so:
columns = [
{
columnDef: 'title',
header: 'Titel',
cell: (element: Movie) => `${element.title}`,
hide: false,
}];
displayedColumns = this.columns.map(c => c.columnDef);
In the table.component.html:
<form [formGroup]="form">
<mat-form-field appearance="fill">
<mat-label>Titel</mat-label>
<input type="text" matInput #titleFormControl placeholder="Titel">
</mat-form-field></form>
<mat-table #table [dataSource]="movies" class="mat-elevation-z8">
<ng-container *ngFor="let column of columns" [matColumnDef]="column.columnDef">
<th mat-header-cell *matHeaderCellDef hidden="column.hide">>
{{column.header}}
</th>
<td mat-cell *matCellDef="let row" hidden="column.hide">
{{column.cell(row)}}
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</mat-table>
How can one display a column only when the titleFormControl has a value?
Alternatively, how can I update the "hide" property in the columns array and refresh the table?
I'm currently feeling a bit lost and would greatly appreciate any guidance.