Explore the contents of a Table

When using a WebService, I send JSON to the front-end and map it to display all its content in a table. My goal is to implement a search method that will filter the rows based on searched letters.

Component.ts

allCountries: AllCountry[];
applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.allCountries.filter = filterValue.trim().toLowerCase();
  }     ^^^^^^^^^^^^
           ERROR

Mapping

export class AllCountry {
    name: string;
    iso2: string;
    iso3: string;
    unicode: string;
    dial: string;
    currency: string;
    capital: string;
    continent: string;
}

HTML

<mat-label for="search">Search</mat-label>
            <input matInput type="text" name="searchString" (keyup)="applyFilter($event)" placeholder="Type to search..." />

      <table mat-table [dataSource]="allCountries">

            <ng-container matColumnDef="name">
                    <th mat-header-cell *matHeaderCellDef>Country</th>
                    <td mat-cell *matCellDef="let allCountries">{{allCountries.name}}</td>
                </ng-container>

                <ng-container matColumnDef="iso2">
                    <th mat-header-cell *matHeaderCellDef>ISO 2</th>
                    <td mat-cell *matCellDef="let allCountries">{{allCountries.iso2}}</td>
                </ng-container>

Error

Error TS2322: Type 'string' is not assignable to type '{ <S extends AllCountry>(callbackfn: (value: AllCountry, index: number, array: AllCountry[]) => value is S, thisArg?: any): S[]; (callbackfn: (value: AllCountry, index: number, array: AllCountry[]) => unknown, thisArg?: any): AllCountry[]; }'.

I am encountering an error because "filter" is available for simple arrays but not for arrays of objects. Unfortunately, I cannot provide more code as it is unrelated to my current issue. Thank you for your assistance.

Answer №1

One issue here is that trying to assign this.allCountries.filter as a property won't work because Array.filter is a function, not a property.

To properly filter the array, you need to call filter() with a filtering function as an argument.

For example, to filter countries based on a substring in their name using String.includes():

  this.filteredCountries = this.allCountries.filter(
      obj => obj.name.toLowerCase().includes(filterValue.trim().toLowerCase())
  );

It's recommended to have two separate arrays: one for all countries (allCountries) and another for the filtered countries according to the search text (e.g., filteredCountries), to avoid depleting the original array during multiple filtering cycles.

Here is an outline of the approach:

export class AppComponent {
  allCountries = [
    {
      name: "England"
    },
    {
      name: "France"
    }
  ];

  filteredCountries = [];
  ngOnInit() {
    this.filteredCountries = this.allCountries;
  }

  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    if (!filterValue) {
      // Empty filter, show all countries:
      this.filteredCountries = this.allCountries;
    } else {
      console.log("Filtering for " + filterValue);
      this.filteredCountries = this.allCountries.filter(
        obj => obj.name.toLowerCase().includes(filterValue.trim().toLowerCase())
      );
    }
  }
}

In the HTML, bind to filteredCountries instead of allCountries:

<table mat-table [dataSource]="filteredCountries">

  <!-- Code omitted for brevity -->

</table>

You can view the working code on StackBlitz at:

https://stackblitz.com/edit/angular-ivy-lzkxnr?file=src/app/app.component.ts

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

Using Angular, a class can serve as a method within another class

I am new to Angular2 and encountering a problem. I have developed a component called info. In the info.component.ts file, I am initializing objects in the following way: import { Comm } from '../shared/comments'; ... const VASACOM: Comm = { na ...

Directing users to varying pages based on a particular criteria

As we continue to develop our application, we are creating various pages and need to navigate between them. Our current framework is Next.js. The issue we are facing involves the Home page: when transitioning from the Home page to another page (such as pa ...

Best practice for including Angular in the list of dependencies for an npm library

I have developed a small angular package on NPM that I consistently maintain to be compatible with all the latest versions of angular. In my package.json file, I have included angular in the list of peerDependencies to ensure they are always available in p ...

Enabling static and non-static methods within interface in TypeScript

As a beginner in TypeScript, I recently discovered that static methods are not supported in interfaces. However, I found a workaround explained in Val's answer. The workaround works fine if your class contains only static methods. But if you have a co ...

Obtain the closest numerical range using JavaScript

I have a range object and an array of price values. My goal is to find the nearest range from the range object for each value in the price values array. I attempted the solution below, but it did not give me the correct range. range = { 0: '25-500 ...

Executing TypeDoc on a Windows system results in zero files being created and no error messages reported

I have been working on generating documentation for a JavaScript application using TypeDoc. Unfortunately, I am facing an issue where TypeDoc is not outputting any files or errors. To get started, I installed TypeDoc within the project folder: npm instal ...

The initial UI did not match the server-rendered content, resulting in a Next.JS Hydration failure

I'm facing an issue with hydration in Next.JS 14, where there is a discrepancy between the server-side rendered UI and the client-side rendering. I have a suspicion that this problem may stem from using new Date(), which could be producing different v ...

Having issues with adding a form group to a form array in Angular 2 Reactive Forms

I am currently working on a dynamic form and I am looking to add form groups dynamically. Below is the code snippet that I have been trying to get to work: import {Component, OnInit} from '@angular/core'; import {FormGroup, FormBuilder, FormArray ...

Angular CLI simplifies the process of implementing internationalization (i18n) for Angular

After diving into the Angular documentation on i18n and using the ng tool xi18n, I am truly impressed by its capabilities. However, there is one part that has me stumped. According to the documentation, when internationalizing with the AOT compiler, you ...

Simplify deeply nested JSON structures with TypeScript generics

After receiving the JSON data shown below, I have a specific model in mind for deserialization: {"results": {"data": { "id":"93cba9bd-2969-3214-b26f-7f42d20241a4", "first_name":"PSU", "last_name":"Bot", "profile": { "data":{"abou ...

Divide the list of commitments into separate groups. Carry out all commitments within each group simultaneously, and proceed to the next group

My Web Crawling Process: I navigate the web by creating promises from a list of website links. These promises act as crawlers and are executed sequentially. For instance, if I have 10 links, I will crawl the first link, wait for it to complete, then move ...

What is the process for creating a Deep Copy of an object in Angular?

I have a specific entity class defined as follows: export class Contact { id: number; firstName: string; lastName: string; constructor(id?, firstName?, lastName?) { this.id = id; this.firstName = firstName; this.lastName = lastName; ...

I am attempting to retrieve a fixed set of information from a query within the resolver

Utilizing nestjs and graphql for my implementation. The service of a source contains an array of objects accessed through getAllPromotions() function: @ObjectType("Promotions") export class StaticPromotions{ @Field(() => String, { descrip ...

The plugin by chartjs-plugin-crosshair is malfunctioning

Having some trouble with the chartjs-plugin-crosshair - it's not working as expected. Here are the packages I am using: "chart.js": "^3.9.1" "chartjs-plugin-crosshair": "^1.2.0" Seems like there might be an i ...

Angular: Differences Between "Partial" and "Full" Compilation Modes

Is there a reason why the library compiled in "partial" mode takes longer to build within the consumer application compared to the "full" compilation mode? ...

How can you obtain the user ID by verifying an email when using applyActionCode in Firebase 9 modular?

Is there a way to access the UID of an email verified user? Will the response provide any helpful insights, or should I handle this from another source? const handleVerifyEmail = (auth: any, actionCode: any) => { applyActionCode(auth, actionCode! ...

Dealing with Cross-Origin Resource Sharing (CORS) issues in Angular and Spring Boot: Addressing the 'Access-Control-Allow-Origin' header absence for a seamless connection. Discover effective solutions using both Angular

Despite my efforts, I keep encountering the same error. How can I resolve it? Error: Access to XMLHttpRequest at 'http://localhost:8083/getuser' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight ...

Utilizing Logical Operators in Typescript Typing

What is the preferred method for boolean comparisons in Typescript types? I have devised the following types for this purpose, but I am curious if there is a more standard or efficient approach: type And<T1 extends boolean, T2 extends boolean> = T1 ...

The file size of clr-ui-dark.min.css seems unexpectedly large, despite attempts to optimize the bundles

Has anyone else noticed a similar issue in their projects, or could it be that I made a mistake? It appears to me that the dark styling comprises roughly 33% (according to webpack-bundle-analyzer) of my app's total size. https://i.sstatic.net/fLduq.j ...

Ways to retrieve the ngValue from various select elements created in the HTML code

I'm dealing with a JSON list of roles that includes their id, name, and parent_id (referring to themselves). roles My goal is to display all the roles along with their names and corresponding parents. The parent will be displayed in a select input, ...