Tips for accessing the value and text of an Angular Material mat-select through the use of *ngFor

When using a dropdown menu, I want to retrieve both the value and text of the selected option.

View dropdown image

Underneath the dropdown menu, I aim to display values in the format of "options: 'value' - 'selected option'".

component.html

<mat-form-field class="week" appearance="outline">
                      <mat-select
                        [(value)]="EndsofMonth"
                        (selectionChange)="selectedValue($event)"
                      >
                        <mat-option
                          *ngFor="let week of endsofmonth"
                          [value]="week.text"
                        >
                          {{ week.text}}
                        </mat-option>
                      </mat-select>
                    </mat-form-field>
     The cycle runs from {{ selectedData.value}} to {{ selectedData.text }}

component.ts

EndsofMonth = 'Last day of the month';

  selectedData: { value: string; text: string } = {
    value: '1st',
    text: 'Last day of the month '
  };


  selectedValue(event: MatSelectChange) {
    this.selectedData = {
      value: event.value,
     text: event.source.triggerValue
    };
    console.log(this.selectedData);
    
    
  }

  endsofmonth = [
    { value: '2nd', text: '1st of the month' },
    { value: '3rd', text: '2nd of the month' },
    ...
    { value: '31st', text: '30th of the month'},
  ];

For example: If I choose the 30th of the month from the dropdown, the displayed selection should be "selected cycle 31st - 30th of the month"

Answer №1

One possible reason for the error occurring is due to using an incorrect variable for the value:

<mat-form-field class="week" appearance="outline">
  <mat-select
    [(value)]="EndsofMonth"
    (selectionChange)="selectedValue($event)"
  >
    <mat-option
      *ngFor="let week of endsofmonth"
      [value]="week.value". // Modify this part
    >
      {{ week.text}}
    </mat-option>
  </mat-select>
</mat-form-field>

Cycle runs {{ selectedData.value}} - {{ selectedData.text }}

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

Exploring component method variables with Jest testing

Imagine a scenario where there is a class component with the following structure: export class Math extends React.Component { ... someComponentMethod = numb => { const sample = numb * 10 ... const result = numb -5 ...

Displaying all components simultaneously instead of displaying placeholders and awaiting image downloads

Is there a way to instruct the browser to load all images first before displaying the page, rather than rendering img elements and then loading the images afterwards? I am working with asp.net on the server side, but I believe the solution may involve DOM ...

Implementing a JavaScript function that uses the AJAX method to confirm and update

I am currently attempting to update a database using the JavaScript confirm() function in combination with AJAX. My goal is to have "accepted_order.php" run if the user clicks "OK," and "declined_order.php" run if the user clicks "Cancel," all without caus ...

Leverage the power of JSON to efficiently represent a collection of string

Currently, I am engrossed in reading the 3rd edition of JavaScript Pocket Reference. The author makes an interesting statement in chapter 5 - Objects on page 75: In JavaScript, objects are dynamic, allowing properties to be added and deleted at will. Int ...

Having trouble with installing Recharts through npm

When I try to install recharts using npm, I encounter the following error message in my console: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! ...

Is there a way to organize items in an array alphabetically according to a predetermined key value?

I have an array of objects containing countries with various values for each country. My goal is to list them alphabetically. // globalBrands { [ { id: 1, title: 'Argentina', content: [{url: 'w ...

Having trouble with the installation of Parcel bundler via npm

Issue encountered while trying to install Parcel bundler for my React project using npm package manager. The terminal displayed a warning/error message during the command npm i parcel-bundler: npm WARN deprecated [email protected]: core-js@<3 is ...

Transferring information between functions

I am trying to retrieve the value of my drop-down within the getData function. Although the data displays correctly in the run function, I am unsure of how to pass that data down to the getData() function. <select class="form-co ...

Creating a JavaScript regular expression for formatting time input without using any external plugin

As I work on implementing a time input mask with the meridian of am|pm without using an input mask plugin, I've encountered some challenges. The input should not allow the user to start with alphabets, but my current pattern, although it works, clears ...

Create artwork by drawing and adding text to an image before saving it

I am looking to enhance my website by adding a feature that allows users to draw on images hosted on the server. Additionally, I want users to have the ability to add text to the image and save their edits as a new picture. While it may seem like a simple ...

There is no link between the two containers

I am facing an issue where two containers need to connect with each other. However, when attempting to fetch data from one container, I encounter an ENOTFOUND error. Surprisingly, this code functions properly on my local system but fails within the contain ...

A guide on attaching files to CouchDB using the Couchdb4j library

I'm facing a challenge with using a Java application to attach system files to a Couchdb database using the Couchdb4J library. Despite trying to modify the code provided, I keep encountering an unresolved error. Can anyone point out where I went wrong ...

Error Arises When Making Selection in PrimeNG's P-ListBox Component

Whenever I choose an item from my listbox module, I encounter an error where the value is being returned as an object instead of an array in my listbox.js file from p-listbox by PrimeNG. HTML: <p-listbox formControlName="programType" [options]="phoneT ...

Enhancing keyboard accessibility with the spacebar for radio buttons and check boxes in Angular 2

I am currently working on a form in Angular 2 that includes radio buttons and checkboxes. When tabbing through the fields, they are highlighted properly. However, I am facing an issue with the radio buttons - I want them to be selected when I hit the space ...

Mapping an array of objects within another array of objects

I have a collection of objects that I looped through to extract the content: const teamSliderContent = [ { Description1: 'Chef. Mordy Wenk', Title: 'Head of the Chief staff.', id: 1, }, { Desc ...

Troubleshooting Google Authorization Issue in Angular 17: How to Fix the Error TS2304: 'google' Not Found in Angular 17

I am encountering an issue while attempting to integrate Google Auth into my Angular(+Express) application using the Google Identity Services library. Despite following the instructions provided in the Google tutorial, I am facing the error: "[ERROR] TS230 ...

Stop the change event from occurring on a textarea when the user clicks on an external cancel button

In a particular scenario, there is a textarea with an autosave feature triggered by the change event. When the textarea is focused on, Save and Cancel buttons appear at the bottom, providing users with options in case they prefer not to simply click outsid ...

Breaking apart a string and mapping it to specific fields

My issue is relatively straightforward. Upon loading my page, a long string representing an address is generated. For example: 101, Dalmations Avenue, Miami, Florida, USA, 908343 With the help of jQuery, I can split the string using: var address = sel.o ...

Click event not functioning in programmatically loaded HTML

I am facing an issue with a JSON file that contains the page content I am trying to load. The link within it appears as follows: <a data-ng-click='foo()'>Bar</a> When I load this page content into the HTML page: <p class="body" ...

Leveraging setter methods within knockoutjs bindings allows for efficient data manipulation

As the day comes to a close, my mind is winding down for the night. I've been diving into the world of setters when dynamically binding to Html elements and trying to wrap my head around it. While I have read through several examples, these URLs below ...