Create a search filter feature using mat-select with the ability to select multiple

I am currently working on implementing a search filter for a multiple mat-select, but I have encountered an issue when searching and selecting items.

While my search function is functioning correctly, the problem arises when I search for an item, select it, then search for another item and select it as well. Only the last selected item remains due to my search not being reset, but I am unsure how to address this issue.

I attempted to clear the search input when closing the mat-select panel, however, this approach did not yield the desired result.

HTML:

<mat-select formControlName="testCategories" [(ngModel)]="testCategories"
    multiple>
    <input matInput class="search-input" type="text" placeholder="Search..."
        (keyup)="onKey($event.target.value)" (keydown)="$event.stopPropagation()">
    <mat-select-trigger>
        <mat-chip-list>
            <mat-chip *ngFor="let category of testCategories" [removable]="true"
                (removed)="removeCategory(category)">
                <div class="chip-text">{{ category.name }}</div>
                <mat-icon class="icon-delete-circle-reverse" matChipRemove></mat-icon>
            </mat-chip>
        </mat-chip-list>
    </mat-select-trigger>
    <ng-container *ngFor="let category of selectedCategories">
        <mat-option [value]="category.id">
            {{ category.name }}
        </mat-option>
    </ng-container>
</mat-select>

TS:

    onKey(value: string) {
        this.selectedCategories = this.search(value);
    }

    search(value: string) {
        this.filter = value.toLowerCase();
        return this.categories.filter(option =>
            option.name.toLowerCase().startsWith(this.filter));
    }

Answer №1

 handleKeyInput(text: string) {
        this.selectedCategories.push(this.filterResults(text));
    }

Answer №2

The method search(value: string) will return an array. You can give it a try with the snippet below:

onKey(value: string) {
    this.selectedCategories.concat(this.search(value));
}

Here is the HTML code:

<mat-select formControlName="testCategories" [(ngModel)]="testCategories"
multiple>
<input matInput class="search-input" type="text" placeholder="Search..."
    (keyup)="onKey($event.target.value)" (keydown)="$event.stopPropagation()">
<mat-select-trigger>
    <mat-chip-list>
        <mat-chip *ngFor="let category of selectedCategories" [removable]="true"
            (removed)="removeCategory(category)">
            <div class="chip-text">{{ category.name }}</div>
            <mat-icon class="icon-delete-circle-reverse" matChipRemove></mat-icon>
        </mat-chip>
    </mat-chip-list>
</mat-select-trigger>
<ng-container *ngFor="let category of selectedCategories">
    <mat-option [value]="category.id">
        {{ category.name }}
    </mat-option>
</ng-container>

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 is the best method to remove a value from a JSON object in a CSV file?

I received a JSON response like this: xxx: ["fsd,das"] I am looking for a way to remove the value "fsd" from the JSON object. The issue is that the response inside the JSON is not actually an array, but rather a CSV format. How can I go about deleting it ...

Dissimilarities in behavior between Angular 2 AOT errors

While working on my angular 2 project with angular-cli, I am facing an issue. Locally, when I build it for production using ng build --prod --aot, there are no problems. However, when the project is built on the server, I encounter the following errors: . ...

The Sharp Promise<Buffer>[] lacks some essential properties compared to the type Promise<File | File[]>: specifically, then, catch, finally, and [Symbol.toStringTag]

I wrote a script to verify and convert images as they pass through. Utilizing resources from nestjs, magic-bytes.js, and Sharp. However, I encountered the following error: Type 'Promise<Buffer>[]' is missing the following properties from ...

Dependency management with various versions of an NPM package

I'm feeling a bit puzzled about NPM package versions. In my ionic2 app's packages.json file, I have a dependency on [email protected]. Additionally, I have the latest version of ionic-native which is dependent on [email protected]. Th ...

``Inconsistencies in how the StatusBar is displayed on emulators versus

After creating a simple tab navigation with content inside, I encountered an issue where the button is hidden under the StatusBar on the Android emulator, but not on an actual device. I have confirmed that no global styles are applied. Can anyone provide a ...

Issue Establishing Connection Between Skill and Virtual Assistant Via Botskills Connect

Encountering errors while connecting a sample skill to a virtual assistant. Both are in typescript and function individually, but when using botskills connect, the following errors occur: Initially, ran botskills connect with the --localManifest parameter ...

Angular validation is malfunctioning for fields that have names ending with periods

Currently in the process of generating dynamic input fields <input class="form-control-lg form-control" placeholder="{{data.DisplayName}}" formControlName="{{data.labelName}}" type="text" maxlength="13" ...

Underscore.js is failing to accurately filter out duplicates with _uniq

Currently, I am integrating underscorejs into my angular project to eliminate duplicate objects in an array. However, I have encountered an issue where only two string arrays are being kept at a time in biddingGroup. When someone else places a bid that is ...

Describe the TypeScript type for an object with constant keys

My query resembles the one found in this Typescript interface definition question, but has a slight variation. I am beginning with an object where the keys are constants: const KEYS = { KEY1: 'hello', KEY2: 'world' } as const; How ...

Unlock the potential of your Windows system by running multiple Node versions at the

Despite finding several related questions on Stack Overflow, none were able to resolve my issue. Fortunately, there is a project called NVM for Windows that can help with this problem by allowing users to switch between multiple Node.js versions. However ...

security fails to redirect promptly

There seems to be an issue with the page not redirecting correctly when using "the guard," resulting in the URL staying as http://localhost:8100/ instead of http://localhost:8100/auth, which causes a blank page to display. In the file auth.guard.ts: canL ...

Mastering the art of chaining concatMaps in RxJS within AngularorUnlock

this.route.params.pipe( concatMap((param) => { const ein = param['nonprofit-id']; return this.nonprofitService.getNonprofit(ein).pipe( switchMap((nonprofit) => { this.nonprofit = nonprofit; ...

What are the top tips for creating nested Express.js Queries effectively?

I'm currently exploring Express.js and tackling my initial endpoint creation to manage user registration. The first step involves verifying if the provided username or email address is already in use. After some investigation, I devised the following ...

Failed to update the innerHTML attribute for the anchor tag

I'm attempting to apply styles through DOM manipulation using Angular's renderer2. I have successfully updated styles for all HTML elements except for anchors. In the example below, I am trying to replace the text www.url.com with World within ...

Tips for determining the datatype of a callback parameter based on the specified event name

Let's say we have the following code snippet: type eventType = "ready" | "buzz"; type eventTypeReadyInput = {appIsReady: string}; interface mysdk { on:(event: eventType, cb: (input: eventTypeCallbackInput) => void) => void } mysdk.on("ready", ...

React component encounters 'Object may be undefined' error from TypeScript upon importing object

Recently, I started using TypeScript but encountered 'Object is possibly undefined' errors when working with imported objects and trying to iterate over their arrays. I gave the non-null assertion operator a try, but it didn't solve the iss ...

Setting up Zurb Foundation in a VueJS TypeScript project: Step-by-step guide

I'm currently facing a challenge involving the integration of Zurb Foundation v6.5.3 into a VueJS project that is TypeScript-based and was created using @Vue/CLI. The project already includes jQuery type definitions. In the code snippet below, you can ...

Executes the function in the child component only if the specified condition evaluates to true

When a specific variable is true, I need to call a function in a child component. If the variable is false, nothing should happen. allowDeleteItem = false; <ChildComponent .... removeItemFn={ deleteFn } /> I attempted to use the boolean variable wi ...

What advantages does asynchronous microservices communication offer when it comes to enhancing the user interface experience?

When working with my Angular UI, I make a call to an API gateway endpoint like this: this.http.post(`/order`).subscribe(order => addNewOrderToList(order)); Following best practices in microservices architecture, the /order handler should publish an ev ...

Is it important to retain route parameters in nested routes?

One interesting scenario I'm facing involves a series of routes structured like this: const appRoutes: Routes = [ { path: 'thing/:id', component: GenericComponent }, { path: 'thing/special', ...