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

Is the username you want available?

I am facing a challenge in my registration form validation process where I need to verify the username input using javascript and flask in python, but the implementation is unclear to me. The requirement is to utilize $.get in the javascript segment along ...

What are some ways to make session variables available for sub applications?

I am currently working on setting up an API to interact with a MongoDB database, which I have integrated as a subapplication. In my server controller, I have created a session variable. However, I am facing an issue where the session variables are not be ...

The method Office.context.mailbox.item.internetHeaders.setAsync has not been configured

I am integrating the Microsoft Office API into Outlook. I'm attempting to add an extra x-header to my email in the composer scope for later identification. To achieve this, I referred to the following documentation: https://learn.microsoft.com/en-us/j ...

Using Vue 3 to have the ability to include multiple composable instances in a single script tag

Currently in the process of revamping our components that are originally built using the Options API. A key point for refactoring from a code-cut perspective is how we handle our multiple modals, each with their own open/close and boolean logic scattered t ...

Is there a way to implement a scrollbar that only scrolls through one specific column in an HTML table?

I need help adding a scrollbar to a specific column in an HTML table. Take a look at this scenario https://jsfiddle.net/6wpdc4tL/: https://i.stack.imgur.com/svzIg.png This table should have two scrollbars, one for the light blue SCROLL column and another ...

Use Onblur and Onfocus events in an input field that is read-only

Here is an input field: <input class="" type="text" id="Name_11_1" name="Name" value="Your name:"> I would like to modify it as follows: <input class="" type="text" id="Na ...

Display debugging information in the console using bunyan

child.log.info('info'); child.log.debug('debug'); When running the command: node app.js | bunyan -o short -l debug I am encountering an issue where only INFO messages are displayed and DEBUG messages are not showing up. I want to be ...

What is the technique for integrating a required file into an Angular module using Browserify?

My Angular SPA build is set up to use NPM for calling the browserify script to bundle it. To execute the build process from the terminal, you can run npm run build:js, which triggers the following script in the package.json file: "build:js": "browserify - ...

Dealing with 404 page not found error without replacing the default in Next.js 13

I followed the Next.js 13 documentation's suggestion to create a file called not-found.jsx in my app directory to handle 404 errors. But, despite placing it inside the app directory and intended for layout and loading purposes, it is not overriding th ...

React typescript is handling various promise response types, causing strange behavior in type-checking

I recently started utilizing the and I seem to be encountering a perplexing issue. If further context is needed, please let me know and I will provide it. All the necessary functions and types are mentioned below my explanatory paragraphs. Your assistance ...

Is it possible to retrieve a variable from a geojson file using Vue 3 and Vite?

For my Vue 3 project, I am trying to import a variable from a geojson file. However, when I use import line from '@static/line.geojson', my page goes blank and it seems like Vue stops working. If I use import line from '@static/line.json&ap ...

jQuery is failing to properly render dynamic content data identifiers

Need help with a dynamic HTML div <a data-id="17" onclick="getcustomer();"> <div class="note note-success"> <h4 class="block">A</h4> <p>Email : <a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

Issue with accessing data in React Admin Show Page using useRecordContext() function leads to undefined return

Within a basic RA application, I am attempting to showcase an item known as a "card" utilizing a Show Page. The fields—specifically id and title—are being presented correctly. Nevertheless, the useRecordContext() hook is consistently returning undefin ...

The $resource.query function will now return an array of characters instead of a single string when splitting strings

Recently, I've been working on utilizing an Angular $resource in my project. Here's a snippet of the code: angular.module('app') .factory('data', function ($resource) { var Con = $resource('/api/data', {}, { ...

Creating dynamic select boxes in Django Admin using jQuery

In my Contract class, the contract_mod field is designed to extend a contract from a previous one and should only display contracts related to the selected person. The Contract class returns the person field, but since I have no experience with AJAX/jQuery ...

Implementing React component that clears state upon selecting a place with Google Autocomplete

I've encountered a issue while using the Google Autocomplete component. Whenever I select a place and use the onPlaceSelected function to save it into a state array (input) of the parent component, the previous value gets replaced with an empty array ...

Engaging with tasks like incorporating fresh elements into JavaScript code

I am looking to implement an event listener that triggers whenever a new element is added to the document or any of its children. Can someone recommend a method for accomplishing this? ...

Experiencing difficulties when utilizing Jest to test components

I recently started working with Jest and JavaScript. I wrote a test for one of my components, but it's failing, and I'm struggling to figure out what's wrong (seems like something related to enzyme). Here is the output: ● Console co ...

Angular 2 error: "HttpService Provider Not Found"

In my Angular 2 / Ionic 2 project, I have the following "constellation" of components and services: Component1 -> Service1 -> Service3 Component2 -> Service2 -> Service3 (where -> denotes a relationship like "using" or "calling") Whenever ...

Travis build unsuccessful due to version inconsistencies

I am facing an issue where my locally working application is failing to build on TravisCI. After some research, I realized that I used "latest" as the version for dependencies in my package.json file. :rekolekcje-webapp:npmInstallnpm WARN deprecated <a ...