The method toLowerCase is not found on this data type in TypeScript

I am currently working on creating a filter for autocomplete material.

Here is an example of my model:

 export class Country {
      country_id: number;
      name: string;
       }

When calling the web method ws:

 this.ws.AllCountry().subscribe(
      countries => {
        this.countries = countries.map((country) => {
          return new Country(country);
        });
      }
    );

I have tried to create the filter, but unfortunately, it is not functioning as expected:

filterStates(val: string) {
    if (val) {
      let filterValue = val.toLowerCase();
      return this.countries.filter(name => name.toLowerCase().startsWith(filterValue));
    }
    return this.countries;
  }

If anyone has any suggestions or solutions, I would greatly appreciate it. Thank you!

Answer №1

It seems like the issue is occurring in the filter line due to the usage of toLowerCase on the Country object itself. To rectify this, you can make the following adjustment:

filterStates(val: string) {
    if (val) {
      let filterValue = val.toLowerCase();

      // Update made below
      return this.countries.filter(country => country.name.toLowerCase().startsWith(filterValue));
    }
    return this.countries;
  }

Answer №2

    searchCountries(val: string) {
    if (val) {
      let filterValue = val.toLowerCase();//The toLowerCase method is not available on type Country.
      return this.countries.filter(item => item.name.toLowerCase().startsWith(filterValue));
    }
    return this.countries;
  }

You were utilizing country object instead of the name property.

Answer №3

If you're incorporating jQuery with Angular 2, remember to utilize the toString function.

$('#search').val().toString().toLowerCase()

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

Tips for Angular 14: How to clearly define a form control as not being undefined

Consider a scenario with a form setup like this: searchForm = new FormGroup({ SearchBox = new FormControl<string>('', {nonNullable: true}); )} Now, when attempting to extract the value from the form field using this code snippet: thi ...

I need assistance with adding a button to a table cell that triggers an action when clicked

I need to add a button to the table cell when I click a button to insert a new row in an Angular table. Although I am successful in adding a new row, I am facing difficulty in including a button in the cell along with the newly created row. ...

Testing Angular 11 methods using Jest unit tests within a .then block

Currently, I am running jest unit tests in Angular 11 and facing an issue while testing methods within the .then method. It seems like the test methods are not being executed at the expect method. I need guidance on how to structure the test code to ens ...

Tips for simulating the getCustomRepository function in typeORM

I am facing a challenge in unit-testing a class that has a getCustomRepository method in its constructor. I'm struggling to find an easy way to mock it. Below is the code for my class: import {getCustomRepository} from 'typeorm'; export cl ...

Understanding NestJS Mixins and Their Distinction from Inheritance

After researching, I found that the Nestjs documentation does not include any information about mixins. Here is what I have gathered from my findings on Google and Stack Overflow: A mixin serves as a means of code sharing between classes within Nest. Esse ...

Best practice for encapsulating property expressions in Angular templates

Repeating expression In my Angular 6 component template, I have the a && (b || c) expression repeated 3 times. I am looking for a way to abstract it instead of duplicating the code. parent.component.html <component [prop1]="1" [prop2]="a ...

Do you have an index.d.ts file available for canonical-json?

I am currently working on creating an index.d.ts file specifically for canonical-json. Below is my attempted code: declare module 'canonical-json' { export function stringify(s: any): string; } I have also experimented with the following sn ...

Angular Material's $mdBottomSheet can be divided into thumbnail and text elements arranged side by side horizontally

I am working on integrating Angular Material (AM) into a Cordova/Phonegap application. I want to incorporate an AM Bottom Sheet with a specific layout where: There is a single container divided into two sections as follows: The left section contains a sq ...

Retrieve the raw text from the input field instead of the date object

Below is the HTML code for an input field: <div class="input-group input-group-md"> <input id="date" name="date" [readOnly]="disabled" type="text" placeholder="M0/d0/0000 Hh:m0:s0" [placeholder]="pl ...

How to use the filter() method to filter an array of objects based on a nested array within each object

The following data presents a list of products along with their inventory information: const data = [ { id: 1, title: "Product Red", inventoryItem: { inventoryLevels: { edges: [{ node: { location: { name: "Warehou ...

The theming feature in Angular 5 with Bootstrap 4 and Bootswatch seems to be malfunctioning

Having trouble implementing bootswatch themes with angular 5 and bootstrap 4? I've added the following to styles.scss: @import "~bootswatch/dist/cerulean/variables"; @import "~bootstrap/scss/bootstrap"; @import "~bootswatch/dist/cerulean/ ...

Primary source for recurring components with the @SkipSelf decorator

Trying to understand the inner workings of Angular's dependency injection system, it seems that the component instance tree is traversed to locate the first occurrence of the specified provider, giving priority to ElementInjector over ModuleInjector ( ...

The element 'stripe-pricing-table' is not a recognized property of the 'JSX.IntrinsicElements' type

I am currently trying to incorporate a pricing table using information from the Stripe documentation found at this link. However, during the process, I encountered an issue stating: "Property 'stripe-pricing-table' does not exist on type &ap ...

Utilizing Next.js to create a Higher Order Component (HOC) for fetching data from a REST API using Typescript is proving to be a challenge, as the

In my withUser.tsx file, I have implemented a higher order component that wraps authenticated pages. This HOC ensures that only users with a specified user role have access to the intended pages. import axios, { AxiosError } from "axios"; import ...

The 'input' element does not recognize the property 'formControl', causing a binding issue in Angular Material Autocomplete with Angular 12

Recently, I upgraded my Angular app from version 11 to 12 along with all the dependencies, including Angular Material. However, after running 'ng serve', I encountered the following error: Error: src/app/components/chips/chips.component.html:19:1 ...

What is the process of importing types in TypeScript?

Here is the export I am working with: import * as jwt from 'jsonwebtoken'; ... export type MyJsonWebToken = typeof jwt; Next, when attempting to use it in my code: export class AuthService { constructor( @Inject(constants.JWT) private ...

Ways to access the values of checkboxes that are initially checked by default

Recently, I was working on a project that involved multiple checkboxes. My goal was to have the checkboxes pre-checked with values in the form (using reactive form). Users should be able to unselect the boxes as they wish and the data would be stored accor ...

Guide on receiving error responses in Angular when making API calls

While testing the API with incorrect credentials in Postman, an error response is received. However, when the same API is called from Angular, a different error status is returned. login(loginFormData){ this.service.login(loginFormData.value.username ...

Angular: ViewContainer is failing to correctly insert the component next to the anchor element, instead it is placing the component inside the anchor element

I have successfully implemented a tab view with the following structure: <tabs> <ul #getVCRefHERE > <li>tab1</li> <li>tab2</li> </ul> <tab> <ng ...

Limit the implementation of Angular Material's MomentDateAdapter to strictly within the confines of individual

Within my app, I have several components that utilize the mat-datepicker. However, there is one component where I specifically want to use the MomentDateAdapter. The issue arises when I provide it in this one component as it ends up affecting all the other ...