在角度为4的选择框中处理optgroup

Vik*_*ram 3 data-binding typescript angular

如何在角度4的选择框中获取onchange函数中的optgroup标签值

我有一个表格中的选择框,其中有多个日期作为选项组,时间为24小时格式,分别为1000,1200和1400,分别为10 AM12PM和2PM.

    <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>
Run Code Online (Sandbox Code Playgroud)

现在我使用onchange函数获取所选的时间/点值但我想获得选项标签是否有任何方法来获取optgroup标签?

一旦我们提交表单,我们在数据库中保存插槽,在编辑页面上我们用数据绑定显示它,但由于多个optgroup可以有相同的插槽,它总是显示第一个选择的optgroup值

不确定如何显示此处选择的确切optgroup值.

Meh*_*oha 5

您可以使用VanillaJS来实现这一点,在您的change函数中编写以下代码:

const selectedIndex = ev.target.selectedIndex;
const optGroupLabel = ev.target.options[selectedIndex].parentNode.getAttribute('label');
Run Code Online (Sandbox Code Playgroud)

这是一个有效的stackBlitz:https ://stackblitz.com/edit/angular-64vvdn