Instructions for adding a select dropdown feature in Angular 6 that includes a search filter. Additionally, tips on how to filter objects by their name property

I need to add an auto-complete feature in my Angular 6 app where the data is displayed as objects in a dropdown and filtered as we type.

**template.html**
  <mat-form-field >
    <input matInput [matAutocomplete]="auto"  [formControl]="customerFilterControl">
       <mat-autocomplete #auto="matAutocomplete" [displayWith] = "displayFn">
         <mat-option *ngFor="let option of (filteredOptions | async)" [value] ="option">
           {{option.name}}
         </mat-option>
       </mat-autocomplete>
   </mat-form-field>

Typescript

import { Observable } from 'rxjs';
import { FormControl } from '@angular/forms';
import { map, startWith } from 'rxjs/operators'; 


export class Component1 implements OnInit {

 objectOptions = [
  { name:'Angular' },
  { name:'Angular Material' },
  { name:'React' },
  { name: 'vue' }
  ];
customerFilterControl = new FormControl();

 ngOnInit() {

  this.filteredOptions = this.customerFilterControl.valueChanges.pipe(
    startWith(''),
    map(value => this._filter(value))
  );

  }

_filter(value:string):string[] {
    const filterValue = value.toLowerCase();
    return this.objectOptions.filter(option => option.name.toLowerCase().includes(filterValue)); // how do I filter values here
  }

  displayFn(subject) {
    return subject ? subject.name : undefined;  
  }

Note : I have imported following modules in app.module.ts MatSelectModule, MatAutocompleteModule, MatFormFieldModule, MatInputModule

It gives me error when I try to filter object by name property

Answer №1

To assist you better, please share the specific error message you are encountering.

Upon reviewing your code, I have identified a mistake in the following line:

this.objectOptions.filter(option => option.toLowerCase().includes(filterValue))

In this context, option is an object, and calling toLowerCase() on it may not be appropriate. It seems like what you intended was:

this.objectOptions.filter(option => option.name.toLowerCase().includes(filterValue))

Edit I also noticed another issue in your code.

_filter(value:string):string[]

Your function is declared to return an array of strings, but actually returns an array of objects with a name property. To resolve this, you can either remove the return type and let typescript infer it automatically, or update it to:

_filter(value:string): {name: string}[]

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 "npm start" does not automatically recompile or display code changes

My experience with my Angular project has been smooth until today. Surprisingly, without making any changes, the "npm start" command suddenly stopped working properly. The project compiles successfully, but any subsequent code changes do not trigger an aut ...

I would like to know the method for inserting an HTML element in between the opening and closing tags of another HTML element using

Recently, I came across a coding challenge involving a textbox. <input type="text></input> The task was to insert a new span element between the input tags using jQuery, as shown below: <input type="text><span>New span element< ...

Steps for incorporating a filter feature in an Angular Material table

.HTML: Can someone assist me with implementing a filter in this component? I tried using it with the expansion table, but unfortunately, the filter is not working as expected. <mat-dialog-content style="width: 63rem; overflow: initial;"&g ...

Mocking a promise rejection in Jest to ensure that the calling function properly handles rejections

How can I effectively test the get function in Jest, specifically by mocking Promise rejection in localForage.getItem to test the catch block? async get<T>(key: string): Promise<T | null> { if (!key) { return Promise.reject(new Error(&apo ...

Is there an issue with the newline character ` ` not functioning properly in TypeScript when used with the `<br/>` tag?

Having trouble with using New Line '\n' ' ' in Typescript Here is an example of my typescript code: this.custPartyAddress = estimation.partyName + ',' + '\n' + estimation.partyAddress + ',' + ...

What steps are involved in creating animations on angular.dev?

I'm trying to recreate the animation on angular.dev. Specifically, I want to create a zoom effect on the Angular logo when scrolling. However, I'm unsure how to achieve this effect. If you visit this page , you'll see exactly what I mean. ...

Why does tsc produce a compiled file that throws an exception when executed, while ts-node successfully runs the TypeScript file without any issues?

I have written two ts files to test a decorator. Here is the content of index.ts: import { lockMethod } from './dec'; class Person { walk() { console.info(`I am walking`); } @lockMethod run() { console.info(`I am running`); } ...

Creating and utilizing multi-module NPM packages written in Typescript: A comprehensive guide

For a while now, I've been quite at ease creating and utilizing NPM packages with Typescript. However, these packages have typically been provided and consumed as a single module. Now, I'm interested in publishing packages that contain more than ...

change the width of a div element to match that of its nearest sibling element

Can the width of a div be automatically set to match its closest sibling when the width is set to width: auto;? In my coding example on jsFiddle, you can observe three colored divs - red, green, and blue. I am aiming for the blue div to adjust its size ba ...

Having trouble sending correct true/false values for selected radio buttons on an Angular5 table, often requiring users to click them twice to submit the appropriate values

My goal is to assign true or false values to selected radio buttons in each row and then form an object for submission. To distinguish between the radio button values in each row, I have used {{k}}+{{sizeobj.rbSelected}} as the value which is causing issue ...

Troubleshooting issues with sorting and pagination in Angular Material table functionality

I am experiencing an issue with sorting and pagination using an Angular material table. The data is being fetched from a store as an observable and successfully displayed in the table. Even though the column names for sorting match the column definitions, ...

How to resolve the issue of not being able to access functions from inside the timer target function in TypeScript's

I've been attempting to invoke a function from within a timed function called by setInterval(). Here's the snippet of my code: export class SmileyDirective { FillGraphValues() { console.log("The FillGraphValues function works as expect ...

Executing an asynchronous action without linking promises to subsequent actions

Encountered a challenge while using componentWillReceiveProps with redux async action. Below is the code snippet along with an explanation: componentWillReceiveProps(nextProps) { if(nextProps.job.status === 'applied'){ this.showAppliedDial ...

React Leaflet causing a frequent map refresh due to context value updates

When I use map.on('moveend') to update the list of markers displayed in another component, I encounter a refreshing issue. The context in my project contains two arrays - one filtered array and one array with the markers. When I try to update the ...

Discovering the method for retrieving JavaScript output in Selenium

Whenever I need to run JavaScript code, the following script has been proven to work effectively: from selenium import webdriver driver=webdriver.Firefox() driver.get("https:example.com") driver.execute_script('isLogin()') However, when I atte ...

Who needs a proper naming convention when things are working just fine? What's the point of conventions if they don't improve functionality?

I am a newcomer to the world of JavaScript programming and stumbled upon this example while practicing. <html> <head> <script type="text/javascript"> function changeTabIndex() { document.getElementById('1').tabIndex="3" d ...

Unattaching Events in AngularJS

I'm still navigating my way through the realms of Angular and MVC programming, uncertain if I'm on the right track. There's a jQuery snippet that I wish to implement in some of my partials, but not all. With event listeners that persist eve ...

Using dynamic imports in Next.js allows us to efficiently load modules based on variables defining the path

When utilizing dynamic import in Next.js, I am encountering an issue. The component renders successfully when the path is used directly, but fails to render when the path is accessed from a variable. const faq = dynamic(() => import('../faq/faq&apo ...

Having issues with Sencha Touch not initiating in mobile browsers

For quite some time now, I have been developing a mobile app using Sencha Touch 2.1 and conducting tests primarily on desktop Chrome and an iOS PhoneGap / Cordova package. Recently, I made the decision to release it as a "native" app while also offering re ...

What could be causing the malfunction of material-UI Tabs?

My Material UI Tabs seem to have stopped working after a recent update. I suspect it may be related to the react-tap-event-plugin update I installed. Initially, I thought it was due to tab indexing but even using values like value='a', value=&apo ...