What is the best way to retrieve the value and text from a mat-select element in Angular without causing the MatSelectChange event

In my HTML code, I have the following:

<mat-select placeholder="Job Category" formControlName="job_category" 
  (selectionChange)="selectedJobType($event)">
              <mat-option *ngFor="let job of jobTypes" [value]="job.jobid">
                {{ job.jobname }}
              </mat-option>
            </mat-select>

In my TypeScript file, I have defined a FormBuilder group for job category as such:

 jobRegisterForm = this.fb.group({
  job_category: [null, Validators.required]});

Inside the ngOnInit() function, I am setting the value using an ID like so:

this.jobRegisterForm.get('job_category').setValue(this.jobData.jobcategoryid);

After this, the value is displayed correctly in the dropdown. If the user changes the dropdown value, I can capture that information with the following TypeScript code:

selectedJobType(event: MatSelectChange) {
    this.selectedMatJob = {
  value: event.value,
  text: event.source.triggerValue
   };
  }

However, if the user does not change the dropdown value and clicks on save, how do I retrieve the selected text and value for 'job_category'?

Answer №1

If you wish to receive updates on value changes, you can subscribe to valueChanges.

// Once the form is created
this.jobRegisterForm.get('job_category').valueChanges.subscribe(res => {
    this.selectedMatJob = {
        value: res,
        text: this.jobType.find(j => j.jobid == res).jobname
    };
})
// Set initial value
this.jobRegisterForm.get('job_category').setValue(this.jobData.jobcategoryid);

Alternatively, you can set the job as the "value" itself

<mat-option *ngFor="let job of jobTypes" [ngValue]="job">

In this case, you will need to use compareWith,

<mat-select [formControl]="job_category" required [compareWith]="compare">
   ....
</mat-select>

In your .ts file

compare = (a: any, b: any) => a.jobid == b.jobid // Function declaration
// When setting a value, for example:
const job = this.jobTypes.find(j => jobid == this.jobData.jobcategoryid)
this.jobRegisterForm.get('job_category').setValue(job)

Yes, a FormControl has the capability to store an object

NOTE: It is recommended to have a compareWith function when assigning values directly from objects in jobTypes using "find". However, with compareWith, you have more flexibility such as:

this.jobRegisterForm.get('job_category').setValue(
  {jobid: 1, jobname: 'my first work'}
)

Moreover, it may not be necessary to fetch the value upon every change; you could simply add the category during submission. But keep in mind that this is just a suggestion.

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

Resetting Form Status in Angular 4

Recently, I encountered an issue with a modal containing a form that has required fields. Whenever I open the modal, the fields appear empty as expected. However, if I enter some text into a required field and then remove it, causing the field to become in ...

Struggling with loading partials in Sails.JS from the "assets" directory?

I am currently using Sails.JS as the backend paired with Angular 6 for the frontend of my application. Within my homepage.ejs file, I am trying to load HTML content from the assets folder: <!DOCTYPE html> <html> <!-- webpack generated ht ...

Commitments shatter amidst constructing a website

Utilizing promise and http.get to retrieve data from a JSON API in Wordpress. Once the data is retrieved, it should be displayed on a page... However, an error occurs when attempting to build the page due to the data not being available. What steps can ...

Guide on incorporating finos/perspective into an Angular 8 project using https://perspective.finos.org/

I am looking for guidance on incorporating Finos/Perspective Datagrid into my Angular 8 application. I need to input data in JSON format and have it output as a Datagrid. Any sample code or examples would be greatly appreciated. You can find the GitHub re ...

Examining form functionalities: angular2 form testing

Currently, I'm facing an issue while attempting to test a component that utilizes 'FormGroup' and 'FormBuilder'. Whenever I run the test file for this particular component, I encounter an error stating that 'FormGroup' an ...

Cross-Origin Resource Sharing (CORS) communication between an Angular application and an ASP.NET Core API running on a local

I am facing an issue with CORS errors in my local setup. Most of the calls to my ASP.NET Core API from the Angular App are successful, but one specific POST operation keeps giving me CORS errors. I believe it might be related to the nature of the POST requ ...

What is the best way to selectively pass certain values to the args object?

Is there a way in TypeScript to pass only one argument into args and have other values be default without using "args = {}" or declaring defaults within the function to avoid issues with intellisense? function generateBrickPattern ( wallWidth: number, ...

When using the "import" statement, all modules are automatically assigned types, unlike require(), which does not provide types

I am unsure if the following issue is related to VS Code or not. Whenever I import packages in TypeScript using this syntax: import express from "express"; I receive both the code itself and the type definitions. However, when I utilize: const e ...

How does Typescript handle dependency injection compared to the JSDoc typedef module import for defining types?

Currently, I am facing an issue with defining dependency injection in Typescript. In my experience with JSDoc, I have used typedef import('./classModule.js').default myClass. To illustrate, let's consider multiple classes stored in their o ...

Validation of required property in the submit function is not functioning in a template-driven form that has a dropdown menu

In the Angular application, I have a template-driven form containing a dropdown menu (select element) that needs validation to ensure a value is selected before form submission. The only validation required is the 'required' property. Despite se ...

What are the steps for utilizing Temporal as a datatype?

Trying this code snippet: const a: Temporal = new Temporal.PlainDate(2024, 2, 1) Results in the error: Cannot use namespace 'Temporal' as a type.deno-ts(2709) What is causing this issue? It seems different from how the Date object is used in Ja ...

Obtain headers from an Excel file uploaded using the XLSX format in Angular

Is there a way to extract the first row containing name, email, and mobile as an array from an uploaded excel file? I am currently utilizing XLSX for this purpose. While I am able to retrieve the entire dataset into an array, my main goal is to only ex ...

The error message "Element is not defined (Object.<anonymous>)" is occurring in the context of Intro.js-react, React, Next.js, and Tailwind

Here is a code snippet: import { useState } from 'react'; import { Steps } from 'intro.js-react'; export default function Dashboard() { const [stepEnabled, setStepEnabled] = useState(true); const steps = [ { intro: &apos ...

Why is the navbar toggle malfunctioning despite having all necessary dependencies in Angular?

Recently, I've been tackling the challenge of implementing a Navbar with collapse menu and dropdown links using Bootstrap 4 and Angular 6. However, I've hit a roadblock as the Navbar is not functioning as expected. Although the elements seem to r ...

The closeOnClickOutside feature seems to be malfunctioning in the angular-2-dropdown-multiselect plugin

I'm currently using 2 angular-2-dropdown-multiselect dropdowns within a bootstarp mega div. The issue I'm facing is that when I click on the dropdown, it opens fine. However, when I click outside of the dropdown, it doesn't close as expected ...

Creating a TypeScript class to extend the JavaScript object prototype

tl;dr: My goal is to apply compiled Typescript prototype definitions to objects I have defined as classes. Situation: I am looking to enhance a JavaScript object with business logic specified in a typescript class. For example: class Address { constr ...

Unable to proceed with npm install due to absence of a package.json file in the directory

Let me share my recent experience: I decided to update the @angular-cli version on my local machine, but it ended up causing a series of issues (like 'Cannot find module '@angular/compiler-cli/ngcc'). Despite trying various solutions, none s ...

Angular feature: Utilizing the @Output decorator for subscribing to EventEmitter

I have created a custom directive featuring an @Output EventEmitter: @Directive({ selector: '[ifValid]' }) export class SubmitValidationDirective { @Output('ifValid') valid = new EventEmitter<void>(); constructor( ...

Error: The field 'password' is not found in the specified type

Hey, I'm fairly new to TypeScript and encountering an error with my express and MongoDB application. Let's take a look at my User.ts model. import mongoose from "mongoose"; interface IUser { username: string; password: string ...

Generating a log file within an Angular 2 application

Looking for suggestions on how to create a log file in Angular 2 to track executed functions. I need a way to append logs to a file stored in the project folder, without having the file download for each execution like with angular2-txt and saveAs in JS. ...