Show the name of the category in the mat table in Angular instead of the category

Using Angular Material Mat Table to display data fetched from an API is great, but I'm facing a challenge with handling categories from another API. Currently, my models include issues and categories, where the category ID is displayed instead of the category name.

Any suggestions on how to display the category name instead?

My models

export class Issue {
  IssueID: string;
  IssueTitle: string;
  IssueContent: string;
  CategoryID: number;
}

export class IssueCategory {
  public CategoryID: number;
  public CategoryName: string;
}

My html

...
  <ng-container matColumnDef="CategoryTitle">
    <mat-header-cell *matHeaderCellDef mat-sort-header>Category</mat-header-cell>
    <mat-cell *matCellDef="let row">{{row.categoryID}}</mat-cell>
  </ng-container>
...

EDIT

My getAllIssues()

CategoryArray: TicketCategory[] = [];

getAllIssues(): void {
this.httpClient.get<Ticket[]>(this.API_URL).subscribe(data => {
this.dataChange.next(data);      

  this.data.map(issue => ({

    category: this.CategoryArray.find(category => category.CategoryID === issue.CategoryID)
  }));
  }
 }

Thank you for any help!

Answer №1

To simplify things, you can utilize pre-combined data as your data source, like this:

// my-component.ts

@Component(...)
export class MyComponent {
  readonly categories: IssueCategory[] = [{
    CategoryID: 1,
    CategoryName: "First Category"
  }, {
    CategoryID: 2,
    CategoryName: "Second Category"
  }];

  readonly issues: Issue[] = [
    {IssueID: "first", IssueTitle: "First Issue", IssueContent: "first issue content", CategoryID: 1},
    {IssueID: "second", IssueTitle: "Second Issue", IssueContent: "second issue content", CategoryID: 2}
  ];

  readonly dataSource = this.issues.map(issue => ({
    title: issue.IssueTitle,
    content: issue.IssueContent,
    category: this.categories.find(category => category.CategoryID === issue.CategoryID)
  }));
}

Alternatively, you can create a pipe that converts a category ID to the corresponding name. Remember to include the pipe in the declarations array of a module.

// category-by-id.pipe.ts

@Pipe({
  name: 'categoryById'
})
export class CategoryByIdPipe implements PipeTransform {
  transform(categoryId: number, categories: IssueCategory[]): string {
    const category = categories.find(category => category.CategoryID === categoryId);
    return category ? category.CategoryName : "";
  };
}
<!-- my-component.html -->

...
  <ng-container matColumnDef="category">
    <mat-header-cell *matHeaderCellDef> Category </mat-header-cell>
    <mat-cell *matCellDef="let element"> {{element.CategoryID | categoryById:categories}} </mat-cell>
  </ng-container>
...

Check out this StackBlitz for both examples. I hope it clarifies things for you.


Here is another illustration using MatTableDataSource.

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

Determine the finishing time by calculating the sum of the start time and duration

Is there a way to determine the end time by using the start time and duration? I am able to receive these values from an API: data : { 'startTime': 1100, // (the format is in 24hrs i.e 11:00 AM) 'duration' : 60 // (in minutes) ...

Utilize an unspecified object key in TypeScript generics for advanced referencing

Upon initial inspection, the function below addPropertyIfValueIsNotUndefined appears to be functioning: function addPropertyIfValueIsNotUndefined<Value>(key: string, value: Value): { key?: Value; } { return isNotUndefined(value) ? { [key]: value ...

The 'status' attribute is not found within the 'User' data type

Currently, I am invested in a personal project using Angular 6 for the client side and Laravel 5.6 for my API. Despite successful testing of the API endpoints with Postman, I find myself struggling to comprehend the behavior of my auth service. To provide ...

Angular 2: Copious Errors in the Mix

Working on building an Ionic 2 app using the Angular 2 framework, I encountered a problem when trying to display a map on a page. I found a helpful guide at the following link: While the map was working fine, I started getting an error in my console: You ...

Combining a Spring project and Angular 4 into a single repository with a single commit

I developed a Spring Boot app with an Angular 4 project. The file structure is set up as follows: (all JS files minified under the static directory in resources). https://i.sstatic.net/0ITCc.png Now I have two separate .gitignore files - one for the Java ...

What is the best way to specify the return type of a currying function?

Check out this currying function I've implemented: export interface NewIdeaCardSubmit { title: string, description: string, categories: CategoryValues } const applyInputs = (title: string) => (description: string) = ...

Error encountered when using Angular Material date-time picker

I encountered an error in the console when trying to use the Angular Material datetime picker. Although it functions correctly, my tests failed due to this error. https://www.npmjs.com/package/@angular-material-components/datetime-picker <mat-form-fiel ...

"Utilize XML parsing to convert data into JSON format and set up subscription functionality

My current task involves converting an XML string to JSON using xml2js. I then need to send and subscribe to the result in another component. getLastWeekSnow = function(){ let headers = new Headers(); headers.append('Access-Control-Allow-Origin' ...

Using Angular's HTTP service with Observables and @Input functionality

Here is the pseudo code snippet I am working on: Service getData(): Observable<MyData[]>{ return this.http.get<Data[]>(`https://localhost/api/data`); } Component: myData: Data[]; [...] ngOnInit(){ this.myService.getData.subscribe( data ...

Bring in TypeScript types exclusively, rather than the entire module

Currently, I have a project with all the necessary JavaScript files already included. However, I am now attempting to transition some of the code to TypeScript for its advantages. One of the libraries I utilize (sweetalert2) is installed in the node_module ...

Disappearance of Angular Material List on click event

Here is an interesting problem I am facing. Take a look at the code snippet below: <md-list flex> <md-list-item class="md-2-line" ng-repeat="device in devices" ng-init="deviceDtl = getDevice(device.$id); tonerCount = tonerCount(device.$id)" ...

How to incorporate a new child object into a preexisting object in Firebase with the help of AngularFire2 in Angular

I have user data stored in Firebase like this: users : { -KamJGmnL8S4Nn_okIcc : { name: "Someone", email: "example.com", website: "somesite.com" }, -laeghmnw8S4Nn_9inb47 : { name: "Someone", email: "exam ...

Anticipating the desired data types for Jasmine arguments

Lately, I've been in the process of upgrading my Angular version from 10 to 13 in order to utilize TypeScript 4.6. However, during this upgrade, I made some errors with types in my tests and I'm wondering if others have encountered similar issues ...

Data fetched by Next.js is failing to display on the web page

After writing a fetch command, I was able to see the data in the console.log but for some reason it is not showing up in the DOM. export default async function links(){ const res = await fetch('https://randomuser.me/api/'); const data = ...

One of the interfaces in use is malfunctioning, despite being identical to the other interface in TypeScript

I have been working on the IDocumentFilingDto.ts file. import { DocumentOrigin } from "./IDocumentFilingDto"; export interface IDocumentFilingDtoGen { UniqueId?: any; Title?: string; DocumentId?: string; Binder?: any; Communi ...

Tips for managing errors in HTTP observables

I'm currently facing a challenge with handling HTTP errors in an Angular2 observable. Here's what I have so far: getContextAddress() : Observable<string[]> { return this.http.get(this.patientContextProviderURL) .map((re ...

My HTML grid table is not being properly rendered by the JSON data

I'm currently facing a challenge with rendering my HTML grid table in Angular using JSON data retrieved from a MySQL database. I would greatly appreciate any assistance or guidance on how to solve this issue. View the output of the Angular code here ...

What is the reason the 'Add' type does not meet the 'number' constraint?

I experimented with type gymnastics using Typescript, focusing on implementing mathematical operations with numeric literals. First, I created the BuildArray type: type BuildArray< Length extends number, Ele = unknown, Arr extends unknown ...

Encountering an issue when using npm to add a forked repository as a required package

While attempting to install my fork of a repository, I encountered the error message "Can't install github:<repo>: Missing package name." The original repository can be accessed here, but the specific section I am modifying in my fork is located ...

Navigating to a new link containing query parameters

I am working on setting up a redirect in Angular 6 The process for the redirect is quite simple as outlined below: Obtain destination URL from parameters: this.returnUrl = this.route.snapshot.queryParams['route'] || '/'; Perform Red ...