Mat-select failing to display the selected value

https://i.sstatic.net/8D3tI.pngWhen I load my edit form, I need to populate the form Array with initial values. Although my drop-down selection option is disabled, it does not display in the mat-select.

let selectedSpecs = this.editData.element.specifications;

this.spec = this.specForm.get('spec') as FormArray;

if (selectedSpecs.length != 0){
  let selectedAttributeIds = [];
  selectedSpecs.forEach((spec, i) => {
    let attribute;
    attribute = {'id': spec.itemDetailId, 'itemId':this.editData.element.itemId, 'name': spec.name};

    this.spec.push(this.formBuilder.group({
      attribute: attribute,
      attributeSpec: spec.description
    }));

    selectedAttributeIds.push(spec.itemDetailId);

  });

  let attributes = [];
  this.selectedCatAttributes.forEach((tempattribute) => {
    let selected;
    if (selectedAttributeIds.includes(tempattribute.id)) {
      selected = true;
    }else {
      selected = false;
    }
    attributes.push(new Attribute(tempattribute, !selected));
  });

  this.attributeList.next(attributes);


}





<div formArrayName="spec" *ngFor="let spec of specForm.get('spec')['controls']; let i= index">
      <div [formGroupName]="i">
        <mat-card class="addShadow">
          <button style="float: right" mat-icon-button (click)="removeSpec(i)"><mat-icon class="specClear">cancel</mat-icon></button>


          <mat-form-field class="spec">
            <mat-select placeholder="Select Attribute" formControlName="attribute" (selectionChange)="selectedOption($event.value,i)">
              <mat-option *ngFor="let attribute of attributeList | async; let index = index" [value]="attribute.attribute" [disabled]="!attribute.allowed">
                {{attribute.attribute.name}}
              </mat-option>
            </mat-select>
          </mat-form-field>

          <mat-form-field class="spec">
            <input matInput placeholder="Specification" formControlName="attributeSpec">
          </mat-form-field>
        </mat-card>
      </div>
    </div>

How can I display the initial values in the dropdowns using form arrays? I have attempted using [value] and [compareWith], but neither has been successful for me.

Answer №1

After numerous attempts, I finally discovered a solution to this problem using the [compareWith] method. Here is my successful approach.

Below is the function I utilized within the [compareWith] method:

attributeDisplay(attribute1, attribute2) {
  if (attribute1.id == attribute2.id) {
    return attribute1.name;
  } else {
    return "";
  }
}

Furthermore, here is the snippet of HTML code that exemplifies how I implemented the [compareWith] method:

<mat-form-field class="spec">
  <mat-select
    placeholder="Select Attribute"
    formControlName="attribute"
    (selectionChange)="selectedOption($event.value,i)"
    [compareWith]="attributeDisplay"
  >
    <mat-option
      *ngFor="let attribute of attributeList | async; let index = index"
      [value]="attribute.attribute"
      [disabled]="!attribute.allowed"
    >
      {{attribute.attribute.name}}
    </mat-option>
  </mat-select>
</mat-form-field>

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

Using AJAX in a WordPress template

I'm currently facing an issue with integrating my operational php/javascript/ajax application into my WordPress theme. This application is meant for my users and not within the admin panel. Steps I've taken: I have successfully included the Java ...

I'm encountering an error when trying to return a value using the question mark operator in Vue.js - can someone explain why

When I attempted to retrieve the value using the question mark operator instead of using return twice, I encountered an error stating "Cannot read property 'omitDescription' of undefined." buttonText() { return this.omitDescription ? 'プ ...

Just started working with React and encountered this initial error message in my project

Welcome to Windows PowerShell! Upgrade to the latest version of PowerShell to enjoy new features and enhancements! PS D:\React> cd textutils PS D:\React\textutils> npm start npm WARN config global `--global`, `--local` are deprecated ...

How can you assign a strokeStyle color to a Canvas using a CSS property?

Our team is currently working on an Angular2 / Ionic 2 project where we have implemented a HTML Canvas element that allows users to draw on it. One challenge we are facing is how to set the Canvas strokeStyle property using a color provided by a CSS style. ...

Show the percentage of completion on the progress bar while uploading with AJAX

I'm having trouble updating the current upload value on my progress bar in real-time. I know how to do it when the progress bar has stopped, but I can't get it to update continuously. xhr.upload.onprogress = function(e) { if (e.lengthComputa ...

Styling the time ticks on the x-axis in Nivo Line Charts

I need help styling the x-axis of my line chart to show time. I am utilizing the @nivo/line react library for generating charts. axisBottom={{ tickValues: 3, tickRotation: 90, format: (values) => `${getRequiredDateFormat(values, 'MMMM-DD ...

Unexpected behavior occurs with AJAX following a keyup event

Currently, I am encountering an issue with a textbox that is used to search for contacts upon triggering the keyup event. The displayed contacts are appended to a specific div element and incorporate pagination functionality through scrolling. However, aft ...

How can I continuously update a datetime tag every second within a Django Template?

I am currently working with Django 3, Bootstrap 4, and MySQL 5.7 on a Laragon server, all running on Windows 10. In one of my views, I have a variable dt_now = timezone.now() that I display in a Template using a simple <p>{{ dt_now }}</p> tag. ...

Theme.breakpoints.down not being acknowledged by MUI breakpoints

The Challenge: Implement a hamburger menu to replace the navMenu on tablet and smaller screens After successfully compiling in VS code terminal, encountering an error in the browser: Error Message: TypeError: Cannot read properties of undefined (reading ...

Using Typescript with Nuxt can become tricky when attempting to inject data into `Vue.extend` as it appears to be

I want to implement TypeScript support in my Nuxt project. From my understanding, I need to use Vue.extend when returning the component data like this: import Vue from 'vue'; type Data = { a: number } export default Vue.extend({ data():Data{ ...

What is the best way to access the contents within this specific div element?

Is there a way to extract only the word "square" from within this div's content? <div class="item"> Blue <span>•</span> Square <span>•</span> Infinite </div> I attempted to use innerText.split(), bu ...

Explore linked MongoDB collections using Node.js and Handlebars to access relevant documents

As a novice web developer, I've taken on the challenge of creating a bug-tracking platform for my project. The main issue I'm facing is displaying the user's name instead of their user ID in the "Reported by" column on the dashboard screensh ...

Implementing a smooth transition for a never-ending CSS rotation animation upon clicking a different div with the help of jQuery

I am attempting to utilize jquery in order to bring a constantly rotating div (with CSS animation) to a gradual, smooth halt when another div is clicked. My current strategy involves changing the "animation-timing-function" property from "linear" to "ease ...

Using Material UI's ProgressBar to create a countdown feature in a React

I am working on a feature where pressing a lock button changes the isReserved status of an item to true. This action also creates two new states in Firebase Firestore, namely startDate and expiryDate. The expiryDate is set to be 72 hours after the startDat ...

Generating a header each time a table is printed across multiple pages

A table has been created in a webform using C#. The goal is to only print the table when the user clicks the print button on the webform. Javascript has been implemented in ASP.NET to only print the content within a specific div. While this method works, ...

The best method for quickly loading a webpage that is over 20MB in size

My website is a single-page calendar featuring a full year's worth of images. With 344 requests and a total load size of 20MB, the page consists of a simple PHP script without a database. The requests include a CSS file (15KB), 4 JS files (20KB), two ...

What could be causing the presence of the word "undefined" at the start of my string?

One of the challenges I'm facing is with a function that combines data from an AJAX request. After running the code, I noticed that my final string always begins with "undefined". To illustrate this issue, here's a simplified example: // ...

What is causing the image to become distorted on the canvas?

Despite specifying the image dimensions to be 50px by 50px, it appears stretched on the y-axis like this. View Stretched Image I suspect that the issue lies with the CSS styling applied. Here is my current CSS code: canvas { background-color: green; ...

Experimenting with a custom AngularJS filter designed to extract numerical values from a chunk of text

I am working on creating a unique filter that can extract numbers from text input into a text box. For example: User enters: The cat went to 4 stores and bought 3 bags of cat litter for 1 dollar. The desired output would be: [4, 3, 1] This filter works ...

Verify whether the user's email is registered in the database

I have a login form and I want to verify if a user's email exists in the database, but I'm not sure about the syntax for integrating Angular with Node. In my Main.js file, I have an ng-click on the submit button that triggers this function. I ex ...