Angular Auto-suggest feature with Object naming convention that distinguishes between the object name and its

I need help filtering an array of objects based on user input. The challenge I'm facing is that the object structure includes both a name and a value, unlike a simple string array. How can I modify the existing code (which currently works for a string array) to work with an array of objects?

HTML

<input type="text"  placeholder="{{ 'string' | translate }}*" matInput formControlName="example" [matAutocomplete]="exampleAutoComplete" (keyup)="filterExample($event)">
<mat-autocomplete #exampleAutoComplete="matAutocomplete" [displayWith]="displayExample">
    <mat-option *ngFor="let example of exampleArray" [value]="example.id">
        {{example.name | titlecase }}
    </mat-option>
</mat-autocomplete>
<mat-error *ngIf="companyInfoFormGroup.get('example').invalid">
    <ng-container *ngIf="companyInfoFormGroup.get('example').errors.required">
      string
    </ng-container>
    <ng-container *ngIf="companyInfoFormGroup.get('example').errors.example">
       string
    </ng-container>
    <ng-container *ngIf="companyInfoFormGroup.get('example').errors.maxlength">
      string
    </ng-container>
</mat-error>
</mat-form-field>

TYPESCRIPT

displayExample = (id: string): string => {
    if (!id) {
        return '';
    }

    this.exampleName =  this.exampleArray.find((item: { id: string, name: string }) => {
        return item.id === id;
    }).name;

    return this.exampleName;
}

public filteredExamples(event): void {
    this.filteredExampleNames = this.filteredExampleNames
        .filter((example: string) => example.toLowerCase().includes(event.target.value.toLowerCase()));
}

I am aware that the current filter method is suitable for a string[], but I need guidance on adapting it for an array of objects.

OBJECT

{
  "id": "f0493847-f05e-ea11-a811-342cd25c7c6",
  "name": "example 1"
}

Answer №1

If you want to simplify the process, you can search for attributes that contain a specific string like this:

function filterItems(event) {
    const searchTerm = event.target.value.trim().toLowerCase();
    this.filteredItems = this.filteredItems
        .filter((item) => {
            return item.id.toLowerCase().indexOf(searchTerm) !== -1 ||
                item.name.toLowerCase().indexOf(searchTerm) !== -1
        });
}

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

Encountered an issue with retrieving schema during self-referencing validation with openapi generator

I created an openapi specification and now I am looking to generate a client for it. openapi.yaml After some research, I decided to use the openapi generator to create a typescript-axios client. This is the command I used: openapi-generator-cli generate ...

How can I delay the loading of a lazy loaded module in Angular until certain data is resolved from an API call?

How can I preload data before loading a lazy module in Angular? I attempted using app_initializer, but it didn't work due to an existing app_initializer in AppModule. Is there a different approach to achieve this? ...

Using ngModel to bind data within an Angular dialog box

I'm facing an issue with my project where changes made in the edit dialog are immediately reflected in the UI, even before saving. This causes a problem as any changes made and then canceled are still saved. I want the changes to take effect only afte ...

What is the best way to handle updating an npm package that is not the desired or correct version?

I've been experimenting with querying data on Firebase using querying lists. My attempt to implement functionality similar to the documentation resulted in this code snippet: getMatchesFiltered(matchId: string, filter: string, sortDirection: string, ...

Unable to integrate moment.js or ng2-bootstrap into my Angular 2 project

While running my gulp tslint task, I encountered an error message. It seems that I need to add moment.js in order to satisfy ng2-bootstrap. In node_modules/ng2-bootstrap/components/datepicker/date-formatter.ts(1,25), I received the following error: &apo ...

The code breaks when the lodash version is updated to 4.17.4

After updating lodash to version 4.17.4, I encountered an error in Typescript that says: TypeError: _.uniqBy is not a function Uncaught TypeError: _.split is not a function The code snippet in question is as follows: import * as _ from 'lodash&apo ...

In TypeScript, when 'this' does not have a specified type annotation, it will implicitly be of type 'any'

I'm facing challenges with redirecting in React using TypeScript. I know it's possible to configure the TS settings to avoid using implicit "this" keyword, but I don't think that's the right approach to truly "fix" it, just a workaround ...

Dealing with Incoming HTML Content from Backend in Angular 5

My backend is sending me HTML with a Facebook login, but the observable is attempting to parse it before I can make any changes... I'm having trouble explaining this issue to search engines, so any help understanding the professional terms related to ...

Update information according to the drop-down choice made from a different, unrelated component in Angular

I have different components that are not related. When I select a company from the header component, I want to immediately display data that matches the selected company. Currently, the data changes only when I visit another page and then return, but I nee ...

The argument passed cannot be assigned to the parameter required

Currently, I am in the process of transitioning an existing React project from JavaScript to TypeScript. One function in particular that I am working on is shown below: const isSad = async (value: string) => { return await fetch(process.env.REACT_AP ...

Having trouble opening a modal view from an action sheet button

Currently, I am in the process of working on a school project and facing an issue where I am trying to open a modal view from an action-sheet button. However, I encounter the following error message: TypeError: Cannot read property 'addMedicationModal ...

Tips for duplicating chosen documents utilizing AngularCLI in conjunction with WebPack for the production build

I am facing an issue with my Angular2 app when building it for production using Angular CLI and WebPack. In order to deploy the app to our production server (IIS), I need to copy certain files to the dist folder. Specifically, I require the web.config and ...

Best method for including a property to a bespoke Angular 2 component

Our Angular 2 application features a custom input component. How can we properly incorporate an attribute into our custom component? Here is an outline of how our input component looks: input-debounce.component.ts var template = ` <input [type]= ...

How to conditionally make a property optional in Typescript depending on the value of another property

I'm a newcomer to Typescript and I've encountered a scenario that has been difficult for me to find a solution for. Any suggestions would be greatly appreciated. My goal is to have the property options be optional when the type is either SHORT_T ...

Guide on executing get, modify, append, and erase tasks on a multi-parameter JSON array akin to an API within Angular

I have a JSON array called courseList with multiple parameters: public courseList:any=[ { id:1, cName: "Angular", bDesc: "This is the basic course for Angular.", amt: "$50", dur: & ...

Problem with jHipster image display

I'm facing an issue while trying to load an image using Angular. The source of the image should come from an attribute of an object within an *ngFor loop, like this: <div *ngFor="let object of objects"> <img src="{{object.imagePath}}"> ...

What is the solution to the problem of a missing property in a TypeScript or Firestore project?

Here is a snippet of code from my TypeScript project: admin.firestore().collection('posts').doc(postId).get().then((data) => { let likesCount = data.data()?.likesCount || 0; let likes = data.data()?.likes || []; let u ...

Implement the usage of plainToClass within the constructor function

I have a dilemma with my constructor that assigns properties to the instance: class BaseModel { constructor (args = {}) { for (let key in args) { this[key] = args[key] } } } class User extends BaseModel { name: str ...

Having trouble retrieving information from Node.js service in AngularJS 2

I am currently expanding my knowledge of Angular and attempting to retrieve data from a node js service using Angular 2 services. When I access the node js services directly from the browser, I can see the results. However, when I attempt to fetch the dat ...

Is it possible to deactivate the error message related to "Unable to ascertain the module for component..."?

I recently incorporated a new component into my TypeScript2+Angular2+Ionic2 project. Right now, I have chosen not to reference it anywhere in the project until it is fully developed. However, there seems to be an error thrown by Angular/ngc stating "Cannot ...