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

Tips for maintaining JSON data in CK Editor

I'm having an issue where my JSON data is not being displayed in CKEditor when using this code function retrieveRules(){ $.ajax({ url: "api", type: "POST", data: { version:'0.1' }, ...

Query executed but no results returned

Currently, I am practicing GQL and facing an issue when trying to display data in the Playground. I am attempting to access the jsonplaceholder API to fetch all posts and show them, but encountering the following error: Error: GRAPHQL_FORMAT_ERROR: Expec ...

The storage of HTML5 data is not being saved locally

<html> <head> <title></title> <style type="text/css"> body { font-family: tahoma; } h2 { font-weight: bold; border-bottom: 2px solid gray; margin-bottom: 10px; } #dat ...

Assign the onClick function to the decoration of a Vscode extension

When I click on a vscode decoration, I want to trigger a function. Here's the code I created for this: const decoration = { range, hoverMessage: `${command} ${input}`, command: { title: 'Run Function', command: ' ...

Tips on converting HTML code into a data image URI

My question may seem unconventional, but here is what I am trying to accomplish. I want to create a design similar to the one found at the following link: I would like to embed text with an image and retrieve the data image URL using Ajax. I know how to g ...

Issue: Headers cannot be set after they have been sent. This is a problem in node.js

I'm trying to create an application that allows users to execute commands via a URL, but I keep encountering this error message: _http_outgoing.js:346 throw new Error('Can\'t set headers after they are sent.'); ^Error: Can't ...

Experiencing issues with the functionality of jQuery AJAX?

I am experiencing difficulties with a jQuery AJAX post. Here is the code: <script> var callback = function(data) { if (data['order_id']) { $.ajax({ type: 'POST', url: '<?php echo $_SERV ...

Set theme value for the tab group in Angular Material

Trying to change the tab theme in Angular Material by setting it directly seems to be a bit tricky. The example from Angular Material shows how to do it with a toggle button, but when I try to code it directly, it doesn't work. Here's the code sn ...

The ngAfterContentInit lifecycle hook is not triggered when the parent component updates the child component

I am trying to understand the functionality of the ngOnChanges callback in Angular. I have implemented it to observe changes in a property annotated with the Input decorator as shown below: @Input() postsToAddToList: Post[] = []; However, after compiling ...

Discover the power and ease of combining Angular with OIDC Implicit Flow for seamless

I have integrated the angular-auth-oidc-client package for authentication in my Angular application with our OIDC server. While using the implicit flow, some users face log out issues when the access token expires. To address this, I decided to implement t ...

Is there a way in JavaScript to format an array's output so that numbers are displayed with only two decimal places?

function calculateTipAmount(bill) { var tipPercent; if (bill < 50 ) { tipPercent = .20; } else if (bill >= 50 && bill < 200){ tipPercent = .15; } else { tipPercent = .10; } return tipPercent * bill; } var bills = ...

Issue with implementing MUI Grid within a dialog across various screen sizes

While working with a MUI dialog and MUI grid, I encountered an issue. The code I am using is directly from the website, with only minor modifications to the dialog function names and the box wrapping the dialog. Despite changing the size of the dialog, t ...

Failed to build development environment: Unable to assign the attribute 'fileSystem' to a null value

I'm attempting to launch an Ionic 2 Application, but I keep encountering this error when running ionic serve Error - build dev failed: Unable to assign a value to the 'fileSystem' property of object null Here is the complete log: λ ion ...

Error message: Unable to instantiate cp in Angular 17 application while building with npm run in docker container

After creating a Dockerfile to containerize my application, I encountered an issue. When I set ng serve as the entrypoint in the Dockerfile, everything works fine. However, the problem arises when I try to execute npm run build. Below is the content of my ...

Tips on invoking a function from an array in JavaScript when a button is clicked

Being new to JavaScript, I encountered a challenge where I have an array of functions: allFunctions = () => [ function1(), function2(), function3(), function4(), function5(), function6(), function7(), function8(), function9() ] My go ...

What is the best way to utilize RxJs for streaming HostListener events?

Although I've found plenty of resources on binding Angular HostListeners, I'm curious about using RxJs to stream it instead: @HostListener('document:click', ['$event']) handleClick(event: Event) { // etc } I want to cre ...

How to populate a database with Facebook data by utilizing AJAX post and PHP

I've been developing a Facebook Canvas game and had it running smoothly on my localhost along with a local database via phpMyAdmin. However, after moving it online, I've encountered an issue with the database. Previously, the game would grab pla ...

Is there a way to hide the borders between cells within these divs?

I am working on an application screen using Vue.js and facing an issue with the divisions between cells. I want to hide these divisions so that the lines of the items appear continuous. I attempted to modify the classes of the columns to "col-md" and "col ...

Steps to retrieve hexadecimal addresses sequentially

Can anyone recommend a module or script that can generate sequential 64-bit hex addresses like the following: 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000001 00000000000 ...

Incorporating an HTML file into a DIV container while also displaying menu links

I am facing a major challenge with what I recognize as a relatively simple issue for experts. As someone who is still learning, I am struggling to create menu links that load an HTML file into a specific DIV. Despite my efforts, the content keeps loading i ...