14

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

3
  • what is the erro you get Commented Nov 10, 2017 at 7:33
  • Could you supply some more code as to where and how you are trying to get the text? Commented Nov 10, 2017 at 7:35
  • i want to Set the Selected Industry Text in "IndustryName" formcontrolname Commented Nov 10, 2017 at 7:41

12 Answers 12

19

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;
}
Sign up to request clarification or add additional context in comments.

Comments

10

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;         
}

2 Comments

He's trying to get the selected value, not set it.
@Jason Cheng, you are correct but yet, the most direct way of getting the selected value is binding the control to a variable so everytime the selection changes, you will still have the updated value. This could also be done using "Template reference variables" or even using ElementRef. But yet, as I said, the most direct approach I know is the one I've suggested. Do you know a better way? Please share with us.
8
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>

Comments

3

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; 
} 

Comments

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;
      }

Comments

3

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);
}

Comments

3

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.

Comments

1

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>

Comments

0

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

6 Comments

Thanx Rahul for your reply. But i want text of Industry. For Eg: My industry has values {Id: 1 , Name: Pravin Id: 2 , Name : Rahul} After Selecting "Pravin" Text , i can able to get value as "1" but i want Text value i.e. "Pravin"
@Pravin udpated the woking link check
Hi Rahul, I dont want to change the Value Property of the Option. It should be {{Industry.Id}} only
then what you want you can use the data in compoennt ans use it in the array to get the value
@Pravin i have updated it a bit of googling also wilh help
|
0

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. :)

Comments

0

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");
}

Comments

0

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);

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.