2

Good morning I have the following question, I have a data table which I get the data that is in it by consuming api rest, the question is that I want to hide a specific column of the same table depending on the value of a variable where its value will be collected in the authentication to enter the application, but I would like to know what method there is to hide a column in a data table depending on the condition of a variable.

My code

The column to hide is the Com. Snmp enter image description here

<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>

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

                  <!-- Weight Column -->
                  <ng-container matColumnDef="vendedor">
                    <th mat-header-cell *matHeaderCellDef>Vendedor</th>
                    <td mat-cell *matCellDef="let element">{{element.vendedor}}</td>
                  </ng-container>

                  <!-- Symbol Column -->
                  <ng-container matColumnDef="ip_gestion">
                    <th mat-header-cell *matHeaderCellDef>IP Gestión</th>
                    <td mat-cell *matCellDef="let element">{{element.ip_gestion}}</td>
                  </ng-container>

                  <ng-container matColumnDef="tipo">
                    <th mat-header-cell *matHeaderCellDef>Tipo</th>
                    <td mat-cell *matCellDef="let element">{{element.tipo}} </td>
                  </ng-container>

                  <ng-container matColumnDef="localidad">
                    <th mat-header-cell *matHeaderCellDef>Localidad</th>
                    <td mat-cell *matCellDef="let element">{{element.localidad}}</td>
                  </ng-container>

                  <!-- <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
                  <tr mat-row *matRowDef="let element; columns: displayedColumns;"></tr> -->

                  <ng-container matColumnDef="categoria">
                    <th mat-header-cell *matHeaderCellDef>Categoria</th>
                    <td mat-cell *matCellDef="let element">{{element.categoria}}</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>

                  <ng-container matColumnDef="ultima_actualizacion">
                    <th mat-header-cell *matHeaderCellDef>Ultima Actualización </th>
                    <td mat-cell *matCellDef="let element">{{element.ultima_actualizacion | date:'d/M/yyyy, h:mm a'}}</td>
                  </ng-container>

                  <ng-container matColumnDef="actions">
                    <th mat-header-cell *matHeaderCellDef>Acciones</th>
                    <td mat-cell *matCellDef="let element">
                    <fa-icon [icon]=icon_edit class="btn btn-success" (click)=onEdit(element) matTooltip="Editar" matTooltipPosition="left" [hidden]='permiso2'></fa-icon>&nbsp;
                    <!-- -->
                    <fa-icon [icon]=icon_delete class="btn btn-danger" (click)=onDelete(element) matTooltip="Eliminar" matTooltipPosition="right" [hidden]='!delete_permiso'></fa-icon>

                    </td>
                  </ng-container>

                  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
                  <tr mat-row *matRowDef="let element; columns: displayedColumns;"></tr>

              </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()
                                   }

4 Answers 4

6

You can make use of displayedColumns variable to show hide cols on basis of your condition. Remove column that you need from displayedColumns as shown below:

ngOnInit(){
 if(yourCond == true){
   displayedColumns: string[] = ['id_equipo', 'nombre', 'vendedor', 'ip_gestion','tipo','localidad','categoria','ultima_actualizacion','actions']; 
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

@Arturo29 Cool!
1

to hide dynamically material table columns;

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

Comments

0

You can use *ngIf on that specific column on which you want to apply some condition. Declare a variable IsTrue and assign it a value of false by default. And in your logic when you want to display this column assign this variable value 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>

1 Comment

Got the error: core.mjs:8400 ERROR Error: Could not find column with id "com_snmp". at getTableUnknownColumnError (table.mjs:987:12) at table.mjs:1902:23 at Function.from (<anonymous>) at MatTable._getCellTemplates (table.mjs:1899:22) at MatTable._renderCellTemplateForItem (table.mjs:1864:39) at MatTable._renderRow (table.mjs:1860:14) at table.mjs:1781:54 at Array.forEach (<anonymous>) at MatTable._forceRenderHeaderRows (table.mjs:1781:29) at MatTable.ngAfterContentChecked (table.mjs:1404:18)
-1

Puedes también solo agregar una clase en el CSS Y Consumir esta en el HTML, esto me funciona en Angular Material. Espero que les sirva

.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>

1 Comment

please use English to answer to question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.