Access the value of the option that has been selected within the Component

When utilizing Angular7 CLI, I am attempting to retrieve the value of mat-select which is associated with a FormControl within a FormGroup. Upon retrieving the value, it displays as [object object]

In one solution, I have added [(value)]="selectedOption". However, this does not align with the official documentation

Below is the component code:

purposeControl = new FormControl('', [Validators.required]);
purposeList: Purpose[] = [
    {id: '0', value: 'Self Care'},
    {id: '1', value: 'Caring for someone'},
];

validateVitalsFormGroup = new FormGroup({
  purposeControl: this.purposeControl,
});

Implemented a 'submit' button to submit data

Returning back to the component :

onFormSubmit(): void {
  console.log('Purpose:' + 
this.validateVitalsFormGroup.get('purposeControl').value);
}

Here is the HTML code:

<mat-form-field>
    <mat-select [(value)]="selectedOption" placeholder="Purpose" [formControl]="purposeControl" required >
        <mat-option>--</mat-option>
        <mat-option *ngFor="let purpose of purposeList" [value]="purpose">{{purpose.value}} </mat-option>
    </mat-select>
    <mat-error *ngIf="purposeControl.hasError('required')"> Please choose a Purpose</mat-error>
    <mat-hint>{{purposeControl.value?.value}}</mat-hint>
</mat-form-field>

The expected value should be either id 0 or 1 based on selection in the HTML.

Answer №1

When selecting a value, it is important to use purpose.id instead of just purpose, as purpose refers to an object.

<mat-option *ngFor="let purpose of purposeList" [value]="purpose.id"> // Use purpose.id if you want to select the Id as the value;
    {{purpose.value}} 
</mat-option>

After defining the purpose.id, you can then:

onFormSubmit(): void {
  console.log('Purpose:' + this.validateVitalsFormGroup.get('purposeControl').value);
}

If you prefer to use the entire purpose object as the value, follow these steps:

onFormSubmit(): void {
  console.log('Purpose Id:' + this.validateVitalsFormGroup.get('purposeControl').value.id);
  console.log('Purpose Value:' + this.validateVitalsFormGroup.get('purposeControl').value.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

Several mat-table components are displayed on a single page, with each table equipped with its own loading spinner to indicate network activity

Currently, I am encountering a problem while trying to display multiple mat-tables (any number of tables) and I need a spinner to be shown whenever there is a network request for data on a particular table. The loader should only appear in that specific ...

The process of retrieving information from an AngularFire2 function

I am facing an issue while trying to create a variable using a function from AngularFire2. The function I am using is authorizeUser(). However, when I try to assign the result of this function to this.user, the console window displays 'undefined' ...

How to display ngx-toastr using the show() method in Angular 2+ with a specific type

Working with ToastrService.success/error/warning/info() poses no issues for me, However, when attempting to utilize ToastrService.show(), I am unsure of the correct string type to pass along I made an attempt by sending an enum like so: export enum To ...

What is the best way to convert the date 19990813 from the format YYYY-MM-DD to 13.08.1999 in the format DD-MM-YYYY, using dots as separators?

Struggling to convert the string date 19990813 provided by the backend into the format 13.08.1999 with dots. Unable to do so successfully. Even when using Angular's built-in date format function, always ending up with the incorrect date. Any suggest ...

Execute a pair of scripts specified in the package.json file

Here is my package.json: "scripts": { "dev": "cross-env NODE_ENV=development nodemon src $NODE_DEBUG_OPTION --exec babel-node", "build": "babel src -s -D -d dist", "tsc:w": "tsc -w" } To run my project, I need to execute two commands: np ...

Restrict the discriminator value in a discriminated union from any other string literal union type in TypeScript

My discriminated union is quite basic, but I want to restrict the discriminator to only allow specific values that come from another string literal union type. This would simplify the process of adding new "cases" to the discriminated union. Here is a str ...

Calculating different percentages from a reduced map containing JSON data

Forgive me in advance if there's a similar question out there, but after a day of searching, I couldn't find what I need. I'm calling an API that responds with data, and I've extracted the necessary details to create a JSON file with t ...

Enhancing asynchronous operations with TypeScript and ExpressJs using Async/Await

Exploring the benefits of TypeScript's async/await in an Express project, I came across the following code snippet that seems to be stuck indefinitely without producing any outcome. Any thoughts on how to fix this issue? .. router.get('/test ...

Is there a way in Jest to restrict function calls to only those that are expected and disallow any other unauthorized calls

When working with Jest, you have the ability to mock out and spy on function calls within a function using functionalities like jest.spyOn and jest.fn() with .toHaveBeenCalledTimes(1) etc. However, in Spock framework testing, you can conclude your unit tes ...

Tips for accurately inputting a Record key in typescript

Within my code, I have a function that filters the properties of an object based on a specified filtering function: function filterProps<K extends string, V>(object: Record<K, V>, fn: (key:K, value: V, object: Record<K, V>) => unknown) ...

What circumstances allow @Inject to be optional in Angular?

My Angular service is simple yet causing errors. Here's the code snippet: // service.ts export class SimpleService { // ... } // component.ts @Component({ selector: 'my-component', templateUrl: 'components/mycomp/mycomp.ht ...

Angular 7 CLI throwing an error when generating a component: 'Unable to locate property 'sourceRoot' due to undefined value'

Encountered this error while attempting to run the command in CLI: ng generate component [component-name] An error kept popping up: Cannot read property 'sourceRoot' of undefined It seems like the error started happening after I updated my An ...

The absence of a type in AnyAction is causing a TypeScript error in react testing

I ran into an issue and received the following error message: TS2345: Argument of type '(dispatch: Dispatch) => Promise<void>' is not assignable to parameter of type 'AnyAction'. Property 'type' is missing in type & ...

The first click causes Highchart to display with varying heights

I have implemented a highchart within a chart object in HTML, with CSS defining the height and width of the chart object. Initially, upon first render, the chart has a height of 290px. However, when I click on the tab again, the chart stretches to a height ...

Conflicting TypeScript enum types: numbers and numbers in NestJS/ExpressJS

Incorporating types into my NestJS server has been a priority. After creating a controller (a route for those who prefer Express), I attempted to define the type for params: public async getAllMessages( @Query('startDate', ValidateDate) start ...

Locate, choose, and interact with a specific choice using Python Selenium

While working on an automated task software, I have been utilizing Selenium with Python to navigate the web. Despite making progress, I have encountered a problem that I am unable to resolve. I am trying to locate a tag using Selenium in order to choose o ...

How can a Firestore Timestamp object be correctly created within a rules test data set?

I am in the process of writing tests for Firestore rules, focusing on testing rules that control when actions can be executed based on a timestamp stored in the document. It is important to note that the rules will utilize rules.Timestamp rather than Java ...

Contrast between sourcing a file from the current directory versus from the node_modules folder

Why does the typescript compiler accept importing from a JS file in the local directory but raises an error when importing from node_modules? Code: import { t2 } from "./t1.js" t2.hello(); import { mat4 } from "./node_modules/gl-matrix/esm ...

Refresh your content with the pull-to-refresh feature in Ionic 2

latest-news.html update function <ion-refresher (ionRefresh)="doUpdate($event)"> <ion-refresher-content pullingText="pull to update"> </ion-refresher-content> </ion-refresher> retrieve latest news from server <ion-li ...

Does the message "The reference 'gridOptions' denotes a private component member in Angular" signify that I may not be adhering to recommended coding standards?

Utilizing ag-grid as a framework for grid development is my current approach. I have gone through a straightforward tutorial and here is the code I have so far: typography.component.html https://i.stack.imgur.com/XKjfY.png typography.component.ts i ...