nick gowdy
nick gowdy

Reputation: 6521

Angular5 - use key/value pair for select option

I've started working with angular5 and I'm trying to get the value of a select option and it's assigned ID onChange.

Component

import { Component, OnInit, EventEmitter } from '@angular/core';
// Services
import { LookupDataService } from '../../../service/lookup-data.service';


@Component({
  selector: 'diversity-dropdown',
  templateUrl: './diversity-dropdown.component.html',
  providers: [LookupDataService]
})
export class DiversityDropdownComponent implements OnInit {

  diversityForm: IDiversityForm[];
  title = 'Lookup data';
  selectedDiversity = '';

  constructor(private readonly lookupDataService: LookupDataService) { }

  ngOnInit() {
    this.lookupDataService.getDiversityForm().subscribe((diversityForm: IDiversityForm[]) => {
      this.diversityForm = diversityForm;
      console.log(diversityForm);

      }
    );
  }

  onChange($event) {
    console.log($event);
  }

}

View

<div *ngFor='let section of diversityForm'>
  <span class="label label-default">{{section.labelText}}</span>

<select (change)="onChange($event)" ng-model="">
<<option *ngFor='let dropdown of section.lookupDropdowns' id="{{dropdown.labelText}}" value="{{dropdown.value}} {{dropdown.labelText}}">{{dropdown.value}}</option>
</select>

  <br />
</div>

Data

enter image description here

I've tried $event.target.id but in the console it's an empty string. $event.target.value works however.

Is there an easy way of doing what I am trying to do?

Upvotes: 0

Views: 1575

Answers (1)

Alec Gerona
Alec Gerona

Reputation: 2897

Stackblitz demo here

You should use select in this way:

HTML:

<select [(ngModel)]="newGovId.first_id_type" (change)="function($event)">
      <option [ngValue]="null">Select something</option>
      <option *ngFor="let option of options"
              [ngValue]="option.value" [innerHtml]="option.text"></option>
</select>

The context of each option should be in the variable you're looping.

Upvotes: 1

Related Questions