Selection of input from the mat-select component is a composed object

I am facing a challenge when trying to input a composed value into a select field. Let's consider our object contains only an ID and a name. The typical way to create a functional select would be:

<mat-form-field>
   <mat-label>Placeholder</mat-label>
   <mat-select>
      <mat-option *ngFor="let i of fooCollection" [value]="i.id">
         {{i.name}}
      </mat-option>
   </mat-select>
</mat-form-field>

While searching for a solution to assign a value, I came across this informative example in the documentation that simply adds a [(value)] option to the mat-select tag. However, as we are dealing with a composed object here, this method no longer functions.

Any thoughts on how to resolve this issue? Thank you in advance! Kev'

Answer №1

Check out this code snippet for a two-way value binding example in Typescript:

      /** @title Select with 2-way value binding */
  @Component({
    selector: 'select-value-binding-example',
    templateUrl: 'select-value-binding-example.html',
  })
  export class SelectValueBindingExample {

  myOptions = [
    new MyOptions('name1','description1' ),
    new MyOptions('name2','description2' ),
    new MyOptions('name3','description3' ),
  ]


  selectedOption = this.myOptions[2]

  }//Cls

  //-----------------------------------------------------//

  class MyOptions{
    constructor(
      public name:string,
      public description:string
    ){}
  }

Here is the corresponding HTML code:

          <mat-form-field appearance="fill">
      <mat-label>Select an option</mat-label>
      <mat-select [(value)]="selectedOption">
        <mat-option *ngFor="let myOption of myOptions" [value]="myOption">
          {{myOption.description}}
        </mat-option>
      </mat-select>
    </mat-form-field>

    <p>You selected: {{selectedOption|json}}</p>

If you include the line

<mat-select [(value)]="selectedOptionName">
, it will retrieve the value from [value] in each
<mat-option *ngFor="let myOption of myOptions" [value]="actualValueGoesHere">
. You can then use this value as needed.

To set an initial value, simply assign selectedOption = this.myOptions[2] (or any other initial choice).

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

Angular 2 problem with navigation trails styling

I am encountering a problem with breadcrumbs. In our menu items, we have attributes such as expanded?: boolean; disabled?: boolean; visible?: boolean; badgeStyleClass?: string; style?: any; styleClass?: string; However, none of the above attributes see ...

The issue encountered is a TypeError stating that it is unable to retrieve properties of an undefined value, specifically in relation to the 'imageUrl

When I include the following line of HTML code: <td> <img align="center" [src]="productByBarCode.imageUrl" /> </td> An error is thrown by the console: ERROR TypeError: Cannot read properties of undefined (reading &a ...

The type 'undefined' cannot be assigned to type 'Element or null'

One of the components I am using looks like this: const data: any[] = [] <Tiers data={data}/> This is how my component is structured: const Tiers = ({ data, }: { data?: any; }) => { console.log('data', data?.length!); ...

Can Angular be used to dynamically filter a JSON object to display only the fields that match a specified filter text?

Sorry if this question has already been asked; I couldn't find the solution. Here is my issue: In my Angular app, I am retrieving a complex JSON object from a web service. I then present this JSON object to the user in tree format using ngx json vie ...

Using createContext in React.tsx to pass the state through useState

There is a context called Transaction that accepts an object and a function as parameters. In the AppProvider component, the Transaction.Provider is returned. The following code snippet is from the GlobalState.tsx file: import { createContext, useState } f ...

Guide to accessing the content of pure ES6 modules directly in the Chrome console without the need for Webpack

Situation: When using tsc to compile code for es6, the scripts function properly once they are served from a server. However, I am unsure of how to access variables within modules through the console. The file names do not seem to be available as objects ...

Is it achievable to have a Dynamic Angular Output?

With multiple parent components needing a common child component that can dynamically and automatically adapt to each case, I am faced with the challenge of generating buttons using a forEach loop with data provided by the parent component (such as name, C ...

What is the reason behind the failure of a react factory method compilation when extending a typescript class, despite it working perfectly fine on the base class?

As I delve into my lengthy codebase consisting of hundreds of lines, I have managed to narrow down my issue to a concise example. My query pertains to the peculiar behavior exhibited by the Typescript compiler in a specific scenario. The snippet below com ...

Ways to fix ERROR Error: Expected validator to return Promise or Observable

After going through all the other questions on this topic, I still haven't found a clear answer. My Reactive Form looks like this: this.recipe = this.formBuilder.group({ title: ['', Validators.required], ingredients: this.formBu ...

Efficiently loading and locally filtering data in Angular 2 using Observables

In my Angular 2 application, I have successfully implemented an input with autocomplete that calls an API for server-side filtering and value retrieval. However, I am now facing a challenge as I need to add more inputs to my page that do not require server ...

What is the best way to align an extensive text and an image side by side within a table cell?

I am facing an issue with my code. In one of the td elements, I have the user's name image on the left and their first name on the right. The problem arises when the first name is too long, causing the image to disappear. Everything works fine if the ...

"Series of Subscriptions: Unleashing New

I have a ReplaySubject that is subscribed to by multiple components. I am curious about the order in which these subscriptions are processed. public getValue$ = new ReplaySubject<any>(1); If I send a value to getValue$ using getValue$.next(5); Assu ...

Can the default setting for --base-href be configured specifically for ng build and not for ng serve?

How can the default setting of --base-href for ng build be adjusted without impacting ng serve? Utilizing Angular CLI version 1.6.6 Compatible with Angular 5 and above ...

Navigating to child components within an Angular module is currently disabled

My Project Dashboard contains 2 sub apps. ├───projects │ ├───app1 │ │ ├───e2e │ │ │ └───src │ │ └───src │ │ ├───app │ │ │ ├───form │ ...

How to correctly deserialize dates in Angular 5

When working with Angular 5, I have encountered an issue where JSON data from an API is not properly deserialized into dates within an array. My model includes a definition like this: export interface ProcessDefinition { _id?: string; proces ...

How can I resolve a bug in Nuxt2 when using TypeScript?

I need help with implementing code using Nuxt.js 2 option API with TypeScript. computed: { form: { get: () => this.value, set: (value) => this.$emit('input', value) } } Additionally, I am encountering the fo ...

Displaying images in Ionic from a JSON URL source

I am having trouble getting an image from a JSON to display on an Ionic card. Although I can see the JSON response in the console log, the image is not showing up on the card, leaving it blank. It seems like I'm making a mistake in the HTML code. Any ...

React Bootstrap Forms: The <Form.Control.Feedback> element is failing to display when the validation is set to false

Problem: I am facing difficulties with displaying the React Bootstrap <Form.Control.Feedback></Form.Control.Feedback> when the validation is false in my form implementation. Steps to Recreate: Upon clicking the Send Verification Code button, ...

Error: The Turborepo package restricts the use of import statements outside of modules

I created a typescript "test" package in turborepo, which imports and exports typescript functions. Due to being in turborepo, it gets copied to node_modules/test. When attempting to run import {func} from "test", an error is thrown: SyntaxError: Cannot ...

The Radix UI Theme's dark mode isn't taking effect

I'm having trouble getting the dark mode to work properly in my Radix UI app. Despite setting appearance="dark", nested components like Box and Card remain light. Interestingly, other props such as accent color seem to be working fine. It&a ...