When adding additional items in Angular's mat-select with multiselect, previously selected options will be reset

I am encountering an issue with a mat-select in my Angular application that has multiselect enabled. Within the mat-select, there is an input used for filtering available options. The problem arises when I select some options, filter using the search input, and then add more options to the selection - the previously selected options are cleared. I want the previously selected options to remain selected as I continue adding more options through the search input. How can I modify my code to achieve this desired behavior?

<mat-select formControlName="services" 
                    #searchSelect 
                    multiple
                    [(ngModel)]="selectedServiceIds">
            <mat-option class="searchable input-group" disabled>
              <input
                [disabled]="false"
                type="text"
                [(ngModel)]="searchService"
                [ngModelOptions]="{ standalone: true }"
                placeholder="Search ..."/>

              <mat-icon class="float-right">search</mat-icon>
            </mat-option>
            <mat-option *ngFor="let service of services | filter : searchService"
                   [value]="service.id">
                        {{ service.name }}
            </mat-option>
</mat-select>

Answer №1

When facing a similar situation like this, my approach would involve incorporating a trackBy function within the ngFor directive. You can find more information here.

By utilizing a "standard" *ngFor, it automatically distinguishes each element of the provided iterable based on object identity behind the scenes.

To resolve this issue, you would need to implement something along these lines:

<mat-option *ngFor="let service of services | filter : searchService; trackBy: trackByFn"
                   [value]="service.id">
                        {{ service.name }}
            </mat-option>

In your .ts file

trackByFn(_i: number, option: { id: unknown } ) {
  return option.id;
}

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

Acquiring the handle of ngComponentOutlet

I am dynamically creating a component using ngComponentOutlet. Here is an example: import {Component, NgModule} from '@angular/core' import {BrowserModule} from '@angular/platform-browser' @Component({ selector: 'alert-success& ...

Access the Angular directive instance before it is actually rendered

Is it possible to access an Angular directive instance even if it has not been rendered yet? Let's say I have an app-component and a baz-directive. I want to be able to get the directive instance even if it is not currently shown or rendered in the D ...

Is the Angular 7 router '**' wildcard feature failing to work properly when used in conjunction with lazy loaded modules and child routes?

I'm currently working on setting up a default route using the wildcard '**' with Angular's router. The intention is for this default route to load a lazy module and then handle its own routes internally. However, I have run into an issu ...

Implementing a "Select All" feature in a Material UI multiselect component and then showcasing the selected values within

As a newcomer to Material UI, I am working on incorporating a select all feature in a material multiselect component. I have an array of objects: const names = [ { id: 0, name: "Oliver Hansen" }, { id: 1, name: "Van Henry" }, { id: 2, n ...

Activate the button when a checkbox within a looping structure is selected using Angular 5

As a relatively new Angular 5 user, I am working with a button that looks like this: <button *ngIf="type!='invoices' && this.action==='edit'" disabled (click)="genera(fields.termini)" class="ml-16 mat-raised-button mat-accen ...

Error: Angular detected a change in the expression after it was already checked

Being a novice in Angular, I am attempting to construct form validations using code. My requirement is that when I click on the Reset button, the fields should reset. To achieve this, I followed the code below. However, the issue arises when I tap on the ...

What methods can I employ to trace anonymous functions within the Angular framework?

I'm curious about how to keep track of anonymous functions for performance purposes. Is there a way to determine which piece of code an anonymous function is associated with? Here's an example of my code: <button (click)="startTimeout()&q ...

What is the best way to set up an endpoint in Angular for image uploading?

Using the Kolkov Angular editor in my Angular application, I have successfully created a rich text editor. Currently, I am looking to upload images from the editor to the server. I already have a function in place that takes a file as an argument and send ...

The side menu fails to appear when pressed

When using the push method, I am unable to see the side menu. However, it works fine with the setRoot navigation. How can I resolve this issue and display the side menu when using the push method? dashboard.html <ion-col col-9> <ion-searchbar ...

Unidirectional data flow from the document object model to the variable within the

When working with Angular, there are multiple methods available for binding variables to DOM properties. You can utilize the `{{}}` syntax, `[property]=expression`, or implement two-way ngModel binding. One aspect that I have not yet discovered is how to ...

What is preventing me from running UNIT Tests in VSCode when I have both 2 windows and 2 different projects open simultaneously?

I have taken on a new project that involves working with existing unit tests. While I recently completed a course on Angular testing, I am still struggling to make the tests run smoothly. To aid in my task, I created a project filled with basic examples f ...

Implementing custom click event for selecting checkboxes in Material-UI table rows

I have been working with the material-ui data table to implement sorting functionality. One feature I am trying to add is a checkbox on each row. The challenge I am facing is that when clicking on the checkbox, it also triggers the row link, which is not t ...

Is there a way to universally modify variant, color, style, and other properties for Material-UI components across the entire application?

Is there a way to simplify this code block: <Button variant="contained" color="primary" style={{textTransform: "none"}} > Description </Button> Can I achieve the same result with just: <Button> Description </Button> W ...

Adjust the dropdown selection according to the entered text

I am looking to dynamically change a select option based on the value entered in a text input field. For instance, when I type "mydomain.com," this is what should happen: I type "mydomain" I type "." (dot) The input stops accepting characters The script ...

Is there a way to customize the text "Number of rows" displayed in material UI TablePagination component?

Is it possible to customize the text "Rows per page" within the Material UI TablePagination component? I have searched everywhere without success... My goal is simply to translate it into Portuguese for my website. ...

Enhancing Material-UI Tabbar (Tabs) with Badge Feature

I am using the Material-UI Tabs component, which has 5 Tab components as children. I want to add a Badge to each tab to display unread items. The challenge I face is that I have two versions of the tab bar - one for desktop with icon and text, and anothe ...

"Take control of FileUpload in PrimeNG by manually invoking it

Is there a way to customize the file upload process using a separate button instead of the component's default Upload button? If so, how can I achieve this in my code? Here is an example of what I've attempted: <button pButton type="button" ...

Found a minor syntax problem in an Angular service related to error handling declaration

As I was working on customizing the Angular tutorial to fit my needs, I found myself wanting to merge the two error handler methods showcased in the tutorial into one. I appreciate the functionality of both methods and believe combining them will be benefi ...

Angular 2's Conditional Validation: A Comprehensive Guide

Angular 2 offers straightforward validation, which is a great feature. However, the challenge lies in making a required field optional based on another field's selection. Below are the validation rules: this.contractsFilter = this.fb.group({ selec ...

Tips for incorporating a personalized touch to your radio buttons

Is there a way to customize the appearance of radio buttons in React or HTML elements, such as the screenshot below? I want to maintain the display of the number No.01 followed by the label next to it. If you have any suggestions or solutions, please shar ...