Tips on Showing a Unique List in Mat-Table?

Here's what I'm trying to accomplish: I have a list and I want to display it without any duplicates. I attempted using the code (this.model.map(x => x.map), but it resulted in an error. Can anyone help me fix this?

model: myModel[];
myObj:any;
result:[];

constructor(){
this.result = Array.from(new Set(this.model.map(x => x.Name))); <----- I encountered an error with this line 
`Cannot read properties of undefined (reading 'map')`
}

ngOninit(){
this.getList()

getList() {
    this.services.getListAll(5, 1).subscribe((data: myModel[]) => {
      this.myObj= data;
      this.model= this.myObj.items
    }) 
  }
  onPaginateChange(event: PageEvent ){
    let index = event.pageIndex;
    let size = event.pageSize;
    index = index + 1;

    this.services.getListAll(size, index).pipe(first()).subscribe((data: myModel[]) => {
      this.myObj= data;
      this.model= this.myObj.items
     
    });
  }
}

I've tried various approaches, but keep encountering the same error. Any assistance would be greatly appreciated.

Answer №1

When you're inside the constructor and attempt to access this.model, keep in mind that this.model doesn't have a value at that time. It only gets assigned a value asynchronously through the callback function of getList inside ngOnInit. To ensure that this.model has a valid value, it is recommended to move your filter logic inside the callback function.

getList() {
    this.services.getListAll(5, 1).subscribe((data: myModel[]) => {
      this.myObj= data;
      this.model= this.myObj.items
      this.result = Array.from(new Set(this.model.map(x => x.Name)));
    }) 
  }

Answer №2

I am currently working on understanding your issue and trying to find a solution.

It seems like you are removing duplicates from an array before assigning the values to a variable. You should move that line of code after retrieving data from the API. Take a look at the improved version of your code below, where I have optimized it for better performance:

public model: myModel[];
public myObj: any = null;
public result: [] = [];

ngOninit(){
  this.getList(5, 1); // Optional to pass parameter
}

public getList(pageSize: number = 5, pageNumber: number = 1) {
    this.services.getListAll(pageSize, pageNumber).subscribe((data: myModel[]) => {
      this.myObj= data;
      this.model= this.myObj?.items || [];
      this.result = [];
      if (this.model != null && this.model.length > 0) {
        this.result = Array.from(new Set(this.model.map(x => x.Name)));
      }
    }) 
  }
}

public onPaginateChange(event: PageEvent ){
   let index = event.pageIndex;
   let size = event.pageSize;

   this.getList(size, index + 1);
}

Please try the updated code above, as it may resolve your issue.

Thank you!

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

Encountered an Angular 4 issue - ERROR in main.ts file: Module not located - Error: Unable to resolve './$$_gendir/app/app.module.ngfactory'

While running the production build for Angular (ng build --prod), an error is encountered: ERROR in ./src/main.ts Module not found: Error: Can't resolve './$$_gendir/app/app.module.ngfactory' in '/Applications/MAMP/htdocs/bandpay/stg-b ...

What is the most effective method for obtaining the ViewContainerRef of a mat-row in Angular 4

I am currently working with a mat-table and I'm looking to retrieve the ViewContainerRef of a clicked row in order to add another component within that specific row. Can anyone suggest the most effective method to obtain the ViewContainerRef of a row? ...

What is the C sharp version of this code structure?

I'm curious to know what the C# syntax is for declaring a property like this: filters: { [arg: string]: string }; ...

Exploring the dynamic duo of SystemJS and AngularJS 2

I am currently working on integrating the Core Angular2 module into my application, which is written in Typescript. It's essentially following the same structure as the quick start tutorial on the Angular.IO website. However, I am facing a challenge ...

Conditioning types for uninitialized objects

Is there a way to create a conditional type that can determine if an object is empty? For instance: function test<T>(a: T): T extends {} ? string : never { return null } let o1: {} let o2: { fox? } let o3: { fox } test(o1) ...

strophe js is designed to handle the reception of individual messages specifically within the context of Angular

I am currently utilizing Strophe.js for establishing a connection with an XMPP server in an Angular 4 application. When using the connection.addHandler() method, I can successfully receive a single message within my listener function after the connection h ...

The challenge of validating in Typescript and utilizing type inference

I am currently facing an issue with a function that resembles the one provided below (I have created a simplified example for discussion purposes): interface Variable { someMethod: () => void } const validateVariable(variable: Variable | undefined) { ...

Displaying Angular reactive form data on screen and then populating it in a jQuery table

Successfully retrieving and displaying data from a template-driven form in Angular, however encountering difficulties when trying to achieve the same with a reactive form. The ultimate goal is to showcase this data on a jQuery table. ...

Swap out each addition symbol with a blank space within a given text

I'm currently working on a Typescript project where I need to convert URL parameters into a JSON object. The issue I'm facing is that some values are concatenated with a '+'. How can I replace this symbol with a space? Here's the ...

Bring in a function by its name from the ts-nameof package that is not declared in the d.ts export

Recently, I came across a captivating package that caught my interest and I would love to incorporate it into my TypeScript application: https://github.com/dsherret/ts-nameof However, upon attempting to import the nameof function, I realized it was not be ...

AG-Grid: Enhancing Cell Interactivity

Within ag-grid, there is a feature called stopEditingWhenGridLosesFocus. I recently developed my own custom cell editor using a cell editor component. I am curious to know if there exists a similar property or method to achieve the behavior of stopEditing ...

I am experiencing an issue with the PUT method on my API as it is not correctly setting the req.body data

Below is the code snippet for implementing the PUT method: [/api/[id].ts] case "PUT": try { const user = await UserModel.findOneAndUpdate( { _id: id, }, { $set: req.body, ...

The exclusion feature in TSLint does not seem to be functioning properly

It seems that the ts lint -e/--exclude feature is not functioning properly, or perhaps I am doing something incorrectly. I currently have tslint 4.5.1 installed. Whenever I attempt to use the CLI with tslint -e path_to_file, it gives me an error stating ...

Angular Material transition animation in fading style

After implementing the routing animation for my Angular 6 + Material app following this answer, I decided to switch to a different animation effect: const fade = [ // route 'enter' transition transition(':enter', [ // css styles ...

Derive a subset Union from a Union in Typescript

Here is a scenario with a Union type I'm working with; type MyUnionType = 'foo' | 'bar' | 'baz' What I need to do is create a new Union called MySubUnion, which will be a subset of the original; type MySubUnion = &apos ...

Utilizing arrays to generate dynamic types within a class method

Is there a way to extract values from an array as specific types in TypeScript? const chars = ['a','b','c'] as const type TChars = typeof chars[number] // 'a'| 'b' | 'c' I want to achieve the sa ...

Issue with Angular 2 - Basic form validation no longer functioning

The Angular 2 application I've been working on includes a simple form with input fields and basic HTML validation. Here's an example: <form (onSubmit)="submit()"> <input type="email" /> <input type="submit" value="save" /> ...

Develop your own personalized Angular schematics that produces a file that begins with an underscore

Having trouble with custom Angular schematics file naming. I'm trying to create a theme SCSS file that starts with an underscore followed by a double underscore as a delimiter. For instance, I want the file name to be _mouse-theme.scss, using the nam ...

encountering difficulties with implementing the custom pagination feature in Angular 2

After creating a custom pagination component using Angular2, I encountered an error when trying to use it in another component: Can't bind to 'offset' since it isn't a known property of 'app-pagination'. Update Made in app. ...

How to Route in Angular 5 and Pass a String as a Parameter in the URL

I am currently working on an Angular project that focuses on geographic system data. The concept is as follows: I have a component with the route: {path: 'home'}. I aim to pass a geojson URL along with this route, making it look like this: {pat ...