Obtain the material-option value in Angular 5

Just starting out with Angular and attempting to implement an Angular Material dropdown menu. My goal is to have it display the months, but when a user clicks on a month, I want to retrieve the month's number so that I can use it as a URL parameter.

This is my current HTML code:

<mat-form-field style="width: 250px;">
     <mat-select placeholder="Select a month" #list [(ngModel)]="selectedOptions" name="selectedOptions" (ngModelChange)="onNgModelChange($event)">
       <mat-option *ngFor="let month of months" (mat-option)="onUpdate($event)" [value]="month.viewValue" >
            {{ month.viewValue }}
     </mat-option>
    </mat-select>
</mat-form-field>

In my component:

protected months = [
    {value: '0', viewValue: 'January'},
    {value: '1', viewValue: 'February'},
    {value: '2', viewValue: 'March'},
    {value: '3', viewValue: 'April'},
    {value: '4', viewValue: 'May'},
    {value: '5', viewValue: 'June'},
    {value: '6', viewValue: 'July'},
    {value: '7', viewValue: 'August'},
    {value: '8', viewValue: 'September'},
    {value: '9', viewValue: 'October'},
    {value: '10', viewValue: 'November'},
    {value: '11', viewValue: 'December'}
];
onNgModelChange(event: Event) {
    console.log(event);
}

I am able to retrieve the viewValue when clicking on the select, but I'm having trouble getting the value parameter (the number). Is there a way for me to achieve this?

For instance, I would like to get the number "1" when the user selects "February".

Answer №1

 <mat-option *ngFor="let item of items" (mat-option)="onUpdate($event)" [value]="item.value" >
        {{ item.viewValue }}
 </mat-option>

There seems to be a mistake where you used item.viewValue as the value for your options, which might lead to not getting the desired value. I hope this information is helpful.

Answer №2

When working with your mat-select component, utilize the following code:

[(ngModel)]="selectedOptions"
(change)="getValue()"

This specific piece of code utilizing (ngModel) enables two-way binding. Ensure to include a (change) event in your mat-select rather than using ngModelChange.

In your component.ts file, make sure to implement the following:

selectedOptions: String = "0";

protected months = [
 {value: '0', viewValue: 'January'},
 {value: '1', viewValue: 'February'},
 {value: '2', viewValue: 'March'},
 {value: '3', viewValue: 'April'},
 {value: '4', viewValue: 'May'},
 {value: '5', viewValue: 'June'},
 {value: '6', viewValue: 'July'},
 {value: '7', viewValue: 'August'},
 {value: '8', viewValue: 'September'},
 {value: '9', viewValue: 'October'},
 {value: '10', viewValue: 'November'},
 {value: '11', viewValue: 'December'}
];

getValue() {
    console.log(selectedOptions); // This will display the selected value
}

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

Error in IONIC 3: The code is unable to read the 'nativeElement' property due to an undefined value, resulting in a TypeError

I am currently learning about IONIC 3 and working on an app that utilizes the Google Maps API. However, when I try to launch my app, I encounter the following error message: inicio.html Error: Uncaught (in promise): TypeError: Cannot read property ' ...

Utilizing the [innerHTML] attribute within the <mat-select><mat-option> tags

I have integrated the use of [innerHTML] within <mat-option> in <mat-select>, which displays correctly in the drop-down list but not for the selected value. Versions: Browser Google Chrome 68.0.3440.106 (Official Build) (64-bit) Angular 6.1 ...

Handling Concurrent HTTP Requests in Angular using RxJS (Independently Triggered)

Angular 6: Implementing Angular Multiple HTTP Requests with RxJS (for updatePhone and updateAddress) that are independent of each other but may or may not occur simultaneously. Scenario 1: When changes are made to address fields (such as address, state, c ...

What is the best method for presenting data in a specific router in Angular?

In the main component, I have created a router: <div class="main-panel"> <app-navbar></app-navbar> <router-outlet></router-outlet> <app-footer></app-footer> </div> Within the app-navbar, there i ...

Extracting information from an object retrieved through an http.get response can be accomplished by utilizing various methods and

I am working with an API that returns a JSON object like this: { "triggerCount": { "ignition_state_off": 16, "ignition_state_on": 14, "exit_an_area": 12, "enter_an_area": 19, "door_unlocked": 1, "door_l ...

Is it possible to concurrently hot module reload both the server (.NET Core) and client (Angular)?

Using the command 'dotnet watch run' to monitor changes in server code and 'ng build --watch' for Angular code updates has been successful. It rebuilds the code correctly into directories "bin/" and "wwwroot/" respectively. myapp.cspro ...

PhantomJS and HTMLUnitDriver are experiencing difficulty locating elements using their id or xpath

I am currently facing a challenge in implementing a browserless solution within my cloud environment due to the lack of Chrome/Firefox installations. Even when using headless Chrome/Firefox solutions, I am encountering difficulties as they still require br ...

Adding a component dynamically to a div in Angular 5

Can anyone help me with this issue? I have successfully managed to dynamically append an element, but it is not getting compiled. I have looked at several tutorials like this one However, these tutorials do not exactly meet my requirements. They often us ...

Tips on triggering an Angular 2 method once a jQuery promise has been resolved

I am currently incorporating the Third Party Library called MarvinJS into my Angular5 Application. In order to successfully handle a MarvinJS promise, I need to execute the method this.sharedService.openMarvinModal(false);. However, upon executing this me ...

The error message "Cannot read property 'firestore' of undefined" is often encountered when

I developed an Angular application to test Firebase functions and deployed it on Firebase hosting. Almost everything is working except for the Firestore function, which is causing this error: main.8ae925009adf8b80e1bc.js:1 ERROR Error: Uncaught (in promis ...

Exploring Angular 10: Managing Two Promises in ngOnInit

I am currently working on integrating the Strava API into my Angular app. To summarize briefly: When a user clicks on a button to connect to Strava They are redirected to Strava for authentication (using PKCE) Strava then redirects back to my app with a ...

The Vue store array declaration triggers a TS error stating that it is not assignable to a parameter of type never

I'm puzzled as to why this error keeps showing up: Argument of type '{ id: string; }' is not assignable to parameter of type 'never'. ... appearing at const index = state.sections.findIndex((section) => section.id === id); T ...

received TypeError when using combineLatest

import { combineLatest } from 'rxjs'; const obs1 = getAndCreateObservableOne(); const obs2 = getAndCreateObservableTwo(); console.log('Initial output', obs1, obs2); obs1.subscribe(e => console.log('Second output', e)); o ...

Upon running the code, no errors appear on the console. However, my project isn't functioning properly and I'm encountering errors on the web console

ReferenceError: require is not defined when trying to access external "url" at Object.url in webpack_require (bootstrap:83) at client:6 importing from webpack-dev-server client index.js(http://0.0.0.0:0) vendor.js:219506 dynamically imp ...

Understanding the transition from v14 to v15 of Angular Material theming: What changes to expect?

After the recent update from Angular Material, there have been changes in how theming works. I went through the tutorial on the Angular Material website and defined a palette with my primary/accent colors as follows: $lightBlue-palette: ( 50: #f1f7f7, ...

What is the best way to incorporate an interface in TypeScript with a specific attribute?

I recently came across the Vue3 reactive library code. However, I am not well-versed in TypeScript and unsure how to implement interfaces like the one below: export interface ReactiveEffect<T = any> { (): T _isEffect: true id: number } It appe ...

When attempting to compile Angular in production mode, errors may arise such as the Uncaught SyntaxError caused by an Unexpected token '<'

I encountered some errors in the console of my Angular 8 app. When I opened the browser window, it was blank and this error appeared: Uncaught SyntaxError: Unexpected token '<' https://i.sstatic.net/a16DD.png I tried running different ng bui ...

I am looking to incorporate serial numbers into two distinct loops within an Angular application

I need help adding a serial number using two separate ngFor loops. Here is the code: <table> <tr> <th>Sr</th> <th>Name</th> </tr> <ng-container #atvalue> <tr *ngFor="let item of items; l ...

Creating Mongoose models in TypeScript with multiple connections

Attempting to build a model with multiple connections as per the documentation, I encountered the following error: TS2345: Argument of type 'Schema<Document<any>, Model<Document<any>>>' is not assignable to parameter of ty ...

The attribute 'XX' is not recognized within the 'useState' type

I am facing an issue with an API call in my code. Here is a snippet where I receive the response and add it to the state using setInfo: const [info, setInfo] = useState([]) axios.post('/user', { data: 'data' }) .then(response => ...