Unable to access the 'filter' property of an undefined Array in Angular

Currently, I have an array named

customerList: Array<String> = [];
that is populated with values from a server-side function. Everything seems to be working well until I attempt to use the .filter() method on this array and encounter an error stating "undefined". The snippet of code causing the issue is as follows:

customerList: Array<String> = [];

ngOnInit() {
this.customerService.getCustomers().subscribe(res => {
    this.customers = res;
    for (const cust of res) {
      this.customerList.push(cust.first_name);
    }
  }
);
}

findChoices(searchText: string) {
return this.customerList.filter(item =>
  item.toLowerCase().includes(searchText.toLowerCase())
  ); 
 );
}

Here's the corresponding HTML snippet:

<mwl-text-input-autocomplete-container>
  <input type="text" class="form-control" id="customer_name" name="customer_name" aria-describedby="emailHelp"
                 placeholder="Customer name" formControlName="customer_name" mwlTextInputAutocomplete
                 [findChoices]="findChoices"
                 [getChoiceLabel]="getChoiceLabel" autofocus>
</mwl-text-input-autocomplete-container>

The customerList.filter() within the findChoices() method is where the error arises.

P.S.- The angular-text-input-autocomplete package is being utilized in this scenario.

Answer №1

When passing the function object findChoices as a value to [findChoices], be mindful that the value of this will not be bound to your component. Therefore, this.customerList may end up being undefined.

To address this issue, you can utilize closure to ensure that customerList is accessible to [findChoices] by following these steps:

  1. Rework the implementation of findChoices to return a function that can serve as the value for [findChoices] - in other words, a function that takes a string parameter.

    findChoicesIn(list) {
      return (searchText) => 
              list.filter(item => item.toLowerCase().includes(searchText.toLowerCase()));
    };
    
  2. Use the newly generated function as the value for [findChoices]

    [findChoices]="findChoicesIn(customerList)"
    

Answer №2

Looks like your customerList is currently empty or null, so make sure to include a validation check

if(this.customerList && this.customerList.length > 0){
  return this.customerList.filter(item =>
  item.toLowerCase().includes(searchText.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

What is the best approach to restructuring route endpoints into an ORM framework?

As a newcomer to Angular, I find myself uncertain about what exactly qualifies as an endpoint and how it can be transformed into ORM. My current understanding suggests that an endpoint is where data is retrieved from a server, whether it's through an ...

Combining HTML with multiple .ts files in Angular

I've been dedicating time to enhancing an Angular application, particularly a sophisticated table with intricate styling and functionality. Within my component file, there is a whopping 2k lines of code that includes functions for text formatting, ta ...

Tips for switching between two icons within the same div by clicking on the icon

I am looking to implement a feature in angular2 that is similar to marking an email as Starred. For example, when I click on the empty star icon, it will make some service calls to check if the item should be starred. If the result is true, then a new icon ...

How to Retrieve Superclass Fields in Angular 5 Component

I have a superclass that provides common functionality for components. export class AbstractComponent implements OnInit { public user: User; constructor(public http: HttpClient) { } ngOnInit(): void { this.http.get<User>(& ...

Struggling with implementing conditional validators in Angular2 form models. I have tried using myForm.setValidators(), but it doesn't appear to be functioning as expected

I have been experimenting with the model form in an Ionic/Angular2 project. My goal is to implement conditional validation on a form where users initially fill out 6 required fields, and then choose between 'manual' and 'automatic' proc ...

When using the react-query library, the useQuery hook may not always return a defined value, leading

Experimenting with reactQuery in a demo app showcased in this repository. The app interacts with a mock API found here. Encountering an issue using the useQuery hook to call the following function in the product API file: export const getAllProducts = asy ...

What is the method for choosing an element by class name in TypeScript?

Currently, I'm working on creating a responsive menu bar that collapses on smaller screens. The challenge I'm facing is that I'm using TypeScript for this project. Is there any guidance on how to translate the following code into TypeScript? ...

Looping Angular Components are executed

I am currently developing an Angular application and encountering an issue with my navbar getting looped. The problem arises when I navigate to the /home route, causing the navbar.component.html components to duplicate and appear stacked on top of each oth ...

I encountered a CORS issue when attempting to call an Asp.Net Web API from an Angular 11 application hosted in IIS

Our current setup is as follows: Angular 11 / TypeScript app: It is hosted in IIS with an SSL/TLS certificate (HTTPS) and it sends user credentials (NTLM) to the backend API using the 'withCredentials' header. In order to handle CORS, we are pas ...

Angular: The fetched data from the API is coming back as undefined

I am trying to use the Highcharts module in Angular to build a chart. The data object needed for the chart is provided by an API, and this is the structure of the object: { "success": true, "activity": [ { &q ...

RXJS - Trigger a function based on a specific condition being fulfilled by a value emitted from an observable

I have created a search field with autocomplete functionality. By using an observable that monitors changes in the text field, I am able to trigger actions based on user input. this.term.valueChanges .debounceTime(300) .distinctUntilChange ...

The Node.js websocket server (utilizing the ws module) is not operating in a secure manner

I am facing an issue with my websocket server setup on a secure domain with SSL. It seems that the server is not using wss protocol, but instead sticking to ws. Below is the code snippet that shows how the WebSocket server is created: const httpsServer = ...

Angular 6 and the intricacies of nested ternary conditions

I need help with a ternary condition in an HTML template file: <div *ngFor="let $m of $layer.child; let $childIndex=index" [Latitude]="$m.latitude" [Longitude]="$m.longitude" [IconInfo]="$childIndex== 0 ? _iconInfo1:$c ...

Error TS2322: The function signature '(state: State, exRep: number, exName: string) => void' does not match the expected type 'Mutation' in Vuex when using TypeScript

I'm currently facing an issue while working with Vuex and TypeScript. I have encountered the following error in my code, but I am unsure how to resolve it: The error : TS2322: Type '(state: State, exRep: number, exName: string) => void' i ...

Create a user-friendly URL using the Router navigation feature

Currently, I am utilizing the navigate function within the Router class to create a URL from a component: this.router.navigate(['/menu'], { queryParams: { level, parent: name } }); Although it functions correctly in terms of setting this.route.p ...

Tips on how to reach an Angular component within a third-party library

I'm currently working on a web application that incorporates the Deezer player through the official JS SDK. I've run into an issue where I am unable to access my Angular component from within the Deezer event subscription. The arrow function does ...

Are there any other options for handling the click event for all elements in Angular besides writing a click function for

click here for code screenshots https://i.sstatic.net/3EHOU.png see more code screenshots here https://i.sstatic.net/CcFZq.png This image displays five(5) li elements, each with the same function. However, if there are many more li elements, I am intere ...

The TypeScript compiler is searching in an external directory for the node_modules folder

My angular 2 project is located in the directory /c/users/batcave/first_project. In that same directory, I have various files such as index.html, systemjs.config.js etc., and a node_modules folder that only contains @types and typescript. This means my @a ...

Checking the loaded status of an observable in Angular

When calling an observable that takes some time to resolve, I found myself needing to add a condition to check for a valid result. The current implementation seems functional, but I can't help feeling there might be a better way to handle this. Here& ...

Sustain Observables in Angular to maintain their functionality

I have a regular function that I'm attempting to convert into an Observable function. Although it wasn't originally designed for this purpose, I am in the process of making adjustments. Here is how my modified function looks: private func1(param) ...