Choosing multiple values in Angular Material Select - automatically preselected items

Taking on the role of an Angular developer, my task involves receiving a JSON-entity from an API and assigning its values to a FormGroup. Despite everything working as expected (with all values present in the FormGroup), the issue lies with the visual preselection of values in the mat-select.

All the functionality mentioned above is encapsulated within the onInit() method.

product-group-update.component.ts: full code: https://pastebin.com/hXLqBAcF

export class ProductGroupUpdateComponent implements OnInit {
  NO_PRODUCT: string = 'No product';
  editProductGroupForm: FormGroup;
  id: number;
  isFormSubmitted = false;
  availableProducts: Product[];
  toSelect: Product[];
 
  constructor(
    private formBuilder: FormBuilder,
    private productGroupService: ProductGroupService,
    private productService: ProductService,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private location: Location,
 
  ) {
  }
 
  ngOnInit(): void {
    this.editProductGroupForm = this.formBuilder.group({
      name: ['', [Validators.required, Validators.maxLength(100)]],
      description: ['', [Validators.required, Validators.maxLength(100)]],
      products: ['', []],
    });
 
    this.activatedRoute.paramMap.subscribe(params => {
      this.id = +params.get('id');
      this.productGroupService.getProductGroupById(this.id).subscribe(
        receivedProductGroup => {
          this.toSelect = receivedProductGroup.products;
          this.editProductGroupForm.setValue({
            name: receivedProductGroup.name,
            description: receivedProductGroup.description,
            products: receivedProductGroup.products,
          });
        }
      );
    });
    console.log(this.editProductGroupForm)
 
    this.productService.getAllProducts(new Page<Product>()).subscribe(response => {
      this.availableProducts = response.content;
    });
  }
 
  ...

}

product-group-update-component.html full code: https://pastebin.com/9GqyU2r2

<div class="col-md-12">
  <div class="card card-container">
 
    <form (ngSubmit)="submitForm()" [formGroup]="editProductGroupForm" class="new-obj-form" id="register-form">
      

      ...

 
      <mat-form-field appearance="fill" class="example-full-width">
        <mat-label>Products</mat-label>
        <mat-select formControlName="products" multiple [(value)]="toSelect">
          <mat-option [value]="NO_PRODUCT">{{NO_PRODUCT}}</mat-option>
          <mat-option *ngFor="let product of availableProducts" [value]="product">
            {{product.name}}
            <i><small>(ID: {{product.id}})</small></i>
          </mat-option>
        </mat-select>
      </mat-form-field>
 

    ...
 

    </form>
  </div>
</div>

The issue arises when attempting to visually preselect values using mat-select: https://i.sstatic.net/BZ889.png

Additional code snippets:

export interface Product {
  id: number;
  name: string;
  description: string;
  price: number;
  groupId: number;
  sold: boolean;
}


import {Product} from "./product";

export interface ProductGroup {
  id: number;
  name: string;
  description: string;
  products: Product[];
}

Answer №1

It's important to note that the items in availableProducts and toSelect are distinct objects. Even though they may have identical properties, they are separate instances, which is why comparing them directly will result in a false value and prevent selection.

There are two ways to address this issue:

  1. The mat-select component offers the option to use the compareWith function, allowing you to customize how the comparison is done (e.g. by Id). Check out the official Angular documentation here for more information. There is also an example available in the Material docs.
  2. Alternatively, you can utilize RxJS to merge both of your API calls and ensure that the items in your toSelect array are actual instances from the availableProducts collection.

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

Jasmine reported that there were no specifications found in the Angular project written in TypeScript

I'm facing a frustrating issue with Karma and Jasmine in my Angular 9 project. Despite setting up the configuration files correctly, I keep getting a "No specs found" message when running ng test. I have tried various adjustments, including creating d ...

Maintaining the essence of generics while encapsulating functions

I am currently facing a challenge in defining a function that can wrap any other function while maintaining the parameter types and return type. I have managed to achieve this when the function does not use generics, but I am encountering difficulties wi ...

Fast + Vue3 + VueRouter Lazy Load Routes According to Files

I am currently working on implementing Domain-Driven Design (DDD) to Vue, and the project structure looks like this: src - App - ... - router - index.ts - Dashboard - ... - router - index.ts - ... The goal is for src/App/router/index.ts to ...

Issues encountered while transitioning from Angular 2 to 4 using npm

I am facing a challenge in upgrading Angular 2 to Angular 4 using npm. I have tried running "npm update --save" in the terminal, but unfortunately, my package.json does not reflect the latest Angular 4 version and remains unchanged. Can someone please ad ...

Troubleshooting Angular Unit Tests: Issues with Observable Response

Currently, I am working on an Angular application that is a bit dated and I am in the process of unit testing to ensure that all functions are operating as intended. Specifically, my focus is on testing whether a function correctly returns the expected ht ...

Transfer data from current worksheet to fresh workbook in Script Lab

I am exploring how to utilize TypeScript in Script Lab for Excel to duplicate the active worksheet into a brand new workbook. I came across a sample script that duplicates the worksheet within the same workbook, but I am unsure of how to modify it to cop ...

Exploring support classes in an Angular application

Within my Angular project, I have not only component classes but also auxiliary classes for data model representation and data iterators. When Angular generates test classes for components, they are named in the format component-name.component.spec.ts I ...

How can I organize an array in JavaScript by date for presentation on a webpage?

Check out this code snippet: list.component.ts const data1 = [ { dateStart: "2020-02-14 00:00:01", name: 'Server1' }, { dateStart: "2020-02-13 14:00:01", name: 'Server1' }, ...

What is the best way to dynamically render a component and interact with its methods within Angular?

I'm currently utilizing Angular 17 for a small application and I'm looking to display various components (each with forms) in a dialog window. The dialog itself acts as a container with two buttons, where one button should trigger a method within ...

What is the best way to set up a property in a service that will be used by multiple components?

Here is an example of how my service is structured: export class UserService { constructor() {} coords: Coordinates; getPosition() { navigator.geolocation.getCurrentPosition(position => { this.coords = [position.coords.latitude, posit ...

Discovering identical objects in two arrays in Angular using TypeScript is a breeze

I've hit a roadblock with a TypeScript problem in my Angular service. I have an array of ingredients: private ingredients: Ingredient[] = [ new Ingredient('farina', 500), new Ingredient('burro', 80), new Ingredient('ucc ...

Is anyone able to assist with resolving the problem of `tsc` constantly monitoring `node_modules`?

Using the Expo platform has been a great experience for me. Here is a snippet from my tsconfig.json: { "compilerOptions": { "paths": { "@/*": [ "./src/*" ], ...

React App Creation: Issue with ESLint configuration in TypeScript environment

I recently built a React app with the CRA (typescript template), but I noticed that TypeScript isn't adhering to the rules specified in the ESLint configuration. This is puzzling because I have consistently used this configuration in all my React proj ...

The AutoComplete feature of MaterialUI Component fails to function properly even when there is available data

I am facing an issue with my component as it is not displaying the autosuggestions correctly. Despite having data available and passing it to the component through the suggestions prop while utilizing the Material UI AutoComplete component feature here, I ...

Using multiple providers for a singular InjectionToken within a specific route

I am facing a situation where I need to use a component in two different routes, with each route requiring different services. However, I am unsure of the best approach to achieve this without adding logic to the component to determine which service to use ...

Unable to compile Angular 5 using the AOT systemjs configuration

I've hit a roadblock in finding a solution to my issue. Maybe someone out there can lend me a hand. I'm in the process of upgrading from ng 4.4.4 to 5.0.1 and everything seems to be functioning fine in JIT mode. However, when attempting to compi ...

Why is patchValue not functioning as expected? Is there another method that does the job

Encountering an issue with the image upload feature on a component form that consists of 8 entries - 7 text inputs and 1 image upload field. While all data is successfully submitted to the node server, the image upload function only sporadically works. Wh ...

Encountering an error in TypeScript and ng2 rc.1: Error message (20, 15) TS2304 indicates that the name 'module' cannot be found

Having trouble with TypeScript and ng2 rc.1 - getting Error:(20, 15) TS2304: Cannot find name 'module'. I encountered this issue when trying to use a directive of the module in my code: @Component({ selector: 'Notes1', moduleI ...

Notifying the Angular 8 navbar component of changes in another component

The index.html file contains the following code snippet: <app-root></app-root> Below are the contents of app.component.ts and app.component.html: import { Component } from '@angular/core'; @Component({ selector: 'app-root& ...

Managing the state of a component in Angular

In the process of uploading files to blob storage using a component, I have encountered an issue with my side bar navigation. Specifically, I am looking for a method to ensure that the progress of file uploads is maintained even when switching between co ...