Conceal a designated column within a material angular data table based on the condition of a variable

In the morning, I have a question about working with data tables and API consumption. I need to hide a specific column in the table based on a variable value obtained during authentication. Can you suggest a method to achieve this?

Here is a snippet of my code:

The column I want to hide is labeled Com. Snmp https://i.stack.imgur.com/wCUu3.png

<div class="col-11 mx-auto">

        <div class="search-div" >
              <button  class="btn btn-primary"  (click)="onCreate()" [hidden]='permiso2'>Crear Equipo</button>&nbsp;&nbsp; 
              <!-- -->
              <button class="btn btn-warning"(click)="onExport()">Descargar Datos</button>&nbsp;&nbsp; 
            <mat-form-field class="search-form-field">
                <input matInput (keyup)="DoFilter($event.target.value)" placeholder="Filtrar">
            </mat-form-field>
        </div>
                                                    <!--Data Table-->
          <div>  
              <table mat-table [dataSource]="dataSource" align="center" [hidden]="isLoading" >  

                  <!-- Position Column -->
                  <ng-container matColumnDef="id_equipo">
                    <th mat-header-cell *matHeaderCellDef>ID Equipo</th>
                    <td mat-cell *matCellDef="let element">{{element.id_equipo}}</td>
                  </ng-container>

                  ...
                  
                   <ng-container matColumnDef="com_snmp">
                      <th mat-header-cell *matHeaderCellDef matTooltip="Comunidad SNMP de Lectura" matTooltipPosition="above">Com. SNMP</th>
                      <td mat-cell *matCellDef="let element">{{element.com_snmp}}</td>
                    </ng-container>

                  ...

              </table>        
                  <mat-paginator [pageSizeOptions]="[5,10,20,50]" showFirstLastButtons [hidden]="isLoading"></mat-paginator>          
          </div>

                                                <!--Spinner Para la Carga de Datos-->
                <ng-container *ngIf="isLoading">
                  <mat-spinner class="spinner-container"></mat-spinner>
                  <br>
                  <p>Su data esta siendo cargada, por favor espere</p>
                </ng-container>           
  </div>
<br>

My equipo.ts

displayedColumns: string[] = ['id_equipo', 'nombre', 'vendedor', 'ip_gestion','tipo','localidad','categoria','com_snmp','ultima_actualizacion','actions',]; // Arreglo con los nombres de las columnas a mostrar por el DataTable
            dataSource:any;


RenderDataTable() {
                this.isLoading=true;
                this.PrtgService.getAllElements(this.table).subscribe(  
                  (res) => {  
                      this.dataSource = new MatTableDataSource();
                      this.dataSource.data = res.sort((a, b) => a.vendedor.localeCompare(b.vendedor));
                      this.dataSource.paginator = this.paginator; // Paginando el DataSource
                      this.isLoading=false;   

                },
ngOnInit() {
            this.RenderDataTable()
                                   }

Answer №1

To control which columns to display based on a condition, you can utilize the displayedColumns variable. Simply remove the column that is not needed from the array as shown in the example below:

ngOnInit(){
 if(yourCondition == true){
   displayedColumns: string[] = ['id_equipo', 'nombre', 'vendedor', 'ip_gestion', 'tipo', 'localidad', 'categoria', 'ultima_actualizacion', 'actions']; 
 }
}

Answer №2

How to dynamically hide material table columns;

if (userRole !== 'Admin') {
  displayedColumns = [
    'requestNo',
    'createdAt',
    'spareName',
    'spareNum',
    'spareAttr',
    'approvedQuantity',
    'quantity',
    'requestedBy',
    'department',
  ];
}

Answer №3

To apply a condition on a specific column, you can use the *ngIf directive. Create a variable called IsTrue and set its default value to false. When you want to display the column in your code logic, change the value of this variable to true.

<ng-container matColumnDef="com_snmp" *ngIf="isTrue">
                  <th mat-header-cell *matHeaderCellDef matTooltip="Comunidad SNMP de Lectura" matTooltipPosition="above">Com. SNMP</th>
                  <td mat-cell *matCellDef="let element">{{element.com_snmp}}</td>
                </ng-container>

Answer №4

Una técnica interesante es agregar una clase en el CSS y luego consumirla en el HTML, esto me ha dado buenos resultados en Angular Material. ¡Espero que les sea útil!

.hide_element{
  display: none;
}
 <ng-container matColumnDef="recibo"class="hide_element">
        <mat-header-cell mat-header-cell *matHeaderCellDef  class="hide_element">Recibo</mat-header-cell>
        <mat-cell *matCellDef="let element" class="hide_element"> {{element.recibo}} </mat-cell>
 </ng-container>

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

The issue I'm facing is that the ng-click functionality in Angular JS is not functioning properly when the

Upon loading the page, my JavaScript function creates a tree structure from JSON data and generates a list of anchor tags which look like this: <a ng-click="shareParent(4619)">Some data</a> Despite associating the ng-click directive with the ...

Learn the process of adding a tag to specific text with the help of JavaScript

I am attempting to implement a feature where the selected text will have a tag added to it. Within a textarea, I have some text entered. The goal is that when I select specific text from the textarea and click a code button, it should insert the tags aro ...

Leveraging JavaScript to trigger onClick() functions for multiple buttons throughout a webpage

        While searching for solutions, I came across several articles with similar topics, but unfortunately, none of the proposed solutions worked. Please forgive me if it was due to my own error. Background I am assisting a client who is transition ...

When the document is fully loaded and processed, a script will be executed immediately following

I'm facing an issue with a modal plugin on my website. The plugin is triggered on $(document).ready, but I have another function (innerHTML) that inserts an <a> element 5-10 seconds after the page loads. This causes the modal not to work properl ...

When should the preloader be placed within the DOMContentLoaded or load event?

I'm looking to implement a preloader on my website to ensure everything is fully loaded - images, JavaScript, fonts, etc. However, I'm unsure whether to use the following: window.addEventListener('DOMContentLoaded', () => { // code ...

At what point should I expect a promise in Protractor to be resolved?

Despite there being similar inquiries on this topic, I am struggling to comprehend them. Allow me to illustrate with an example, where my task is to click a button and verify the URL. Initially, I thought it should be coded as: element(by.id('butto ...

Interact with SOAP web service using an Angular application

I have experience consuming Restful services in my Angular applications, but recently a client provided me with a different type of web service at this URL: http://123.618.196.10/WCFTicket/Service1.svc?wsdl. Can I integrate this into an Angular app? I am ...

Tips for altering the appearance of a button when moving to a related page

I have a master page with four buttons that have a mouse hover CSS property. Each button's corresponding response page is defined on the same master page. Now, I want to change the button style when the user is on the corresponding page. How can this ...

Ui Bootstrap (angularjs) sidebar is not functioning properly

I am encountering an issue with a sidenav that I am in the process of creating for one of my projects. The goal is to develop a side menu that shifts the content to the right when opened and returns it to the left when closed, essentially functioning as a ...

Need help with updating React component state within a Meteor.call callback?

I've constructed this jsx file that showcases a File Uploading Form: import React, { Component } from 'react'; import { Button } from 'react-bootstrap'; class UploadFile extends Component { constructor(){ super() this. ...

"electron-builder - initially designated for building app for Mac only, but now configured to build for both Mac

This is my first attempt at creating an electronjs app, so I may not have a full grasp on what I'm doing. I've been following the instructions on GitHub and also this guide from Medium. Here's a snippet of my package.json: { (package.jso ...

JQuery Mobile applies X to all divs with the specified class

I am currently working on a JQuery mobile website with an image slider on 2 different pages. In order to activate the sliders, I am using the following JavaScript code: $(function () { $("#slider").excoloSlider(); }); where '#slider' refers ...

I am curious about why I am unable to utilize inline functions in component props. Could you please provide a detailed explanation and perhaps give an example to illustrate? Furthermore, what is

Please take note: The component prop accepts a component, not a render function. Do not pass an inline function (e.g. component={() => }), as this will cause your component to unmount and remount, losing all state when the parent component re-renders. F ...

Having trouble establishing a connection between Atlas and Node.js

Here is the content of my server.js file: const express = require('express'); const cors = require('cors'); const mongoose = require('mongoose'); require('dotenv').config(); const app = express(); const port = pro ...

Challenges arise when transferring data retrieved from a table into a bootstrap modal window

I have been attempting to transfer values from a table into a modal. Initially, I successfully displayed the <td> values in an alert when a button was clicked on a specific row. Now, I am aiming to take it a step further by having these <td> va ...

I'm having trouble getting my ms-auto to properly align the contents within a div

I've been trying to use the ms-auto class in my code, but it doesn't seem to be working properly: <div class="p-5 rounded bg-light text-dark"> <div class="container row"> <div class="col-sm-6"> ...

Creating a unique JavaScript script that gradually adjusts the background color using the setTimeout() function

Is there a way to create a function that continuously changes the background color every 15 seconds by picking colors from an array that starts over once all colors have been used, without having the function run just one time? $(document).ready(() => ...

Typescript: The type 'T' fails to meet the requirement of being an 'object'

Ever since I installed a package along with its @types package, I've been encountering an issue with the following code: https://i.stack.imgur.com/rrRhW.png This is the error message that I'm receiving: https://i.stack.imgur.com/BfNmP.png The ...

How to Transfer Information Between Two React Components

I recently started learning React and I'm not sure how to approach this task. Basically, I have a list of cars and when the user clicks on each car, it should display detailed information about that specific car in a full-page slide. This is my curr ...

Looking for assistance with jqGrid

Is there a method to confirm if the grid has finished loading using a separate function? My goal is to automatically click on the first row and move that row to the second grid once this action occurs. jQuery("#search_grid").jqGrid('setGridParam&apo ...