Pravin
Pravin

Reputation: 301

Angular 4 Get the Text of Selected option of Select control

I am trying to get the Text of Selected option of Select control in Angular 4.

HTML:

<div class="col-sm-6 form-group">
<label>Industry</label>
<select   class="form-control select"  formControlName="Industry">
<option value="">Please select Value</option>  
<option *ngFor="let industry of industries"  
[ngValue]="industry.ID">{{industry.Name}}  
</option>  
</select> 
</div>


upload.component.ts
this.form.controls['Industry'].valueChanges.subscribe((name) => {
                this.form.controls['IndustryName'].setValue(name);
  });

I am using formControlName property from Reactive.

Kindly suggest the idea to retrive the Text of Selected Select control

Upvotes: 14

Views: 58772

Answers (12)

rajquest
rajquest

Reputation: 711

HTML

 <select class="form-control" formControlName="modelCode" (change)="changeValue($event)">                
            </option>
          </select>

TS

changeValue(event: any): void {
let text = event.target.options[event.target.options.selectedIndex].text;
console.log(text);

}

Upvotes: 0

vinay adepu
vinay adepu

Reputation: 51

In .ts page, Go on with the following code..

(this.industries.filter((ele)=>{return ele.ID==this.form.controls['Industry'].value}))[0].Name

You will get name of the industry.

Upvotes: 3

zibreel
zibreel

Reputation: 31

If you just want title value.

Simply use:

public onOptionsSelected(event) {
   const value = event.target.value;

    let id = event.target.options[event.target.options.selectedIndex].title;
    alert(id);
}

Upvotes: 3

HTML:

<div class="form-group">
        <label for="SelectCountry" class="col-md-3">Country</label>
        <div class="col-md-9">
          <select class="form-control" formControlName="Country" (change)="onChangeCountry($event)">
            <option *ngFor="let country of country; let i = index" value="{{i}}">{{country.name}}</option>
          </select>
        </div>
      </div>

.ts:

private SelectedCountry: any;
onChangeCountry($event) {
        this.SelectedCountry = $event.target.options[$event.target.options.selectedIndex].text;
      }

Upvotes: 3

RJB
RJB

Reputation: 2103

There's a much easier way than any of the other answers, using a #reference variable...

Took a lot of experimenting to get this to work.

<select #selectedSegment id="segment" name="segment" [(ngModel)]="entryForm.segmentId" type="text">
    <option *ngFor="let segment of segments" value="{{segment.id}}">{{segment.segmentName}}</option>
</select>

<div *ngIf="selectedSegment.selectedIndex !== -1 && selectedSegment.options.item(selectedSegment.selectedIndex).text === 'Testing'">

    {{ selectedSegment.options.item(selectedSegment.selectedIndex).text }}

</div>

Upvotes: 1

malballah
malballah

Reputation: 701

You can use

<select class="form-control" (change)="onChange($event)">

</select>

then in the component

onChange($event){
let text = $event.target.options[$event.target.options.selectedIndex].text;
}

Upvotes: 19

Daniel Santana
Daniel Santana

Reputation: 1837

The simpliest way to achieve that is: get the id from HTML, raise an event with the id value and then search your collection for the item.

HTML

<select class="form-control" [(ngModel)]="selectedStatusId" (change)="setSelectedStatus(selectedStatusId)">
   <option *ngFor="let status of statusList" [value]="status.id">{{status.name}}
   </option>
</select>

TypeScript

public setSelectedStatus(value: string): void {

  if (this.statusList && value) {
     let status: ListItemSimplified = this.statusList.find(s => s.id == value);
     if (status)
       this.selectedStatus = status.name;
   }
   else
      this.selectedStatus = '';
 }

Model Class

export class ListItemSimplified {
  id: string;          
  name: string;         
}

Upvotes: 10

khan Farman
khan Farman

Reputation: 366

You can simply get the selected value and text using the $event property

html code

<label>Select Market</label><br/> 
<select class="user-preselect btn-add" style="width: 90%;height: 34px;"(change)="selectchange($event)"> 
<option value="0" selected="selected">ADD Market</option> 
<option *ngFor="let country of Countrylist" [value]="country.id" >{{country.name}}</option> 
</select><br/><br/> 

typescript code

selectchange(args){ 
  this.countryValue = args.target.value; 
  this.countryName = args.target.options[args.target.selectedIndex].text; 
} 

Upvotes: 3

Charmy Shah
Charmy Shah

Reputation: 101

getSelectedOptionText(event: Event) {
   let selectedOptions = event.target['options'];
   let selectedIndex = selectedOptions.selectedIndex;
   let selectElementText = selectedOptions[selectedIndex].text;
   console.log(selectElementText)
}

HTML

<select class="form-control select" formControlName="Industry" (change)="getSelectedOptionText($event)">
  <option value="">Please select Value</option>  
  <option *ngFor="let industry of industries" value="{{industry.ID}}">{{industry.Name}}</option>
</select>

Upvotes: 8

Jnr
Jnr

Reputation: 1664

You can simply do:

In your View

<select class="select" (change)="onChange($event.target.value)" [(ngModel)]="someObject.BoundItem" name="BoundItem" #BoundItem="ngModel">
   <option *ngFor="let item of myObject" [value]="item.Id">{{item.displayiItem}}</option>
</select>

In your Component

onChange(selectedId: number)
{
   this.selectedItem = this.myObject.find((x: any) => x.Id == selectedId); 
   console.log(this.selectedItem["displayItem");
}

Upvotes: 0

pimisi
pimisi

Reputation: 439

Try the following:

Template

upload.component.html

<form [formGroup]="form">
  <div class="col-sm-6 form-group">
    <label>Industry</label>
      <select class="form-control select" 
        formControlName="industry" (change)="onChange()">
          <option value="">Please select Value</option>  
          <option *ngFor="let industry of industries"  
            [ngValue]="industry.id">{{ industry.name }}  
          </option>  
      </select> 
  </div>
</form>

Component

upload.component.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from "@angular/forms";

@Component({
  selector: 'app-upload',
  templateUrl: './upload.component.html',
  styleUrls: [ './upload.component.css' ]
})    

export class UploadComponent implements OnInit { 
  form: FormGroup;
  select: FormControl;
  industries = [
    {id: 1, name: 'Mining'},
    {id: 2, name: 'Information Technology'},
    {id: 3, name: 'Entertainment'}
  ];

  ngOnInit(){
    this.createForm();
  }

  createForm() {
    this.select = new FormControl('');
    this.form = new FormGroup({
      select: this.select
    });
  }

  onChange() {
    console.log(this.select.value);

    # to get the name that was selected

    const id = parseInt(this.select.value, 0);
    const selected = this.industries
      .filter(industry => industry.id === id)
      .reduce(function(str: string, project) {
        return str + project.name;
      }, '');

    console.log(selected.name);
  }
}

Hope this helps, and on time. :)

Upvotes: 0

Rahul Singh
Rahul Singh

Reputation: 19622

Make the following changes

Template

<form [formGroup]="test">
    <div class="col-sm-6 form-group">
        <label>Industry</label>
        <select class="form-control select" formControlName="Industry">
      <option *ngFor="let industry of industries"  [ngValue]="industry.id">{{industry.id}} </option>  
</select>
    </div>
</form>

<pre>{{test.value | json}} </pre>

Component

import { Component,OnInit } from '@angular/core';
import {FormArray, FormGroup, FormControl, Validators} from "@angular/forms";

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit { 
  name = 'Angular 5';
  test:FormGroup;
  industries = [{id:1},{id:2}];

  ngOnInit(){
     this.test = new FormGroup({
      Industry:new FormControl('')
    });

    this.test.get('Industry').valueChanges.subscribe(data => console.log(data));

  }

}

Working Link

Upvotes: 0

Related Questions