【问题标题】:Angular 4 Get the Text of Selected option of Select controlAngular 4获取选择控件的选定选项的文本
【发布时间】:2018-04-23 09:14:11
【问题描述】:

我正在尝试在 Angular 4 中获取 Select 控件的 Text of Selected 选项。

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

我正在使用 Reactive 的 formControlName 属性。

请提出检索选定选择控件文本的想法

【问题讨论】:

  • 你得到了什么错误
  • 您能否提供更多代码来说明您在何处以及如何尝试获取文本?
  • 我想在“IndustryName”表单控件名称中设置选定的行业文本

标签: angular angular-reactive-forms


【解决方案1】:

进行以下更改

模板

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

组件

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

【讨论】:

  • 感谢拉胡尔的回复。但我想要行业的文本。例如:我的行业有值 {Id: 1 , Name: Pravin Id: 2 , Name : Rahul} 选择“Pravin”文本后,我可以将值设为“1”,但我想要文本值,即“Pravin”
  • @Pravin 更新了工作链接检查
  • 嗨 Rahul,我不想更改选项的值属性。它应该只是 {{Industry.Id}}
  • 那么您可以使用组件中的数据并在数组中使用它来获取值
  • @Pravin 我已经更新了一些谷歌搜索也希望得到帮助
【解决方案2】:

尝试以下方法:

模板

上传.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.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);
  }
}

希望这会有所帮助,并且准时。 :)

【讨论】:

    【解决方案3】:

    你可以这样做:

    在你看来

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

    在你的组件中

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

    【讨论】:

      【解决方案4】:

      实现这一点的最简单方法是:从 HTML 中获取 id,使用 id 值引发事件,然后在您的集合中搜索该项目。

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

      模型类

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

      【讨论】:

      • 他试图获取选定的值,而不是设置它。
      • @Jason Cheng,您是对的,但是,获取所选值的最直接方法是将控件绑定到变量,因此每次选择更改时,您仍将拥有更新的值。这也可以使用“模板引用变量”甚至使用 ElementRef 来完成。但是,正如我所说,我所知道的最直接的方法是我建议的方法。你知道更好的方法吗?请与我们分享。
      【解决方案5】:
      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>
      

      【讨论】:

        【解决方案6】:

        您可以使用 $event 属性简单地获取选定的值和文本

        html代码

        <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/> 
        

        打字稿代码

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

        【讨论】:

          【解决方案7】:

          你可以使用

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

          然后在组件中

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

          【讨论】:

            【解决方案8】:

            使用#reference 变量有一种比其他任何答案都简单得多的方法...

            进行了大量的实验以使其发挥作用。

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

            【讨论】:

              【解决方案9】:

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

              【讨论】:

                【解决方案10】:

                .ts页面,继续下面的代码..

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

                您将获得行业名称。

                【讨论】:

                  【解决方案11】:

                  如果你只想要标题值。

                  简单使用:

                  public onOptionsSelected(event) {
                     const value = event.target.value;
                  
                      let id = event.target.options[event.target.options.selectedIndex].title;
                      alert(id);
                  }
                  

                  【讨论】:

                    【解决方案12】:

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

                    }

                    【讨论】:

                      猜你喜欢
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 2018-05-18
                      • 2018-03-08
                      • 2020-03-23
                      • 2010-11-26
                      • 1970-01-01
                      • 2015-06-29
                      相关资源
                      最近更新 更多