Retrieving the value of a selected option in Angular

I have the following dropdown select in my HTML and I am currently retrieving the text content of the selected option. How can I access the value attribute instead?

Here is the dropdown select:

<form [formGroup]="angForm"  class="form-inline my-5 my-lg-0">
    <div class="post-emojy">
        <select #emoji class="textboxclass" type="text" placeholder="Emojy" aria-label="Post" formControlName="emoji" required>
            <option value="" disabled selected>šŸ˜€</option>
            <option value="angry" style="background-image:url(./src/assets/emoticons/png/angry.png);">angry</option>
            <option value="bored" style="background-image:url(~assets/emoticons/png/bored.png);">bored</option>
            <option value="confused" style="background-image:url(~assets/emoticons/png/confused.png);">confused</option>
            <option value="embarrassed" style="background-image:url(~assets/emoticons/png/embarrassed.png);">embarrassed</option>
            <option value="happy" style="background-image:url(~assets/emoticons/png/happy.png);">happy</option>
            <option value="kissing" style="background-image:url(~assets/emoticons/png/kissing.png);">kissing</option>
            <option value="unhappy" style="background-image:url(~assets/emoticons/png/unhappy.png);">unhappy</option>
            <option value="sad">sad</option>
        </select>
    </div>
</form>

Below is the method that fetches the value:

 angForm: FormGroup;

 constructor(
   private postService: PostServiceService,
   private fb: FormBuilder
 ) {
   this.createForm();
 }

 postMood(): void {
   const emoji = this.angForm.get("emoji").value;
   const text = this.angForm.get("postText").value;
   this.postService.postMoods(emoji, text);
   // Call to reset the form values
   this.angForm.get("postText").reset();

   function delay(ms: number) {
     return new Promise((resolve) => setTimeout(resolve, ms));
   }

   (async () => {
     await delay(300);
     location.reload();
   })();
 }

Answer ā„–1

In my approach, I find it beneficial to store option-related data in an array and iterate through it.

this.emojis = [
  {
    displayValue: 'Happy',
    value: 'happy',
    src: './src/assets/emoticons/png/happy.png'
  },
  {
    displayValue: 'Sad',
    value: 'sad',
    src: '~assets/emoticons/png/sad.png'
  },
  ...
]

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

<select multiple formControlName="emoji">
  <option [ngValue]="null" disabled>Select your emotion</option>
  <option *ngFor="let emoji of emojis" [style.backgroundImage]="'url(` + emoji.src + ')'" [ngValue]="emoji.value">
   {{ emoji.displayValue }}
  </option>
</select> 

However, if extracting text content from a node is necessary, using ViewChild is the way to go.

Warning: Approach with caution

<option #emojiRefs *ngFor="let emoji of emojis" [style.backgroundImage]="'url(` + emoji.src + ')'" [ngValue]="emoji.value">
@ViewChildren("emojiRefs") private emojiRefs: QueryList<ElementRef<HTMLOptionElement>>;

this.emojiRefs.toArray()[0].textContent

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

Tips for capturing an error generated by a child component's setter?

I've created an App component that contains a value passed to a Child component using the @Input decorator. app.component.html <app-child [myVariable]="myVariable"></app-child> app.component.ts @Component(...) export class AppC ...

Retrieving information as the user navigates to the next page

Currently, I am using an API endpoint that retrieves over 1000 data objects and delivers them to the user. I believe this method is not efficient since only 30 objects are displayed at once. Is there a more efficient way to load these objects, perhaps in ...

Determining the appropriate version of the types package for your needs

It has come to my attention that certain npm packages do not come with types included. Because of this, the community often creates @types/packagename to provide those types. Given that both are packages, how does one determine which version of the types ...

What steps can I take to resolve the 'Object may be null' error in TypeScript?

I am facing a similar issue to the one discussed in this thread, where I am using Draft.js with React and Typescript. After following the code example provided in their documentation, I encountered the 'Object is possibly 'null'' error ...

Error in the ngx-owl-carousel-o-Angular causing disruptions in the carousel rotation

I've integrated the owl carousel into my Angular project to showcase various elements. The carousel is set to only display from 767px downwards with display:block, and above 767px it's set to display:none. However, I'm encountering a glitch ...

Is there a way to turn off the "defer" feature in an Angular build?

After compiling my Angular project, I noticed that the compiler automatically adds the "defer" attribute to the script tag in my "index.html" file. However, I need to disable this feature. Is there a way to do it? I am currently working with Angular versi ...

Using TypeScript to create a unique object type that is mapped with generics for each key

Suppose I have a type representing an array of two items: a list of parameters and a function with arguments corresponding to the parameters. I've created a handy function to infer the generic type for easy use. type MapParamsToFunction<A extends a ...

Step-by-step guide for importing a JSON file in React typescript using Template literal

I am facing an error while using a Template literal in React TypeScript to import a JSON file. export interface IData { BASE_PRICE: number; TIER: string; LIST_PRICE_MIN: number; LIST_PRICE_MAX: number; DISCOUNT_PART_NUM: Discout; } type Discoun ...

Encountering an issue with unexpected token 'import' while working on Angular-cli and RC

Currently, I'm in the process of setting up Material 2 with Angular-cli RC5. However, when attempting to load the material button component in app.module.ts, I encounter the following error message. zone.js:461 Unhandled Promise rejection: SyntaxErro ...

Verify the status of the nested reactive forms to determine if the child form is in a dirty state

I am working on a form that consists of multiple sections within nested form groups. I need to find a way to detect when changes are made in a specific section. Here is the HTML structure: <div [formGroup]="formGroup"> <div formGroupN ...

Tips for minimizing the amount of code in Angular 5

As our Angular 5 application continues to expand, due to being a Single Page Application with dynamic components, our main component is becoming overloaded. The main component is responsible for rendering other components and contains the majority of the l ...

What could be the reason for the 'tsc' command not functioning in the Git Bash terminal but working perfectly in the command prompt?

I recently installed TypeScript globally on my machine, but I am facing an issue while trying to use it in the git bash terminal. Whenever I run tsc -v, I encounter the following error: C:\Users\itupe\AppData\Roaming\npm/node: l ...

Storing multiple strings in a string array in Angular2

Hi everyone, Iā€™m just getting started with Angular and currently working on creating a recipe page that fetches data from an API. The API setup is complete, but now I need to figure out how to input the data into the API using Angular. I have defined a ...

Encountering the error "RouterOutletMap provider not found" while using angular-cli version 1.0.0-beta.10

I am facing confusion while trying to set up routing for angular-cli version 1.0.0-beta.10, using @angular/router version 3.0.0-beta.2. I encountered an error message stating 'No provider for RouterOutletMap'. Any assistance in resolving this iss ...

Creating a gradient background with the makeStyles function

Why is it that the background: 'linear-gradient(to right, blue.200, blue.700)' doesn't work within makeStyles? I just want to add a gradient background to the entire area. Do you think <Container className={classes.root}> should be rep ...

Icon positioned to the left within the text box

Hey there! I'm new to NativeScript and I've been struggling to place an icon inside a textbox. Can someone please help me out? Expected Output: https://i.stack.imgur.com/xvoZG.png Code <GridLayout columns="*, *" rows=& ...

Discover the Magic of Angular 8 and Bootstrap 4 Tooltips

I'm trying to implement tooltips from Bootstrap 4 into my web application. According to Bootstrap documentation, I should initialize the tooltips with the following code: $(function () { $('[data-toggle="tooltip"]').tooltip() }) (Implement ...

Ensuring type compatibility in a declarative manner: What are the methods?

My goal is to establish a compile-time constraint that ensures a variable of type T2 can be assigned to a variable of type T1. If I have a value (t2) of type T2, I can simply do the following: const t1: T1 = t2; Is there an alternative method to achiev ...

Unable to connect to 'formGroup' as it is not recognized as a valid property of 'form' within the component on the page

Currently, I am in the process of developing an app using Ionic. One of the pages I have created is called survey, and its corresponding component is known as SurveyPage. Within this page, there are various texts displayed along with a component tagged as ...

Changing Ionic Column Widths Based on Content Length

In my dynamic ionic 2 grid system, I am facing a layout issue. <div> <ion-row> <ion-col > ; <ion-card-header class="card-header"> {{hunt.title}} </ion-card-header> </ion-col> <ion-col *ngIf="!hunt. ...