How can I show a limited number of columns in a mat-table in Angular 6 depending on a specific condition?

Currently, I am facing an issue with my mat table as it contains several columns. In a specific scenario, I need to hide two of these columns. Typically, for a regular table, we would use a simple ngIf condition to achieve this. However, in the case of this mat-table, that approach does not seem to work. Here is what I have tried:


displayedColumns1: any[] = [
  'Ref No', 'E Type',
  { def: 'Approve', showMobile: true },
  { def: 'Transfer', showMobile: false },
];

getDisplayedColumns(): string[] {
 const isMobile = this.entityRole === 'Admin';
 return this.displayedColumns1
  .filter(cd => !isMobile || cd.showMobile)
  .map(cd => cd.def);
}

Below is the relevant HTML code snippet:

<table mat-table [dataSource]="dataSource" class="">
    <tbody>
        <ng-container matColumnDef="Ref No">
            <th mat-header-cell *matHeaderCellDef> Ref No <br></th>
            <td mat-cell *matCellDef="let element"> {{ ref }} </td>
        </ng-container>
        
        <!-- Other column definitions go here -->

   <tr mat-header-row *matHeaderRowDef="getDisplayedColumns"></tr>
        <tr mat-row *matRowDef="let row; columns: getDisplayedColumns;"></tr>     
    </tbody>
</table>

Unfortunately, I encountered an ERROR TypeError: Cannot read property 'diff' of undefined. Can someone please assist me in resolving this issue while using mat-table?

Answer №1

It seems like the issue you're facing is due to a mix of custom objects and strings in your column name array, which is causing problems with your filter.

displayedColumns1: any[] = [
    'Ref No', 
    'E Type',
    { def: 'Approve', showMobile: true },
    { def: 'Transfer', showMobile: false }
];

getDisplayedColumns(): string[] {
  const isMobile = this.entityRole === 'Admin';
  return this.displayedColumns1
    .filter(cd => !isMobile || cd['showMobile'] !== false)
    .map(cd => typeof cd === 'string' ? cd : cd.def);
}

Answer №2

displayedColumns: any[]
if (this.userType === 'Admin') {
    this.displayedColumns = ['name', 'dob', 'grade', 'address'];
} else {
    this.displayedColumns = ['name', 'dob', 'grade'];
}

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

What is the best way to implement a timeout and subsequently clear it in a React functional component?

Hello there, I am currently working on a functional component in ReactJS and I am facing an issue with implementing a timeout on mouse hover over a menu. The timeout functionality is working fine, but I am struggling to clear this timeout in another funct ...

Angular component linked to a dynamic object requiring user confirmation before changing or reverting to the original value

I've been working on getting a simple <select> behavior where the value reverts back if the user cancels the change. I managed to achieve it, but it took me quite a few hours and I'm not entirely satisfied with the implementation as it&apos ...

Utilizing Angular's global interceptor functionality can streamline the process

Having trouble making 2 interceptors (httpInterceptorProviders, jwtInterceptorProviders) work globally in my lazy modules. I have a CoreModule and X number of lazy-loaded modules. Interestingly, autogenerated code by the Swagger generator (HTTP services) g ...

Creating secure RSA keys using a predetermined seed - a step-by-step guide

Is it possible to utilize a unique set of words as a seed in order to recover a lost private key, similar to how cryptocurrency wallets function? This method can be particularly beneficial for end-to-end encryption among clients, where keys are generated o ...

After refreshing the page, Angular 8 may incorrectly load JavaScript from an incorrect path when accessing a lazy loaded

Whenever I refresh the page while on a lazy loaded module, the application breaks because it attempts to import JavaScript files from an incorrect path. Here is an overview of my routing configuration: App Routing Module: { path: 'accommodations&ap ...

How can I bind Angular to the selection of a file input field?

I am facing an issue with my upload form where the displayed filename is showing a virtual filepath instead of just the filename itself. How can I improve the binding to only display the filename (like selected.files[0].name) without any virtual path? My ...

Height and width not being properly set by Ngx-Bootstrap popover

Struggling to integrate ngx-bootstrap into my Ionic 2 / Angular 2 application. The popover seems to be having issues with its display in the view: <button placement="right" [outsideClick]="true" popover="this is a test text for the popover conten ...

Animating sprites using TypeScript

I've been tackling the development of a small Mario game lately. However, I'm facing some difficulty when it comes to animating sprites. For instance, I have a mario.gif file featuring running Mario (although he's not actually running in th ...

"I would like to implement ngClass in Angular to display the 'active' status in red and the 'inactive' status in black

I need to implement ngClass in Angular so that the current status is displayed in red color while all other statuses are displayed in black. How can I achieve this? <div *ngFor="let item of status_history; let i = index"> ...

Using LINQ with ngFor in Angular 6

Within the component.ts, I extract 15 different lookup list values and assign each one to a list, which is then bound to the corresponding <select> element in the HTML. This process functions correctly. Is there a method to streamline this code for ...

Utilizing TypeScript Class Inheritance: The Reference to 'super' is Only Allowed in Members of Derived Classes or Object Literal Expressions

We have encountered a scoping issue while using TypeScript classes with inheritance. It seems that TypeScript/JavaScript does not allow us to use 'super' within a promise structure or an enclosed function. The error message we are getting is: Ty ...

Assign the chosen value to the dropdown list if ngModel is present

I currently have a select field implemented in my Angular component: <select class="form-control" [(ngModel)]="myClient.address && myClient.address.state" name="state" (ngModelChange)="getCitiesByState($event)"> <option class="form-con ...

Property of object (TS) cannot be accessed

My question relates to a piece of TypeScript code Here is the code snippet: export function load_form_actions() { $('#step_2_form').on('ajax:before', function(data) { $('#step_2_submit_btn').hide(); $(&ap ...

watcher using RxJS

After recently diving into the Observable and Observer pattern, I came across various resources that describe Observable as a producer and Observer as a consumer. However, as I analyzed the code snippet below, I found myself puzzled by the role of the obse ...

Understanding Restangular with Typescript can be challenging, especially when dealing with a 'restangularized' response object

In my project, I am working with Angular 1.5.x using TypeScript in combination with restangular to access a remote API. Here is an overview of the scenario: The API endpoint I am connecting to is http://localhost:53384/api/timezones. Making a GET request ...

Tips for adjusting fullcalendar's local property in an Angular application

I'm having trouble changing the local property of fullcalendar. I've tried setting it to "en-gb", but it's not working. Can you help me figure out what I'm doing wrong? <full-calendar #calendar defaultView="dayGridMonth" [header]="{ ...

Unable to retrieve post information from Angular using PHP

I've hit a roadblock in my Angular App where I can't seem to access the body of the post data being sent from Angular 4. Despite numerous attempts, I'm unable to retrieve this crucial information. Can anyone lend a hand in identifying the is ...

Solving a React app's dependency problem with Yarn workspaces

Currently, I am in the process of constructing a complex multi-module project using create-react-app, TypeScript, and Yarn workspaces. The layout is as follows: package.json packages - create-react-app-project - other-lib-project - tsconfig.json ...

The minimum and maximum validation functions are triggered when I am not utilizing array controls, but they do not seem to work when I use array controls

Take a look at the stack blitz example where min and max validation is triggered: https://stackblitz.com/edit/angular-mat-form-field-icrmfw However, in the following stack blitz with an array of the same controls, the validation does not seem to be worki ...

Enhancing TypeScript Types with a custom method within an Angular 2 context

I am working on an Angular 2 project using the CLI. Currently, I am trying to add a custom method to the String type as shown below. interface String { customMethod(): number; } String.prototype.customMethod = function() { return 0; } Despite my ...