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

What seems to be the issue with the useState hook in my React application - is it not functioning as

Currently, I am engrossed in a project where I am crafting a Select component using a newfound design pattern. The execution looks flawless, but there seems to be an issue as the useState function doesn't seem to be functioning properly. As a newcomer ...

Can Angular routing be used with a LAMP server?

I have decided to host my Angular 2 application on which offers a traditional LAMP stack for hosting. In my local ng serve environment, the route www.mysite.com/myapp/item/:id functions perfectly. However, when trying to access www.mysite.com/my-app/ite ...

Is it feasible to alter the file name while utilizing express-fileUpload library?

Is there a way to modify the file name of an uploaded file on the server side? app.post(URL, (req, res) => { let fileName = req.files.file.name; req.fileUpload; res.statusCode = HTTP_OK; res.send("Good Job") }) The settings I have in uploadF ...

Investigating SCSS Issues: The Problem with Absolute Imports

I am working on a project with the following structure: - my/project - assets - images - image-name.svg - source - components - MyComponent - MyComponent.module.scss - ... - ... ...

Similar to the getState() function in react-redux, ngrx provides a similar method in Angular 6 with ngrx 6

Recently, I developed an application with react and redux where I used the getState() method to retrieve the state of the store and extract a specific slice using destructuring. Here's an example: const { user } = getState(); Now, I am transitioning ...

What is the best method for accessing a store in Next.js with Redux Toolkit?

Currently, I am working on incorporating integration testing for my application using Jest. To achieve this, I need to render components in order to interact with various queries. However, in order to render a component, it must be wrapped in a Provider to ...

Improving efficiency of basic image carousel in Angular 8

In my Angular 8 app, I am developing a basic carousel without relying on external libraries like jQuery or NgB. Instead, I opted to use pure JS for the task. However, the code seems quite cumbersome and I believe there must be a more efficient way to achie ...

The Google Chrome console is failing to display the accurate line numbers for JavaScript errors

Currently, I find myself grappling with debugging in an angular project built with ionic framework. Utilizing ion-router-outlet, I attempt to troubleshoot using the Google Chrome console. Unfortunately, the console is displaying inaccurate line numbers mak ...

Issue with Ionic Native File: File.writeFile function - file is not being created and there is no callback response

I've exhausted all the different solutions I could find, but unfortunately, the file isn't getting saved and nothing seems to be happening. The callback functions aren't being called - neither success nor error. Here are the solutions I&apo ...

Tips on submitting JSON data to a server

I need the data to be structured like this {"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7f0c3f18121e1613511c1012">[email protected]</a>","password":"1"} but it is currently appearing like this { & ...

Using TypeScript's type casting functionality, you can easily map an enum list from C#

This is a C# enum list class that I have created: namespace MyProject.MyName { public enum MyNameList { [Description("NameOne")] NameOne, [Description("NameTwo")] NameTwo, [Description("NameThree")] NameThree ...

Issue encountered in event.d.ts file at line 74, character 76: TypeScript error TS2370: A rest parameter is required to be an array type

I am currently working on a project in Angular 6 and I encountered an issue while trying to integrate Google Maps into my website. When running ng serve, I received the following errors: ERROR in node_modules/@types/googlemaps/reference/event.d.ts(74,76): ...

Angular2 calendar and time selector

Having trouble setting up a date and time picker for my angular2 app. Can anyone provide assistance with this? I've experimented with the following methods: Ng2-datetime: I added it to the main app.module file: import { NKDatetimeModule } from &ap ...

What is causing elements like divs, paragraphs, or text not to display within an ion-item after an ion-input is added?

I am currently working on validating a simple form and everything seems to be functioning properly. However, I have encountered an issue with displaying text messages within an ionic 3 list item. The ion-item consists of an ion-input element. When I place ...

Can you explain the purpose behind using this syntax within the subscribe function?

.subscribe(data=> { this.timezones = data; } Is the 'data' variable used in the .subscribe() method the same as the one declared in the constructor (private: data)? What does the arrow symbol mean and what is its purpose? export class X ...

Ways to retrieve the length of the parent array within a component in AngularJS

Is there a way to access the value of a property in the parent from within a component? Parent: export class Animal{ animalID ?: Array<number>; { Child: import {Component, Input} from '@angular/core'; import {Animal} from '../anim ...

One way to display a table is by populating it with data from an API. If the table does

Within my Angular 6 application, there exists a table that displays data fetched from a web api. Additionally, I have incorporated some ngIf containers. One of these containers is programmed to exhibit a message in case the web api data turns out to be emp ...

How to define a TypeScript recursive object with a defined endpoint?

Welcome to my first question! I am currently facing an issue with defining an object to store strings in multiple languages. I am looking for a flexible solution and have considered using a nested object structure. However, I want the final object to adhe ...

The journey of an Angular and NGXS store application culminates in a seamless loop of store updates

Currently, I am utilizing NGXS as the store mechanism in my application. Within the store, there is a list of conditions that are displayed using the RuleEngineAddViewStepperConditionComponent component and the *ngFor directive on the UI. Each condition ha ...

Issue with Angular 2: Not receiving events when subscribing to a service's Subject property

Presented below is a service: @Injectable() export class AuthService { public reset: Subject<any>; constructor() { this.reset = new Subject(); } public logout() { this.reset.next('logout'); } } Here is an additional s ...