Tips for implementing a real-time search feature in Angular

I require assistance. I am attempting to perform a live search using the following code: when text is entered into an input, I want my targetListOptions array, which is used in a select dropdown, to update accordingly. The code runs without errors, but nothing happens when data is inputted. My goal is to search based on the name field retrieved from the backend. I am aiming for a basic input approach without relying on autocomplete. Could you please advise me on how to properly implement this search functionality and identify any mistakes in my code? Thank you sincerely.

HTML

<mat-select formControlName="targetListValue">
   <input formControlName="searchTargetInput">
   <mat-option *ngFor="let targetItem of targetListOptions" [value]="targetItem.id">
     {{ targetItem.name }}
   </mat-option>
</mat-select>

Typescript

public form: FormGroup;
public targetListOptions: ITargetData[] = [];

ngOnInit(): void {
   this.form = new FormGroup({
     templateListValue: new FormControl(null, [Validators.required]),
     searchTargetInput: new FormControl('')
   })

this.form.controls.searchTargetInput.valueChanges.subscribe(() =>
   this.targetListOptions = this.targetListOptions.filter(element => element.name.includes(name)));

}

Answer №1

  1. At the outset, it seems there is a flaw in your line of code. How do you obtain the new searchTargetInput value? Your current code subscribes to the valueChanges but does not capture the new value. See what you are currently doing:

    this.form.controls.searchTargetInput.valueChanges.subscribe(() =>this.targetListOptions = this.targetListOptions.filter(element => element.name.includes(name)));}

Instead, consider revising your code as follows:

this.form.controls.searchTargetInput.valueChanges.subscribe((inputValue) => {
  this.filteredTargetListOptions = this.targetListOptions;
  this.filteredTargetListOptions = this.filteredTargetListOptions.filter(element => element.name.includes(inputValue));
});

Notice the difference in the arrow function argument?

  1. I'd advise against filtering the targetListOptions array directly. Imagine if a user enters something in the searchTargetInput field. Since we're subscribing to changes in that input, it will trigger the filtering process we've set up. However, with each subsequent filter operation, the original data from the backend gets overwritten by the filtered result stored in targetListOptions. Now, let's say the user makes a typo while typing in the search field. Even if they delete just one character, the targetListOptions will already have been permanently altered due to the initial filter operation. Here's a simple and effective solution.

Typescript

public form: FormGroup;
public targetListOptions: ITargetData[] = [];
public filteredTargetListOptions: ITargetData[] = [];
ngOnInit(): void { /** your code*/}
  1. How are you populating the targetListOptions? Are these values fetched from the backend? If so, where is the backend call being made? If targetListOptions still holds the default empty array you initialized before ngOnInit, attempting to filter it will simply result in an empty array.

Answer №2

It is crucial to unsubscribe from your subscription in the ngOnDestroy lifecycle hook. Additionally, make sure to thoroughly debug your code and monitor any activities within the subscription. You can include console logs or utilize browser sources for debugging.

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

Running my Angular Single Page Application on a self-hosted ServiceStack service

Currently, I am utilizing ServiceStack to construct a small self-hosted RESTApi service with a NoSQL database and the setup is working perfectly fine (without using .Net Core). My next step involves creating some maintenance screens using Angular. Howeve ...

Why is npm installing a version of Angular CLI that is incompatible with its usage?

After using nvm to install node v16.13.2, as well as npm version 8.1.2, I discovered that this setup did not include the Angular CLI by default. To rectify this, I ran npm install -g @angular/cli. However, upon checking the version of Angular CLI with ng v ...

Alert: Circular dependency detected!

In an effort to have cleaner imports, I've set up a typescript file that exports all the components I'm using. For example: import { Comp1, Comp2, Comp3 } from index/components However, when using this approach, I encounter a warning during bu ...

What could be causing my matDialog to display incorrectly in Angular version 15?

After I upgraded my project to version 15 of Angular, following the official Angular documentation, I encountered an issue with my MatDialog not opening correctly. The problem seemed to stem from removing the entryComponents and transforming all components ...

Unlock the canGoBack feature in your Ionic 5 app with these simple steps!

I'm currently working on implementing a back button in my Ionic app, but I am running into an issue. I need to hide the back button when it's at the root level, which is dynamic and can change based on the flow of the app. I came across some code ...

``Error Message: TypeORM - could not establish database connection

I encountered an issue while running my project built with Typescript, Typeorm, and Express. The error message received when running the dev script was: connectionNotFoundError: Connection "default" was not found The content of my ormconfig.json ...

An instructional guide on seamlessly incorporating a TypeScript variable into an HTML element submission method

A problem arises in my Angular 8/Django 3 app as I attempt to incorporate a server-side variable called client_secret into the stripe.confirmCardPayment() method. The error message that keeps popping up is Property 'client_secret' does not exist ...

What might be causing the component in Angular and TypeScript to have trouble reading the data returned by the service?

I've been working on this for hours without success. I created a web API get method that returns a simple array. public Hero[] getHeroes() { return new Hero[] { new Hero { Id = 1, Name = "Hunain Hafeez-1" }, ...

Angular2 webpack example error: Cannot execute function 'call' because it is undefined

As I navigate through the Angular2 webpack sample app on https://angular.io/docs/ts/latest/guide/webpack.html, I've encountered an issue. After completing the "Development Configuration" section and attempting the "try it out" by copying the app code ...

What is the best way to extract data from API console output using Angular?

Currently, I am deeply involved in a full stack project utilizing asp.net and angularjs. My goal is to extract output response from the Swagger API. You can view the code I've written for this purpose here: (https://i.stack.imgur.com/vLyIE.png) The A ...

Unable to locate the module styled-components/native in React Native

When adding types in tsconfig.json to remove TypeScript complaints and enable navigation to a package, the code looks like this: import styled, {ThemeProvider} from 'styled-components/native'; The package needed is: @types/styled-components-re ...

The function you are trying to call is not callable. The type 'Promise<void>' does not have any call signatures. This issue is related to Mongodb and Nodejs

Currently, I am attempting to establish a connection between MongoDB and Node (ts). However, during the connection process, I encountered an error stating: "This expression is not callable. Type 'Promise<void>' has no call signatures" da ...

Endless cycle of NGRX dispatching

I tried creating a simple ngrx project to test the store, but I encountered an infinite loop issue. Even after attempting to mimic other examples that do not have this problem. To begin with, I defined 2 class models as shown below: export interface IBookR ...

Exploring different ways to customize the grid style in Angular 6

Here is the style I am working with: .main-panel{ height: 100%; display: grid; grid-template-rows: 4rem auto; grid-template-columns: 14rem auto; grid-template-areas: 'header header''sidebar body'; } I want to know how to cha ...

Sending a POST request in Angular5 using the HTTP module

Angular 5 Attempting to create a function that will generate a resource on my API using Angular has proven to be a challenge. The "employee.service.ts" file contains a method named "saveEmployee" which is triggered by a function called "addEmployee" locate ...

Standardized identification code

My request response needs to be defined, but the key name may vary. It will always be a string, but the specific key depends on the request. These are the possible responses: { someRequest: { message: 'success', status: 200 } } { someOtherReques ...

Adding a fresh element and removing the initial item from a collection of Objects in JavaScript

I'm working on creating an array of objects that always has a length of five. I want to push five objects initially, and once the array reaches a length of five, I need to pop the first object and push a new object onto the same array. This process sh ...

typescript What is the best approach to searching within a nested array?

I am struggling to extract a specific value from a nested array within an array. Here is an example structure of my array: [ { ConcessionId: 1, ConcessionName: "Coyotes", KnownAs: [ { TeamId: 1, ...

The variable 'React' is defined but not utilized in the code

Here's the code snippet in question: // tslint:disable import * as React from 'react'; import { Input, InputProps } from '../atoms/Input/Input'; import { FormControl } from '../hoc/FormControl/FormControl'; export const ...

What is the best way to execute a sequence of http requests only after the previous one has been completed successfully, while also addressing any

Working with Angular/rxjs 6 has brought me to a challenge. I'm struggling to get an observable sequence to run smoothly as intended. Here's the concept of what I'm trying to achieve: Request received to change systems: Check permissions Fe ...