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

How should a React Testing Library wrapper be properly typed in a TypeScript environment?

There's this code snippet from Kent C. Dodd's library that I find extremely helpful import * as React from 'react' import {render as rtlRender} from '@testing-library/react' import {ThemeProvider} from 'components/theme& ...

Deactivate the button if the mat-radio element is not selected

Here is my setup with a mat-radio-group and a button: <form action=""> <mat-radio-group aria-label="Select an option"> <mat-radio-button value="1">Option 1</mat-radio-button> <mat-radio-b ...

Troubleshooting issue: How to effectively extract route params in Angular using switchMap

I've been following a tutorial on how to retrieve route parameters in the Angular Routing documentation. Initially, I successfully retrieved the route parameters using subscribe. this.getRouteParams$ = this.route.params.subscribe(params => { // ...

Ionic 2: Unveiling the Flipclock Component

Can anyone provide guidance on integrating the Flipclock 24-hours feature into my Ionic 2 application? I'm unsure about the compatibility of the JavaScript library with Ionic 2 in typescript. I have searched for information on using Flipclock in Ionic ...

What is the proper way to provide parameters for express.use to avoid encountering a type error?

When attempting to use the path string in this code snippet within the function, an error is thrown. The argument type string cannot be assigned to the parameter type RequestHandler<RouteParameters>    The assigned type does not contain call si ...

Adding a dynamic CSS stylesheet at runtime with the power of Angular and Ionic 2

Currently, I am working on creating a bilingual application using Ionic2. The two languages supported are English and Arabic. As part of this project, I have created separate CSS files for each language - english.css and arabic.css. In order to switch be ...

Applying CSS dynamically to a mat-cell in Angular 6

In my material table, I need to apply specific CSS classes based on the content of the cell. These are the CSS classes that I am using .status-code{ flex: 0 0 10% !important; width: 10% !important; } .status-code-success{ flex: 0 0 10% !impo ...

What is the best way to define the height in a react project?

Greetings on this fine Friday. I've experimented with various options, but none of them appear to have any effect. "height": "100%" "height": "450px" "height": "auth" I would rather avoid a ...

The process of HTML compilation is halted due to the unexpected presence of the forbidden 'null' data type, despite the fact that null cannot actually be a valid value in

Encountering an issue with my HTML code, where the compiler stops at: Type 'CustomItem[] | null | undefined' is not compatible with type 'CustomItem[] | undefined'. Type 'null' cannot be assigned to type 'CustomItem[] ...

The value specified as type '{ value: BigNumber; }' cannot be assigned to the parameter type 'Overrides & { from?: string | Promise<string> | undefined; }'

I am currently working on a smart contract using Solidity (version 0.8.0) at my buildspace project. Below is a snippet of my code written in TypeScript (4.5.x)/JavaScript and Node.js 16.13.x: ... const waveContractFactory = await hre.ethers.getContractFact ...

Using wildcard in Angular app for MQTT observation

My curiosity lies in MQTT wildcards and how they function, specifically while utilizing the mosqitto broker. Let's say I have around 1-2k topics. In my frontend, I am observing them with a single-level wildcard using ngx-mqtt. Will there be a separat ...

Add the specified HTML tag to the existing document. An error has occurred: HierarchyRequestError - The action would result in an invalid node

During my testing of a React/TypeScript project using Jest + Enzyme, I encountered an issue when trying to append an HTML tag. The error occurred with the following unit test code: const htmlTag: HTMLElement = document.createElement('html'); htm ...

The Angular Password Strength Extension will display an error message if the password strength is below 100

It's frustrating to keep trying different methods to achieve a simple task. I have a reactive form and all I want is to display an error if the password strength is not 100, indicating that it does not meet all the requirements. I can easily access t ...

When working with Typescript, an error is thrown if property "p" does not exist on one of the classes that are OR

In my component class, I have a property called renderContent which can be of either LessonPageType or TaskPageType based on the input value. Below is the code snippet from my component: import {ChangeDetectionStrategy, Component, HostListener, Input, OnI ...

How can the value be accessed when using getElementById in Angular for <mat-select> elements that do not have a value attribute?

Within a loop, I have an element that has a dynamically generated id: <mat-select multiple class="dw-input" [value]="element.txn_type_id ? element.txn_type_id.split(',') : []" id="field-{{element.Name}}-txn_type_id&quo ...

Angular - ngx-Pagination malfunctioning in an unexpected manner

Currently in my Angular project, I am setting up server-side pagination using ngx-bootstrap-pagination with ASP.NET Core-6 as the backend. This is the service implementation: getPaymentStatus(): Observable<IPaymentStatus[]> { return this.http.get& ...

cycle through options of radio buttons

How can I display items of radio buttons, with the values of these items coming from a backend api? <div class="input-group col-md-9 input-group-sm"> <label>gender</label> </div> <!-- TO CORRECT ...

Retrieve the input value from a Bootstrap Form Input

When using a Bootstrap Form Input to allow the user to enter text, I am wondering how to save that text and use it as a parameter in a function. Below is the HTML snippet I have: <!--Directory Input Form--> <div class="row"> <div class= ...

Using the <template> syntax to apply ngclass or [class.classname]

I am familiar with the syntax for ngFor, ngIf, and ngSwitch using templates. Can someone provide guidance on how to utilize ngClass or [class.className] with template syntax in Angular 2? Can anyone explain how to implement classes using template syntax i ...

Guide to automatically opening a webview upon launching an ionic application

After encountering difficulties opening a login page from the desktop site with webview when my ionic app launches, I decided to create a separate page named login-check.page. On this page, I included a button that successfully opens the desktop login page ...