Search code examples
angulartypescriptdata-binding

Handle optgroup in select box with angular 4


How can I get the optgroup label value in onchange function on a select box in angular 4

I have following select box in a form with multiple dates as options group and time in 24 hour format for booking like 1000,1200 and 1400 for 10AM,12PM and 2PM respectively.

    <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>
         <ng-container *ngIf="availablePrevSlots">
            <optgroup label="{{availablePrevSlotDate}}">
               <option value=null hidden>HH:MM</option>
               <option *ngFor="let slot of availablePrevSlots" [value]="slot">{{slotToString(slot)}}</option>
            </optgroup>
         </ng-container>
         <ng-container *ngIf="!availableSlots">
            <optgroup label="{{availableSlotDate}}">
               <option value=null hidden>-- No Slot Available --</option>
            </optgroup>
         </ng-container>
         <ng-container *ngIf="availableSlots">
            <optgroup label="{{availableSlotDate}}">
               <option value=null hidden>HH:MM</option>
               <option *ngFor="let slot of availableSlots" [value]="slot">{{slotToString(slot)}}</option>
            </optgroup>
         </ng-container>
         <ng-container *ngIf="!availableNextSlots">
            <optgroup label="{{availableNextSlotDate}}">
               <option value=null hidden>-- No Slot Available --</option>
            </optgroup>
         </ng-container>
         <ng-container *ngIf="availableNextSlots">
            <optgroup label="{{availableNextSlotDate}}">
                <option value=null hidden>HH:MM</option>
                <option *ngFor="let slot of availableNextSlots" [value]="slot">{{slotToString(slot)}}</option>
            </optgroup>
          </ng-container>
      </select>

Now I am getting the selected time/spot value with onchange function but I want to get the option label as well Is there any method to get the optgroup label ?

also once we submit the form we save the slot in data base and on edit page we show it with data binding but as multiple optgroup can have same slots it always shows first optgroup value selected

no sure how to show exact optgroup value selected here.


Solution

  • You can use VanillaJS in order to accomplish that, in your change function write this:

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

    And here's a working stackBlitz: https://stackblitz.com/edit/angular-64vvdn