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

What is the best way to access the inner html of every cell within a table row that I have selected?

I want to implement a feature on my website where users can click a "save" button on a specific row in a table and save the entire row's innerHtml onto another page as their favorite hiking trails. I've been trying to achieve this by adding clic ...

Tabulator - Enhancing Filter Results Using a Second Tabulator

I've implemented a Tabulator that displays search results, here is the code: var table = new Tabulator("#json-table", { layout:"fitDataFill", //initialFilter:[{field:"title", type:"!=", value:"ignoreList.title"}], ajaxURL:tabUrl, ajax ...

Exploring the power of Angular's ng-repeat to generate hierarchical lists

I am looking to display a structured list of layers and sublayers by looping through an object using ng-repeat. var lyrslist = [ { layername: "Base Maps", layertype: "layer" }, { layername: "Open Street Map", layertype: "sublayer" },    { layer ...

Is it possible to dynamically add the URL to an iframe based on a condition being true, and then iterate through a list of URLs before

I'm trying to figure out how to change the URL in an iframe based on the presence of a class="show". The first time the element has the class "show," it should load about.html. The second time the same element has the class "show," it should open wor ...

How Angular 2's change detection system causes unnecessary DOM refreshing

My application is currently in the live beta stage and I am focused on improving its performance. One issue that has caught my attention is the flickering of images within a table. Upon investigation, I discovered that the DOM is continuously refreshing, e ...

Encountering an error when attempting to upload a file to S3 using JS Vue

I'm attempting to upload a file to my S3 bucket using the aws-s3 library, but I am encountering this error in the console: https://i.stack.imgur.com/lk47U.png Here is the code for the component: <template> <input type="file" @ch ...

Learn how to retrieve specific user information from a JSON file by implementing a button click feature within a custom directory using Angular.js

I am just starting to learn angular.js and I'm trying to figure out how to retrieve JSON data from a custom directory. My goal is to display the information of a specific user when a particular button is clicked, but so far I haven't been success ...

Display a browser alert in Angular 5 whenever a query parameter undergoes modification

In my web application, there is a Parent component called Item which has the route '/Item'. Within this Parent component, I have two children components: one is named Catalogue and the other is named AddSize. By default, when the page loads, th ...

npm encountered an abrupt conclusion of JSON input during parsing near "serify":"latest","cha"

After uninstalling angular-cli yesterday to update to @angular/cli, I encountered an error while trying to install @angular/cli: Received an unexpected end of JSON input while parsing near '...serify":"latest","cha' Even after attempting to c ...

Creating a class in TypeScript involves declaring a method that takes a parameter of type string, which matches the property name of a specific derived class type

I am working on a scenario where I have a base class containing a method that can be called from derived classes. In this method, you provide the name of a property from the derived class which must be of a specific type. The method then performs an operat ...

Validation of forms in Angular using a pseudo submission method

On a webpage, there is a form with two buttons: one to calculate a price and the other to submit the form. Below is a basic example: <form novalidate name="formStep1"> <select ng-model="address" required> <option></option> ...

Trouble arises when the properties of this.props are supposed to exist, yet they are not

Wow, what a name. I am struggling to come up with a better title given my current state. The problem at hand is as follows: When using React, I set the state to null during componentWillMount. This state is then updated after data is fetched from a serve ...

The presence of ng-show dynamically adjusts the minimum height of a div element

I am encountering an issue with a div that has the class of wrapper. Inside this div, there is a parent div with the class of content-wrapper. The wrapper div includes a conditional directive ng-show which toggles between displaying or hiding its content. ...

Increase the size of the NativeScript switch component

Here is the code I am working with: .HTML <Switch style="margin-top: 10" (checkedChange)="onFirstChecked1($event)" row="0" col="1" horizontalAlignment="center" class="m-15 firstSwitchStyle"></Switch> .CSS .firstSwitchStyle{ width: 30%; ...

Redis appears to be missing the expected results

After following an express demo which involved storing and retrieving values with Redis, I attempted to implement the code in my own Express app. However, I encountered issues as the req.online variable was returning null when I tried to retrieve its lengt ...

Having trouble retrieving data using a custom URL in Axios with ReactJs

My knowledge of Reactjs is still new and I am currently working on a project using nextjs. I have a component called Trending.js that successfully fetches data from the URL "https://jsonplaceholder.typicode.com/users". However, when I try to change the U ...

React app experiencing crashes due to Material UI Select component issues

I am facing a challenge while trying to incorporate a material ui select component into the React application I am currently developing. Whenever I attempt to add a select functionality to a form, it results in a crash. Despite following the example provid ...

Having trouble getting `npm start` to work for the Lite-server?

As a newcomer to Angular and web programming, I attempted to replicate the quickstart project on github/angular by using "npm start" to initiate lite-server. However, following a tutorial [link] (https://www.youtube.com/watch?v=-zW1zHqsdyc&t=804s), I ...

Choose Angular Material to dynamically display the state of multiple items as either checked or unchecked

Currently, I am utilizing <mat-select> from Angular Material for multiple choice selection. Is there a particular property that can be set for <mat-option> to determine whether an option should be checked or unchecked based on a parameter? For ...

Angular JS Tab Application: A Unique Way to Organize

I am in the process of developing an AngularJS application that includes tabs and dynamic content corresponding to each tab. My goal is to retrieve the content from a JSON file structured as follows: [ { "title": "Hello", "text": "Hi, my name is ...