Issue with form array patching causing value not to be set on material multiple select

When attempting to populate a mat-select with multiple options using an array of ids from Firestore, I encountered an issue. The approach involved looping through the array, creating a new form control for each id, and then adding it to the formArray using the reactive form push method. Despite successfully patching values into the form group, the material select component was not pre-populating as expected.

patchValueForm(portfolio: any) {
 this.formGroup.patchValue(portfolio);

 for (const id of portfolio.property_ids) {
   const control = new FormControl(id);
   if (!this.property_ids.getRawValue().includes(id)) {
     this.property_ids.push(control);
   }
}
console.log(this.formGroup.getRawValue()); }

The HTML snippet used for the mat-select part is:

 <mat-form-field appearance="outline">
          <mat-select [formArrayName]="'property_ids'" multiple>
            <mat-option *ngFor="let property of properties; let i = index" 
                        (onSelectionChange)="updatePropertyIdArray(property.property_id)" >
              {{property?.address?.first_line_address}}
            </mat-option>
          </mat-select>
          <mat-error>Please select at least one property</mat-error>
        </mat-form-field>

Even after exploring various methods online, the material select component remained unpopulated. If anyone has encountered a similar challenge before, I would appreciate any insights or solutions.

Answer №1

Instead of using formArray in the mat select, I suggest utilizing a simple formControl. This way, the formControl can hold the selection array and you can easily use formControlName.

 <mat-form-field appearance="outline">
      <mat-select [formControlName]="'property_ids'" multiple>
        <mat-option *ngFor="let property of properties; let i = index" [value]="property.property_id" 
                    (onSelectionChange)="updatePropertyIdArray(property.property_id)" >
          {{property?.address?.first_line_address}}
        </mat-option>
      </mat-select>
      <mat-error>Please select at least one property</mat-error>
    </mat-form-field>

In addition, ensure that there is a value binding in the mat option for the select to function correctly.

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

The resend email feature isn't functioning properly on the production environment with next js, however, it works seamlessly in the development environment

import { EmailTemplate } from "@/components/email-template"; import { Resend } from "resend"; const resend = new Resend("myApiKey"); // this works only in dev // const resend = new Resend(process.env.NEXT_PUBLIC_RESEND_API_KE ...

Angular UI Router allows for the resolution of data before a state

When working on my angular sample route, I attempted to achieve the following: (function(angular){ 'use strict'; angular .module('appRouter',['ui.router']) .controller('routerCtrl',function( ...

Encountering a CouchDB 401 Unauthorized Error

I have a couchDB database named "guestbook". Initially, I utilized the following code to add a user to the "_users" database: $scope.submit = function(){ var url = "https://sub.iriscouch.com/_users/org.couchdb.user:" + $scope.name; console.log(url); $ht ...

javascript selecting window location strings

Hey there, http://localhost/estamo/asset.php?aname=VklQIFBsYXph&di=Ng== I have this URL and I want to retrieve it using Javascript: var locat = window.location.href; $.get("enviaramigo.php?email="+$("#email").val()+"&url="+locat, function(h ...

Exploring the functionality of typeahead with server-side data integration

I am utilizing ng-select with Angular 7 and creating the following component: export class PostComponent { selectedCategoryID: number; allCategories$: Observable<CategoryModel[]>; constructor(private catService: CategoryService) { } ngOn ...

Harmonizing database with AJAX-powered webpage

When using ajax calls to update data on a web page, what is the most effective way to synchronize changes with a database? For example, if I have a comment form that needs to work asynchronously. I write JS code to submit the form data to the database, but ...

While working with AJAX, the variable value remains static and is not refreshed

My jQuery code successfully calls a REST Service and handles the response in the AJAX Success event. However, I'm facing an issue where the variable "SelectedVal" (document.getElementById('Text1').value) is not getting updated with each cli ...

Creating objects based on interfaces in TypeScript is a common practice. This process involves defining

Within my TypeScript code, I have the following interface: export interface Defined { 4475355962119: number[]; 4475355962674: number[]; } I am trying to create objects based on this interface Defined: let defined = new Defined(); defined['447 ...

What is preventing me from performing CPU profiling in Node.js when the process is blocked by the operation String(str).replace(some_regexp, '')?

As an illustration, the blow function testReplace will block the Node.js process: function testReplace() { let str = '<br/> 早餐后自由活动,于指定时间集合自行办理退 ...

Steps for Signing Up for a Collaboration Service

I'm struggling to understand how to monitor for new values in an observable from a service. My ultimate objective is to integrate an interceptor, a service, and a directive to show loading information to the user. I have set up an interceptor to liste ...

Angular FormControl is a built-in class that belongs to the Angular forms module. It

I’ve been working on adjusting tslint for the proper return type, and here’s what I have so far: get formControls(): any { return this.form.controls; } However, I encountered an error stating Type declaration of 'any' loses type-safet ...

Encountered a 'angular is not defined' error message when attempting to upgrade an AngularJS1 component

I am currently in the process of upgrading AngularJS1 components to Angular6. My approach involves creating wrappers for all existing AngularJS1 components by extending "UpgradeComponent" and placing them under the folder "directive-wrappers" in my example ...

Testing a React component's function within the confines of a Redux Provider component

My current challenge involves unit-testing a React component called TodoList. This component essentially maps through items and displays them in the render method. These items, of type TodoItem, are retrieved from the Redux store using MapStateToProps. Be ...

Issue with conditional comment in IE 8 not functioning as expected

Struggling with changing the SRC attribute of my iFrame specifically for users on IE 8 or older. This is the code I have written: <script> var i_am_old_ie = false; <!--[if lte IE 8]> i_am_old_ie = true; <![endif]--> </script> ...

JavaScript - Removing an Array from an Object

Can an array be removed from an object? For instance, suppose I have an object named response with an array inside it called items: var response = { success: false, items:[] }; What is the method to remove 'items' from the response object? Tha ...

Trying out the ClientPortal in Next.JS with Jest Testing

I'm currently working with NextJS and I want to run tests on the ClientPortal component. My testing toolkit consists of Jest and React Testing Library. Below is a sample code snippet for the ClientPortal component: import { useEffect, useRef, useStat ...

Compiling TypeScript to JavaScript with Intellij IDEA while preserving the folder hierarchy

Seeking assistance with maintaining directory structure when compiling Typescript to Javascript in Intellij Idea. The current directory setup is as follows: root - ts - SomeClass1.ts - SomeFolder - AwesomeClass2.ts - tsc The desired compiled file ...

I will not be accessing the function inside the .on("click") event handler

Can someone help me troubleshoot why my code is not entering the on click function as expected? What am I missing here? let allDivsOnTheRightPane = rightPane.contents().find(".x-panel-body-noheader > div"); //adjust height of expanded divs after addi ...

Guide to executing specific functions based on selected dropdown options in Angular 5

Several drop down menus need to be implemented. The requirement is that when an option from the drop-down is selected, a corresponding custom function should be called. However, in the code below, what should replace opt.mtd since it is not functioning as ...

Caution: Additional server attributes detected: style

Alert in my Next.js project, I encountered the following message: Notice: Server is sending additional attributes: style I am uncertain about the source of this warning and therefore unable to provide any code snippet. ...