"Every time you run mat sort, it works flawlessly once before encountering an

I am having an issue with a dynamic mat table that includes sorting functionality.

dataSource: MatTableDataSource<MemberList>;
  @Output() walkthroughData: EventEmitter<number> = new EventEmitter();
  @ViewChild(MatSort, { static: true }) sort: MatSort;

  data: any;
  memberList: MemberList[];
  membersCount: number;
ngOnInit(): void {
    setTimeout(() => {
      this.dataSource.sort = this.sort;
    });

    this.teamService.getTeamMembers().subscribe((response) => {
      this.data = response['data']['result'];

      this.memberList = this.data.map(({ name, role, email }) => ({
        teamMember: Object.values(name).join(' '),
        email,
        role: role?.name,
        assignedOn: [
          'LA Care Health Plan',
          'LA Care Health Plan',
          'LA Care Health Plan',
        ],
      }));
      this.dataSource = new MatTableDataSource(this.memberList);
    });
  }

The problem I am facing is that it only works once and then throws an error.

core.js:6210 ERROR TypeError: Cannot set property 'sort' of undefined

I have checked that matHeaderCellDef and matCellDef are the same, I have imported the mat sort module, and I have also tried using ngAfterViewInit for the datasource, but the same error persists. What could I be doing wrong?

Answer №1

It appears that there may be a race-condition problem occurring, where the code works the first time due to chance. The issue is arising because your setTimeout function is running before your subscribe function, causing the dataSource variable to be undefined.

To resolve this, you should reposition the following code:

this.dataSource.sort = this.sort;

Move it immediately after initializing your variable like so:

this.dataSource = new MatTableDataSource(this.memberList);

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

Eliminate the unnecessary code repetition in my functions using Typescript

I have 2 specific functions that manipulate arrays within an object. Instead of repeating the same code for each array, I am looking for a way to create reusable functions. Currently, my functions look like this: setLists(): void { if (this.product.ord ...

CORS policy has blocked access to XMLHttpRequest from the origin because the requested resource does not have the 'Access-Control-Allow-Origin' header

I recently built an API project using MVC Core. Everything seemed to be working fine when testing the GET and POST methods with Postman. However, I encountered a CORS error when trying to call these APIs from my Angular App: Access to XMLHttpRequest fro ...

Validating forms in Angular 5 with the help of ngx-bootstrap

I am currently delving into Ari Lerner's ng-book about Angular 5. My setup includes ngx-bootstrap and Bootstrap 4. However, I am facing an issue with form validation that doesn't align with Mr. Lerner's implementation. I'm unsure whethe ...

How to Implement Autocomplete Feature in Angular

CSS <div class="dropdown"> <input type="text" formControlName="itemName" (ngModelChange)="filterItems()" class="dropdown-input" (keyup)="onKeyPress($event)" (blur)="toggleDropdown(0)" (focus)="toggleDropdown(1)" placeholder="Search..." [ngCla ...

Using TypeScript to send state through history.push({...})

I recently utilized the history.push method to redirect to a specific URL while passing along some information through the included state. Here's how I implemented it: const history = useHistory() history.push({ pathname: '/someurl/', ...

Modify the outDir of the compiled code in NativeScript

I find it frustrating that the js files are always generated next to my ts/ng files. It's really annoying, so I decided to move the compiled/transpiled js files outside of the app directory, just like in any typical Angular app. This is what I did: ...

The Angular2 view is failing to display updated data from a shared service

I've been struggling to show data from my shared service, but it's not displaying. Can someone please help me out? I've been stuck on this for the past few days. I've tried NgZone and ChangeDetectorRef, but they haven't worked for ...

Tips for integrating TypeScript files into Next.js HTML files

Encountering an issue while trying to load a typescript file from HTML, resulting in this error Here is the code snippet for the page: export default function Home() { return ( <> <Script src="/static/main.tsx"></Scri ...

Global.styles.css not applying background-color in Angular

I decided to enhance the appearance of my website by adding some code to the global styles.css file in order to change the background color to light blue. html, body{ background-color: lightblue ; } However, after refreshing the home.component page, I n ...

Creating a View-Model for a header bar: A step-by-step guide

I am looking to develop a View-Model for the header bar using WebStorm, TypeScript, and Aurelia. In my directory, I have a file named header-bar.html with the following code: <template bindable="router"> <require from="_controls/clock"></ ...

3 Ways to Ensure Your Picture Uploads are Visible Right Away

I am currently working on an Ionic app that enables users to upload images to Firebase storage. One issue I am encountering is that the image only changes once a new one is selected, after closing and reopening the app. I would like it to update immediatel ...

Ways to access a property within an object using TypeScript

Can you help me extract the "attributes" array from this object and store it in a new variable? obj = { "_id": "5bf7e1be80c05307d06423c2", "agentId": "awais", "attributes": [ // that array. { "created ...

Is it possible for pdfjs-dist to be used with Typescript?

Is there a way to preview a PDF as a canvas without importing pdfjs-dist into my project? I have already used the command $yarn add pdfjs-dist to install pdfjs-dist. Do I need to include any additional imports? import pdfjsLib from "pdfjs-dist/build ...

The Angular component refuses to open

Having some trouble with my navbar containing different components that should open upon selection. The profile component is opening correctly, but the "My favorites" button isn't displaying anything from that component. Here's the code snippet ...

Steps to dynamically populate dropdown menus based on the selected options from other dropdown menus

I am working on a project that involves two dropdown menus. The options for the first dropdown menu are stored in a file called constant.ts. Depending on the selection made in the first dropdown, the options for the second dropdown will change accordingly. ...

Encountering a type mismatch error in Typescript while working with Redux state in a store file

It appears that I have correctly identified all the types, but could there be a different type of Reducer missing? 'IinitialAssetsState' is not assignable to type 'Reducer' The complete error message: Type '(state: { assets: n ...

Exciting Dynamic Text Animation in React using styled components

I came across this cool jumping text effect on https://web.dev/patterns/animation/animated-words/ and wanted to incorporate it into my app. However, when I tried implementing the component in React, I encountered some issues. I created a styled component a ...

Utilize the npm module directly in your codebase

I am seeking guidance on how to import the source code from vue-form-generator in order to make some modifications. As a newcomer to Node and Javascript, I am feeling quite lost. Can someone assist me with the necessary steps? Since my Vue project utilize ...

The 'type' property within the NGRX Effect is not present in the type Observable<any[]>

I am currently in the process of upgrading my Angular app from version 6 to version 7. Additionally, I am upgrading the TypeScript version from 2.7.2 to 3.1.6. The issue I'm encountering is that TypeScript is flagging an error stating that my ngrx ef ...

The click event is activated following the :active selector being triggered

My Angular application features a button with a slight animation - it moves down by a few pixels when clicked on: &:active { margin: 15px 0 0 0; } The button also has a (click)="myFunction()" event listener attached to it. A common issue arises w ...