Conceal mat-table column when form field is empty

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.

Answer №1

You can easily retrieve the value of every FormControl by accessing its value property.

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

In this modified example, instead of toggling a column's hide property to false, it is now set 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);

Here is another example demonstrating how to use the value of a FormControl to hide table columns.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Monitor changes in input display within ngIf statements

Within my code, I am utilizing an input element within a conditional statement of *ngIf: <div *ngIf='display'> <input number="number" /> </div> My goal is to be able to detect the visibility state of the input element insi ...

Errors occur when trying to utilize an enum as a generic type in Typescript that are not compatible

Take a look at the code snippet provided. The concept here is that I have different provider implementations that extend a base provider. Each provider requires a settings object that is an extension of a base settings object. Additionally, each provider c ...

Troubleshooting: Issues with Angular 2 Dependency Injection

I am facing an issue with my angular2 application that involves a simple dependency injection, but it seems to be not working correctly. Can anyone help me figure out what might be missing? Below is the error message I am encountering: EXCEPTION: Cannot ...

Unable to load dynamic JSON data in ag-grid for Angular 2

ngOnInit(){ this.gridOptions = {}; this.gridOptions.rowData = []; this.gridOptions.rowData = [ {configName: 1, configName1: "Jarryd", configName2: "Hayne", configName3: "tttttt", configName4: "rrrtttt", configName5:"drrrrrr"}]; } ...

JavaScript Date() function misinterpreting Unix timestamp

When creating the date using a timestamp retrieved from Firebase, I use the following code: let da = new Date(item.date.day); I have double-checked that item.date.day is indeed a timestamp and the correct one at that. However, regardless of the actual t ...

Using angular 7 to apply a dynamic CSS class on a span element

I want to dynamically change the CSS class of a span element in an ngx datatable based on the value. Here is my HTML code: <ngx-datatable #orderinvoice class="bootstrap" [rows]="invoiceSource" [headerHeight]="50" [footerHeight]="50" [rowHe ...

The rapid execution of code causing an observable race condition

When exporting a CSV file in my code, I encounter a race condition while trying to modify some data before the export. The issue is that the id gets set correctly, but the number only updates after the method is called a second time. I believe the proble ...

Variable type linked to interface content type

Is it possible to link two fields of an interface together? I have the following interface: export interface IContractKpi { type: 'shipmentVolumes' | 'transitTime' | 'invoices'; visible: boolean; content: IKpiContent; } ...

How can you define a function type for a rest parameter in Typescript?

At this point, I have a function that takes in two parameters: param 'a' as a string and 'b' as a function that returns a string. My intention is to call it using a rest parameter and specify the types accordingly. However, on line 10 ...

What is the best way to create a function that can securely search for a URL containing parameters while ensuring type safety?

I am working on a NextJS/React application. We have a large object containing internal URLs, each with a createPath function that looks similar to this: const URLS = { dashboard: { createPath: ({ accountNumber }: { accountNumber: string }) => ...

Keep the code running in JavaScript even in the presence of TypeScript errors

While working with create-react-app and typescript, I prefer for javascript execution not to be stopped if a typescript error is detected. Instead, I would like to receive a warning in the console without interrupting the UI. Is it feasible to adjust the ...

Retrieving data from a form input that utilizes reactive checkboxes

Hey there, I am currently working on implementing a Reactive Form and facing an issue with fetching values from checkboxes. It seems that only the value of the first checkbox selected is being recognized while the others are not. Below is the snippet of my ...

NGRX refresh does not result in any successful actions

Having an issue with loading users into a mat-selection-list within a form. Everything works fine the first time, but upon page refresh, the selector returns 'undefined'. Initially, both GET_USERS and GET_USERS_SUCCESS are triggered (console log ...

What are the steps for integrating Socket.IO into NUXT 3?

I am in search of a solution to integrate Socket.IO with my Nuxt 3 application. My requirement is for the Nuxt app and the Socket.IO server to operate on the same port, and for the Socket.IO server to automatically initiate as soon as the Nuxt app is ready ...

Could a template variable be established for the p-dropdown element in template-driven form validation?

In the template, I have a p-dropdown element <p-dropdown id="output-method" [options]="outputMethods" [(ngModel)]="transformer!.outputMethod" pTooltip="Output Method" tooltipPosition="bottom&quo ...

Determine whether the ng bootstrap modal has already been opened

Is there a way to determine if a modal window is open? In order to accomplish this, I create a variable called modalInstance: NgbModalRef; and initialize the modal by using the code below this.modalInstance = this.modalService.open(UpdateModalConten ...

Mistakes in combining Angular NgRx actions and union types

After reviewing my code, I have encountered the following issues: In my shared.actions.ts file: import { Action } from '@ngrx/store'; import { Error } from '../error.interface'; export const types = { IS_LOADING: '[SHARED] IS_L ...

Selecting a radio button by clicking on its corresponding label within an Angular Material dialog

I recently implemented a custom rating bar in Angular, which worked perfectly fine in a basic component. However, when I tried to move it to a MatDialog component, I encountered some issues. In the initial setup, my input was set to display: none so that t ...

The art of expanding Angular's HTTP client functionality

I understand that the following code is not valid in Angular, but I am using it for visual demonstration purposes. My goal is to enhance the Angular HTTP client by adding custom headers. I envision creating a class like this, where I extend the Angular h ...

Positioning Placeholder in Angular Material's mdInput

I am currently in the process of designing a Form for my website, but I am encountering an issue with the Input and its Placeholder. The implementation should be straightforward, resembling something similar to this. However, the Placeholder is appearing ...