What is the best way to assign the selected attribute to my mat-option element?

I am encountering an issue with my mat-select and mat-option control. I am trying to apply the selected attribute to the first mat-option control without using binding on [(ngModel)] or [(value)]. The mat-option control is being generated by the *ngFor directive, but I want to avoid needing a property in my component that typically binds the mat-select UI control with [(ngModel)]. I have tried various approaches:

<mat-form-field>
    <mat-label>Currency</mat-label>
    <mat-select #currencySelect>
        <mat-option *ngFor="let currency of currencies; let isFirst = first" [value]="currency" [attr.selected]="isFirst ? 'selected' : null">
            {{currency | currencyName}}
        </mat-option>
    </mat-select>
</mat-form-field>
<mat-form-field>
    <mat-label>Currency</mat-label>
    <mat-select #currencySelect>
        <div *ngFor="let currency of currencies; let isFirst = first">
            <mat-option *ngIf="isFirst" selected [value]="currency">
                {{currency | currencyName}}
            </mat-option>
            <mat-option *ngIf="!isFirst" [value]="currency">
                    {{currency | currencyName}}
            </mat-option>
        </div>
    </mat-select>
</mat-form-field>
Out of these attempts, only the following achieved the desired outcome:
<mat-form-field>
    <mat-label>Currency</mat-label>
    <mat-select #currencySelect [value]="currencies != null && currencies.length != 0 ? currencies[0] : null">
        <mat-option *ngFor="let currency of currencies;" [value]="currency">
            {{currency | currencyName}}
        </mat-option>
    </mat-select>
</mat-form-field>
However, this solution relies on binding the [value], which is not ideal for me. I would prefer the code structure to be like this:
<mat-form-field>
    <mat-label>Currency</mat-label>
    <mat-select #currencySelect>
        <mat-option *ngFor="let currency of currencies; let isFirst = first" [value]="currency" [selected]="isFirst">
            {{currency | currencyName}}
        </mat-option>
    </mat-select>
</mat-form-field>
How can I achieve this? I wish to accomplish it without the need for a component property that tracks the selected item. Thank you.

Answer №1

To make Mat select work with an object directly, you can implement the compareWith input on mat-select like shown below:

<mat-select [compareWith]="compareFn" [value]="initialValue"></mat-select>

In your TypeScript file, include these lines for example:

initialValue= {currencyID: 1, currencyName: 'USD'};
compareFn(a, b) {
  return a.currencyID == b.currencyID;
}

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

Utilizing identical child components in Angular 2 parent component

My goal is to have a page with 2 tabs, each containing a table. To simplify the structure of the tables, I decided to create a custom component for a table and use it as a child component. Here is how I structured my parent page: <p-tabPanel> ...

Display the div only if the router is not the same in angular 2

If the router is not equal to an empty string or '/dashboard', I would like to display the following code: <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right> & ...

What is the best method to retrieve the value of a cell in a different cell within the same row in an Angular Material Data-Table?

I am working with an Angular Material Data Table that has four columns. In every row, the last cell contains a button with an on-click function attached to it. I need to pass the value from the first cell ("Name") as a parameter in the corresponding button ...

Dealing with incorrect type declarations in Typescript when using Material-UI Higher Order Components can

Currently, I am in the process of upgrading from Material-UI 1.x to the newer version Material-UI 3.9.2. I had several components that were functioning well with Higher Order Components (HOC), but when it comes to migrating them to 3.9.2, I am facing some ...

Finding the index of an element in an array using the filter method in Angular JavaScript

As I was working with an array of pages in a book, I wanted to find the index of a specific page that had been identified using filter. While my current function gets the job done, I can't help but wonder if there's a way to combine indexOf or fi ...

Node OOM Error in Webpack Dev Server due to Material UI Typescript Integration

Currently in the process of upgrading from material-ui v0.19.1 to v1.0.0-beta.20. Initially, everything seems fine as Webpack dev server compiles successfully upon boot. However, upon making the first change, Node throws an Out of Memory error with the fol ...

Why are mustaches not functioning as expected in Vue SFC defined by Vite?

I recently ran into a configuration issue with my vite-config.ts file. export default defineConfig({ ... define: { __PRODUCT__: JSON.stringify("My Product") } In my vue sfc template, I have the following code snippet: <div class="footer"> {{ ...

What are some techniques for streamlining this code with Typescript?

I am currently working with the following code snippet: let doNavigate = this.currentScreen === removedFqn; if (doNavigate) { location.reload(); } Does anyone have any suggestions on how I can simplify this code using Typescript? ...

Kindly include an @Ionic3Annotation for either @Pipe, @Directive, or @Component

During development, this code runs without any issues. However, when attempting to run it in production using the command: Working: ionic cordova run android Not working: ionic cordova run android --prod --release Error Message: [03:34:41] types ...

What could cause a member variable to be uninitialized in the ngInit method in Ionic/Angular, even though it was initially set in the constructor

Despite setting the modal form to be bound to an instance of "Foo" during its construction, I encountered a strange issue where, post-constructor, this.foo became undefined. Even after verifying this through breakpoints and console.log, the problem persist ...

Error: Module not found - Issue with importing SVG files in NextJS

Currently, I am utilizing the babel plugin inline-react-svg to import inline SVGs in NextJS. Here is a snippet from my .babelrc configuration file: { "presets": ["next/babel"], "plugins": [ "inline-react-svg" ...

Is it not possible to access the width and height of an element using ViewChild, unlike what is suggested in other responses

I've encountered an issue with my Angular component. The HTML code for the component, before any TypeScript is applied, looks like this: <svg #linechart id="chartSpace"></svg> Wanting to create a responsive webpage featuring a line chart ...

Implementing a persistent "remember me" feature in Angular 2 without relying on local

Is it possible to implement a "remember me" feature in Angular 2 without relying on the use of local storage? ...

Keeping track of important dates is ineffective using the calendar

I am facing an issue with developing a calendar that marks events on the correct dates. I am receiving the dates in the following format in PHP [ { "status": "OK", "statusCode": 200, "statusMensagem": & ...

Stop Material UI Typography Text from exceeding the boundaries of its parent container

I am dealing with a situation where I have a Typography element nested inside a div, and the issue arises when the text within the Typography element is too lengthy causing it to overflow outside the boundaries of its parent div. This behavior is not desir ...

Is there a way to include a personalized attribute in the React Menu item that is created?

Is it possible to add an id or some attribute to the MenuItem, such as <MenuItem id="foo" onClick={handleClose}>Copy Ctrl+C</MenuItem>, in order to access it from event.target within the context menu event handler in my TreeView? The ...

When trying to generate a popOver in Ionic, an error message "<TypeError: ev.target.getBoundingClientRect is not a function>" may be displayed

I'm currently working on implementing a popover that appears when a mouse click event is triggered. However, I've encountered an issue where the Create() method of the popover gets called upon event activation, but I keep receiving the following ...

Position the mat-icon button in the top right corner for the close button

I'm struggling with positioning my close icon button at the top right corner of my dialog box. Here is my app-iconbutton component: <button mat-icon-button class="iconbutton" [ngStyle]="{ 'background-color': back ...

Expand the font manually

Is there a way to define a type that represents the widened version of another type? Consider the following scenario: function times<A extends number, B extends number>(a: A, b: B): A & B; The intention behind this times function is to preserv ...

Obtaining the TemplateRef from any HTML Element in Angular 2

I am in need of dynamically loading a component into an HTML element that could be located anywhere inside the app component. My approach involves utilizing the TemplateRef as a parameter for the ViewContainerRef.createEmbeddedView(templateRef) method to ...