Hide mat-table column if formfield has no value

Viewed 268

I am new to the programming field and working on a table with form fields for filtering.
I want to hide or show table columns if a formfield has a value or not.

So in my table.component.ts:

 form:FormGroup = new FormGroup({
titleFormControl: new FormControl('')})

Then i declare the columns like this:

columns = [
{
  columnDef: 'title',
  header: 'Titel',
  cell: (element: Movie) => `${element.title}`,
  hide: false,
}];
displayedColumns = this.columns.map(c => c.columnDef);

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 i show the column if the titleFormControl has a value.
Or how can i update the columns array field hide and refresh the table.
I am clueless at the moment and would appreciate any help.

1 Answers

Every FormControl has a value which you can easily read using a value property.

https://material.angular.io/components/form-field/api#MatFormFieldControl

I change your example accordingly, instead of setting a hide property of a column to false, I set it to the value of a titleFormControl:

columns = [
{
  columnDef: 'title',
  header: 'Titel',
  cell: (element: Movie) => `${element.title}`,
  hide: this.titleFormControl.value
}];
displayedColumns = this.columns.map(c => c.columnDef);

One more example how to use FormControl value to hide the table columns.

Related