"Concealing a column in a PrimeNG data table with dynamic columns: A step-by-step

Hi, I'm looking for a way to hide a column in my PrimeNG data table. Is there an attribute that can be used to turn off columns in PrimeNG data tables?

.Html

<p-dataTable emptyMessage="{{tbldatamsg}}" [value]="dataset" scrollable="true" [style]="{'overflow':'hidden!important'}"
    [responsive]="true" [stacked]="stacked" [filters]="GlobalFilterValue"  [rows]="20" sortMode="multiple" [(selection)]="selectedRow" selectionMode="multiple"
    [resizableColumns]="true" columnResizeMode="expand" [paginator]="true" [globalFilter]="gb" [rowsPerPageOptions]="[10,15,20,25]"
    appendTo="body" #dt>
    <p-column styleClass="checkbox ui-resizable-column" [style]="{'width': 'auto'}" selectionMode="multiple"></p-column>
    <p-column *ngFor="let col of cols;let j=index;" [style]="{'width':'130px'} "[field]="col.field" [header]="col.header" [sortable]="true"
      [filter]="true" filterPlaceholder="Search" (mouseleave)="hoveredIndex=null" filterPlaceholder="Search" appendTo="body">
      <ng-template let-row="rowData" let-i="rowIndex" pTemplate="body">
        <!--    <div [pTooltip]="row[col.field]" [id]="col.field"> -->
        <span *ngIf="col.field==='modified'" (mouseover)="passIndexValue(i) ">
          <a style="color:black;">{{row[col.field]}}</a>
        </span>
        <p-button *ngIf="col.field==='modified' && hoveredIndex===i && !displayDialog " appendTo="body" icon="fa fa-fw fa-eye" (click)="onRowSelect($event,'View',i)"></p-button>
        <p-button *ngIf="col.field==='modified' && hoveredIndex===i && !displayDialog" appendTo="body" icon="fa fa-fw fa-edit" (click)="onRowSelect($event,'Edit',i)" ></p-button>
        <p-button *ngIf="col.field==='modified' && hoveredIndex===i && !displayDialog " appendTo="body" icon="fa fa-fw fa-trash" (click)="onRowSelect($event,'Delete',i)"></p-button>
        <span *ngIf="col.field==='suggested_Value'">
          <a style="color:black;">{{row[col.field]}}</a>
        </span>
        <!-- set String -->
        <span (mouseover)="hoveredIndex=null" style="text-align:left;" *ngIf="col.datatype!='int' && col.datatype!='float' && col.field!='modified'  && col.field!='suggested_Value'" >
          {{row[col.field]}}
        </span>
        <!-- set int -->
        <span (mouseover)="hoveredIndex=null" style="text-align:right;float: right" *ngIf="col.datatype=='int' || col.datatype=='float' && col.field!='modified'  && col.field!='suggested_Value'" >
          {{row[col.field]}}
        </span>
       </ng-template>
   <!--<ng-template pTemplate="filter" let-colvalue>
              <input *ngIf="col.field==='symbol'" type="text" pInputText  style="width:100%" [(ngModel)]="SymbolFilterValue" (onChange)="ApplySymbolFilter(dt,SymbolFilterValue,col.field,col.filterMatchMode)" (input)="ColumnFilter(dt, $event.srcElement.value, col.field, col.filterMatchMode)" class="ui-column-filter"/>
              <input *ngIf="col.field!='symbol'" type="text" pInputText  style="width:100%" (input)="ColumnFilter(dt, $event.srcElement.value, col.field, col.filterMatchMode)" class="ui-column-filter"/>
      </ng-template> -->
    </p-column>
  </p-dataTable>

Answer №1

Issue Resolved!

The problem was successfully resolved by utilizing the CSS property display:none;

<p-column *ngFor="let col of cols; let j=index;" 
[style]="{'width':'130px','display': col.display}" <<--add condition
[field]="col.field" 
[header]="col.header"

.ts

getColumns() {
    let ColumnNamePath = './assets/Grid Column Names/Oats-Exception-Summary-Columns.json';
    this.SharedHttpClientService.getJson(ColumnNamePath)
      .subscribe(column => {
        this.columnJson = [];
        for (var i = 0; i < column.length; i++) {

          this.cols[i] =
            { header: column[i].UI_ColumnName, field: column[i].MappingKey, datatype: column[i].DataType, label: column[i].UI_ColumnName, value: column[i].DB_ColumnName ,display: column[i].Display}
        }

      }, error => console.log(error));

}

column.json

[
     {
        "Display": "true",
        "UI_ColumnName": "End Of Record Marker",
        "DB_ColumnName": "END_OF_RECORD_MARKER",
        "DataType": "String",
        "MappingKey": "end_Of_Record_Marker"
    },
    {
        "Display": "true",
        "UI_ColumnName": "MPID",
        "DB_ColumnName": "MPIDS",
        "DataType": "String",
        "MappingKey": "MPID"
    },
    {
        "Display": "true",
        "UI_ColumnName": "Explanation",
        "DB_ColumnName": "Explanation",
        "DataType": "String",
        "MappingKey": "explanation"
    },
    {
        "Display": "true",
        "UI_ColumnName": "Mpid OATS Exc ID",
        "DB_ColumnName": "MPID_OATS_Exc_ID",
        "DataType": "int",
        "MappingKey": "MPID_OATS_Exc_ID"
    },
    {
        "Display": "none",
        "UI_ColumnName": "OMSOrder ID",
        "DB_ColumnName": "OMSOrderID",
        "DataType": "int",
        "MappingKey": "OMSOrderID"
    },
    {
        "Display": "none",
        "UI_ColumnName": "Report Header ID",
        "DB_ColumnName": "Report_Header_ID",
        "DataType": "int",
        "MappingKey": "report_Header_ID"
    }
]

Answer №2

For the col object, you have the option to utilize the hidden property in this manner:

...
<p-column 
    *ngFor="let col of cols;let j=index;" 
    [style]="{'width':'130px'}" 
    [field]="col.field" 
    [header]="col.header" 
    [sortable]="true"
    [hidden]="!col.isVisible" <======== include your condition here
    ...

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

Binding data to custom components in Angular allows for a more flexible

In my current scenario, I am looking to pass a portion of a complex object to an Angular component. <app-component [set]="data.set"></app-component> I want the 'data.set' object in the parent class to always mirror the 'set&apo ...

Utilizing the useRef hook in React to retrieve elements for seamless page transitions with react-scroll

I've been working on creating a single-page website with a customized navbar using React instead of native JavaScript, similar to the example I found in this reference. My current setup includes a NavBar.tsx and App.tsx. The NavBar.tsx file consists o ...

What is the best way to incorporate the TUI image editor for Javascript into my Angular application?

Issue - I'm facing a challenge with my Angular application as I want to integrate Toast UI image editor. However, I am unsure about how to properly add the imports to app.module.ts in order to utilize it. Despite following the npm installation instru ...

Issue with minifying AngularJS and TypeScript route configuration for safe minification

Currently, I have a package containing multiple js files that were created from typescript files. However, when I attempt to apply minification to the package, the webpage encounters errors. The error message displayed on the Chrome console is: Uncaug ...

Opting in to an Observable depending on specific criteria

Introduction I am utilizing Reactive Forms that span across two tabs on a lengthy page with a Submit button at the bottom. Validation occurs when the Submit button is clicked. If validation fails, the page should scroll to the error field. I am successf ...

Using TypeScript with React: Specifying a type when calling a React component

How should a type be passed into a component call? Within this scenario, the render prop APICall is utilizing a type parameter named MobileSplashReturn. Although this example is functional, it seems to be causing issues with prettier, indicating that it m ...

How can I bypass a unit test suite in Angular?

Is there a method to skip certain unit tests that should not be executed currently, without resorting to using fdescribe on the ones I do want to run? ...

Can getters and setters be excluded from code coverage reports in Angular projects?

Looking to clean up my coverage reports for the front end portion of an angular project by removing trivial code like getters and setters. I generate my reports using npm run test-sonar -- --coverage, but everything is included in the report when I view ...

Using Typescript to create a union of functions

There are two different types of functions: one that returns a string and the other that returns a Promise<string>. Now, I am looking to create a function that can wrap both types, but I need to be able to distinguish between them when invoking the f ...

There was an issue retrieving the token in the interceptor. The type 'Promise<void | Observable<HttpEvent<any>>>' does not match the expected type 'Observable<HttpEvent<any>>'

I am currently working on developing an interceptor that sends the token along with requests for the Api. In order to store user information, I am utilizing the @ionic/storage library. However, I am facing an issue where my interceptor cannot access the t ...

Configuring Angular routes based on service method invocation

I have my routes configured in @NgModule. I also have a service that determines which parts of the application to display based on specific conditions. I need to call this service and adjust the routes according to its output. Issue: The route configurati ...

Guide on setting up multiple Axios instances in NestJS

I'm in the process of migrating an existing Express application to NestJS. Currently, I have a configuration file where I define multiple axios instances for each microservice: export const writeModelApi = axios.create({ baseURL: getWriteModelApiUrl ...

Trigger a change event for a Material Checkbox by referencing its unique identifier

<div *ngFor="let cus of deselectedList | keyvalue" (click)="clickCheckBox('customer_'+cus.key+'_checkbox')"> {{cus.key}} <mat-checkbox id="customer_{{cus.key}}_checkbox" (change ...

Use the constant INLINE with npm commands to specify inline behavior

Today I was working on Angular2 using the template provided at . Following the installation guide, I executed the commands as instructed. I have successfully installed Node.js v6.9.1. npm install --Executed without any issues. npm server --Encountered a ...

Creating custom Moment.js plugins within an Ionic 2/Cordova project using TypeScript

In my Typescript Ionic 2 project, I am utilizing the moment.js library. To include it in my project, I use the following code snippet: import * as moment from 'moment'; Once imported, I can use moment in my component like so: let endDate = mom ...

A technique for adding a border to a Mat Card that mimics the outline of a Mat Form Field within a custom

I am faced with a unique design challenge where I am utilizing the MatCardComponent and each card contains a table. I would like to incorporate a floating label within the border gap similar to what is seen in MatFormField. https://i.stack.imgur.com/51LBj ...

Attempting to create a function that can accept two out of three different types of arguments

I am trying to create a function that only accepts one of three different types type A = 'a' type B = 'b' type C = 'c' The function should accept either type A, C, or both B and C, but not all three types. This is what I hav ...

Implementing a NextJS client component within a webpage

I am currently working with NextJS version 14 and I am in the process of creating a landing page. In one of the sections, I need to utilize the useState hook. I have specified my component as "use-client" but I am still encountering an error stating that " ...

What is the most efficient way to retrieve and update a Stencil component parameter without triggering a rerender of the component?

Within my Stencil component, there exists a not-Prop member variable known as private _zIndex. The value of this variable can be adjusted via a method call like Method() setZIndex( zIndex : number );, or it may change internally during the component's ...

Running a function using a component in Angular 5

I am looking to develop an "action" component that functions similar to an "a" element. However, I need a way to track when the action is complete after clicking on the component. The main objective is to show a message while the action is in progress. He ...