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

Encountering a white screen while loading StaticQuery on Gatsby website

I encountered an error that has been reported in this GitHub issue: https://github.com/gatsbyjs/gatsby/issues/25920. It seems like the Gatsby team is currently occupied and unable to provide a solution, so I'm reaching out here for help. Just to clar ...

How can I ensure that a user variable stored in an Angular6 service remains defined and accessible from other components?

Currently, I am working on an Angular app and facing a challenge. After receiving a user variable from an asynchronous call to Firestore Cloud, I noticed that the variable is successfully set (verified using console.log()). However, when I navigate between ...

Using the textbox input to trigger an alert message

Just starting out with JavaScript and I'm attempting to create an alert box that not only displays the message "Thank You For Visiting" when you click the Enter button, but also includes the name entered into the text box. While I have successfully im ...

Why is there a node_modules folder present in the npm package I authored when using it as a dependency in another module?

After successfully launching my first npm package, I noticed something strange when installing it as a dependency in my project. Upon exploring the project folder in node_modules, I discovered an unexpected node_modules folder containing just one package ...

Creating a mechanism for automatic refreshing of JWT tokens in a Spring Boot and Angular application

I am working with Spring Boot and storing JWT tokens in httpOnly cookies. How can I implement automatic token refresh using the existing refresh tokens method on the backend? ...

How can I properly implement a Closure or IIFE to manage an onclick event in ReactJS?

I'm encountering an issue while attempting to utilize the this object in an event handler. An undefined error related to the this object keeps popping up. My development stack includes ReactJS and Redux as well. class Chat extends Component { c ...

What is the best way to access the data being sent to a router link in Angular?

After navigating to the user page using the router sample below, how can I retrieve the details once it reaches the user page? I need to verify in my user.component.ts that the navigation is triggered by this [routerLink]="['user', user.id, &apo ...

Tips on retrieving an item using jQuery's select2 plugin

How can I retrieve the value (flight_no) from the processResults function in order to populate the airline name with the respective flight number when selected? I've attempted to access the (flight_no) within the processResults function, but I'm ...

Verify internet connectivity with Ionic

Seeking a reliable method to accurately detect whether a mobile device is truly online and connected to the internet. One approach I have explored involves utilizing an http interceptor: if (navigator.connection.type != Connection.NONE) alert("you'r ...

Navigating through each element of an array individually by using the onClick function in React

I'm currently working on a project that involves creating a button to cycle through different themes when pressed. The goal is for the button to display each theme in sequence and loop back to the beginning after reaching the last one. I've imple ...

JavaScript form validation issue unresolved

When I attempt to validate form fields using Javascript functions, they seem to not load or check the field upon clicking the submit button. <html> <body> <?php require_once('logic.php'); ?> <h1>New Region/Entit ...

Issue with Struts 2 tag causing malfunction in validating the collection

When iterating through a list in a JSP file using Struts 2 tags, the code below is used: <%@ taglib prefix="s" uri="/struts-tags"%> <head> ... The issue arises with date validation. The following line of code does not work: <td><s:d ...

Reduce the size of the header in the Sydney theme for WordPress as you scroll

Currently, I am attempting to reduce the size of the header once scrolling down. My focus is on refining the child theme. Displayed below is a screenshot illustrating the appearance of the header at the top of the page: https://i.stack.imgur.com/wojGf.pn ...

What is the best way to capture user input using an onClick event in JavaScript and then display it on the screen?

I'm in the process of upgrading a table, and while most of it is working fine, there is one function that's giving me trouble. I want this function to return an input with an inline onClick event. The actual return value is displaying correctly, ...

The Ionic application encounters an issue with the $stateParams being

Can someone assist me with resolving an issue related to ionic $stateParams? Here is the state configuration: .state('tabs.categories', { url: "/categories/:parentID", views: { 'categories-tab': { templateU ...

Shifting annotations on a Bar Graph featuring Negative Values on Google's Chart Maker

Incorporating google charts into my MVC project. Looking to create a bar chart that accommodates negative values. Desire annotations on the same side as the end of the bar for negative values (similar to positive values shown in the green box below). ht ...

How to organize initial, exit, and layout animations in Framer Motion (React) tutorial?

Currently, I am utilizing framer-motion library for animating a change in grid columns. This is the objective: Within the grid container (#db-wrapper), there are nine buttons arranged. https://i.stack.imgur.com/61pQqm.png When the user switches to the ...

Iterate through each key in the response JSON object using a variable named "a

Here is a snippet of my code: var roomid= roomIds[i] const Availabilitydata = await AvailResponse.json(); availableroomsArray.push(Availabilitydata); app.get("/api/availability", (req, res) => { res.json({ indicateur: availableroomsA ...

Is it possible to send requests to multiple APIs using a TypeScript event handler?

I'm facing a challenge in pinging multiple APIs within a single function. It seems like it should be possible, especially since each API shares the same headers and observable. I attempted to write a function for this purpose, but unfortunately, it do ...

What is the proper method for overriding styles in material-ui v5 for properties that are not present in the themes components?

Currently, I am customizing MuiDataTables using the adaptv4theme in the following manner: declare module '@material-ui/core/styles/overrides' { export interface ComponentNameToClassKey { MUIDataTable: any; MUIDataTableFilterList: any; ...