Managing optgroup in select dropdown using Angular 4

Is there a way to retrieve the optgroup label value within an onchange function on a select box in Angular 4?

In my form, I have a select box with multiple dates as option groups and time slots in 24-hour format for booking (e.g. 1000 for 10AM, 1200 for 12PM, etc).

    <select class="form-control" formControlName="arrival_time" (change)="onSlotChange($event)">
        <option value="" data-date="" data-slot="">Select Arrival Time</option>
         <ng-container *ngIf="!availablePrevSlots">
            <optgroup label="{{availablePrevSlotDate}}">
               <option value=null hidden>-- No Slot Available --</option>
            </optgroup>
         </ng-container>

        <!-- More ng-containers for different scenarios -->

      </select>

I am successfully getting the selected time/slot value using the onchange function. However, I also need to retrieve the optgroup label. Is there a way to achieve this?

When submitting the form, the selected slot is saved in the database. On the edit page, when binding the data, it always shows the first optgroup value selected due to multiple optgroups having the same slots. How can I display the exact optgroup value that was selected?

Answer №1

To achieve this, you can utilize VanillaJS. Simply add the following code snippet to your change function:

const selectedIndex = ev.target.selectedIndex;
const optGroupLabel = ev.target.options[selectedIndex].parentNode.getAttribute('label');

For a demonstration, check out this functional stackBlitz: https://stackblitz.com/edit/angular-64vvdn

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

Need help with resetting a value in an array when a button is clicked?

Using Tabulator to create a table, where clicking on a cell pushes the cell values to an array with initial value of '0'. The goal is to add a reset button that sets the values back to '0' when clicked. component.ts names = [{name: f ...

Ensure that the text is wrapped properly when implementing innerHTML functionality

Within my Angular 5 application, I am faced with a requirement to display HTML content retrieved from a database. An example of the text stored in the database is: <div><u>Documents and Files</u></div><ul><li>These docu ...

The PKIJS digital signature does not align with the verification process

Explore the code snippet below const data = await Deno.readFile("./README.md"); const certificate = (await loadPEM("./playground/domain.pem"))[0] as Certificate; const privateKey = (await loadPEM("./playground/domain-pk ...

Differences between Typescript and Node versions

Is there a connection between the version of Typescript and the version of Node since Typescript is a global npm module? In other words, is there a minimum Node version required to run a specific version of Typescript. ...

Laravel 5.4 integrates with Angular4: Implementing Passport token requests

Trying to make a Token request from API using: Signin(email: string, password: string): void { let data: Object = { client_id: 2, client_secret: 'vSFxVqALQHjyotPyGfhrGj3ziudUGsts2ZWiAGms', grant_type: 'password&a ...

Is it possible to load components lazily without lazy loading modules in Angular?

Lazy loading is a widely used strategy, especially in Angular where it typically applies at the module level. However, can components be lazily loaded as well? Most web tutorials explain how lazy loading works with modules, such as having a main module in ...

Is it possible to compile a TypeScript file with webpack independently of a Vue application?

In my Vue 3 + Typescript app, using `npm run build` compiles the app into the `dist` folder for deployment. I have a web worker typescript file that I want to compile separately so it ends up in the root of the `dist` folder as `worker.js`. Here's wha ...

npm is unable to install the package called 'node-sass'

So, I'm running a project with npm start and suddenly encountering the same error in multiple components: Module build failed: Error: Cannot find module 'node-sass' Frustrated, I decide to run 'npm install node-sass', only to be ...

The local types package cannot be built by react-scripts even though tsc has successfully completed the process

I have developed an application with a TypeScript frontend and backend. To streamline the process, I decided to create a shared types module that contains all the necessary types for both components in one centralized location. Rather than going through th ...

Tips on converting a date string in the format 'dd/MM/yyyy' to a date type using TypeScript

I have attempted the following code in order to convert the date from 'yyyy-mm-dd' format to 'dd/MM/yyyy'. However, when I check the typeof() of the result, it shows that it is a string. Is there a method to convert it into only a date? ...

Error: Cannot locate 'import-resolver-typescript/lib' in jsconfig.json file

Issue: An error occurred stating that the file '/Users/nish7/Documents/Code/WebDev/HOS/frontend/node_modules/eslint-import-resolver-typescript/lib' could not be found. This error is present in the program because of the specified root file for c ...

Exploring Angular (5) http client capabilities with the options to observe and specify the response type as 'blob'

Situation: I'm facing a challenge in downloading a binary file from a backend system that requires certain data to be posted as JSON-body. The goal is to save this file using File-Saver with the filename specified by the backend in the content-disposi ...

Error on the main thread in NativeScript Angular for Android has not been caught

As a beginner in the field of mobile development, I am currently exploring NativeScript and encountering an error in my Android application. https://i.stack.imgur.com/BxLqb.png You can view my package.json here ...

Acquiring an element through ViewChild() within Angular

I am in need of a table element that is located within a modal. Below is the HTML code for the modal and my attempt to access the data table, which is utilizing primeng. <ng-template #industryModal> <div class="modal-body"> <h4>{{&a ...

Error: Uncaught TypeError - Unable to access 'reduce' property of undefined value

Currently, I am focusing on implementing yup validation. Specifically for FileList validation, encountering an issue where leaving the input empty triggers the following error message: enter image description here Below is the code snippet in question: (C ...

Removing a key from an index signature in Typescript - a step-by-step guide

In my web application built with Angular, we encountered a need for a data type to store translations of strings in different languages. To address this requirement, a team member defined the following type: export class TranslatedString { [language: str ...

Obtaining the count of a specific column in Angular 6 by grouping objects based on the same value in an array

In TypeScript, I have an array of objects and I am using a foreach loop. The array contains 2 columns with a progress value of 100, while the rest have values less than 100. My goal is to calculate the count of columns with a progress value of 100, which ...

Tips for providing certificate key file during the deployment of a cloud function?

Within my TypeScript file, the following code is present: import * as admin from 'firebase-admin' import * as functions from 'firebase-functions' const serviceAccountKey = "serviceAccountKey.json" const databaseURL = "https://blahblah. ...

What specifications need to be set up for server and client configurations when using a MEAN Stack application?

When preparing to launch a mid-level enterprise application for the MEAN Stack, what specific configurations are required? How should these configurations be implemented with Angular 2/4/5 and NodeJS? ...

Error: Trying to access the `push` property of an undefined value is causing an issue

Issues with using the push method in TypeScript have arisen. Here are the details: Below is the code snippet for the reservation modal component: guestArray=[1, 2, 3, 4, 5, 6]; guests: number; isDateTime: boolean = false; constructor(private params: Mo ...