46

如何从 Angular 4 中的选择选项中获取值?

我想将它分配给 component.ts 文件中的一个新变量。我试过了,但什么也没输出。

你也可以使用 [(ngModel)] 吗?

组件.html

<form class="form-inline" (ngSubmit)="HelloCorp(f)" #f="ngForm">
     <div class="select">
         <select class="form-control col-lg-8" #corporation required>
             <option *ngFor="let corporation of corporations" [value]="corporationObj">{{corporation.corp_name}}</option>    
         </select>
             <button type="submit" class="btn btn-primary manage">Submit</button>
     </div>
</form>

组件.ts

HelloCorp() {
const corporationObj = corporation.value;
}
4

7 回答 7

58

一般情况下(请参阅此处的 Stackblitz:https ://stackblitz.com/edit/angular-gh2rjx ):

HTML

<select [(ngModel)]="selectedOption">
   <option *ngFor="let o of options">
      {{o.name}}
   </option>
</select>
<button (click)="print()">Click me</button>

<p>Selected option: {{ selectedOption }}</p>
<p>Button output: {{ printedOption }}</p>

打字稿

export class AppComponent {
  selectedOption: string;
  printedOption: string;

  options = [
    { name: "option1", value: 1 },
    { name: "option2", value: 2 }
  ]
  print() {
    this.printedOption = this.selectedOption;
  }
}

在您的特定情况下,您可以像这样使用 ngModel:

<form class="form-inline" (ngSubmit)="HelloCorp()">
     <div class="select">
         <select [(ngModel)]="corporationObj" class="form-control col-lg-8" #corporation required>
             <option *ngFor="let corporation of corporations"></option>    
         </select>
         <button type="submit" class="btn btn-primary manage">Submit</button>
     </div>
</form>

HelloCorp() {
  console.log("My input: ", corporationObj);
}
于 2017-09-27T12:12:12.047 回答
41

export class MyComponent implements OnInit {

  items: any[] = [
    { id: 1, name: 'one' },
    { id: 2, name: 'two' },
    { id: 3, name: 'three' },
    { id: 4, name: 'four' },
    { id: 5, name: 'five' },
    { id: 6, name: 'six' }
  ];
  selected: number = 1;

  constructor() {
  }
  
  ngOnInit() {
  }
  
  selectOption(id: number) {
    //getted from event
    console.log(id);
    //getted from binding
    console.log(this.selected)
  }

}
<div>
  <select (change)="selectOption($event.target.value)"
  [(ngModel)]="selected">
  <option [value]="item.id" *ngFor="let item of items">{{item.name}}</option>
   </select>
</div> 

于 2018-08-28T19:53:27.110 回答
6

HTML 代码

    <form class="form-inline" (ngSubmit)="HelloCorp(modelName)">
        <div class="select">
            <select class="form-control col-lg-8" [(ngModel)]="modelName" required>
                <option *ngFor="let corporation of corporations" [ngValue]="corporation">
                    {{corporation.corp_name}}
                </option>    
            </select>
            <button type="submit" class="btn btn-primary manage">Submit</button>
        </div> 
    </form>

组件代码

HelloCorp(corporation) {
    var corporationObj = corporation.value;
}
于 2018-03-14T10:03:10.730 回答
4

你只需要穿上[(ngModel)]你的选择元素:

<select class="form-control col-lg-8" #corporation required [(ngModel)]="selectedValue">
于 2017-09-27T12:08:52.950 回答
0
    //in html file
    <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="name">Country</label>
                        <select class="form-control" formControlName="country" (change)="onCountryChange($event.target.value)">
                            <option disabled selected value [ngValue]="null"> -- Select Country  -- </option>
                            <option *ngFor="let country of countries" [value]="country.id">{{country.name}}</option>
                            <div *ngIf="isEdit">
                                <option></option>
                            </div>
                        </select>
                      </div>   
                </div>
            </div>
            <div class="help-block" *ngIf="studentForm.get('country').invalid && studentForm.get('country').touched">
                <div *ngIf="studentForm.get('country').errors.required">*country is required</div>
            </div>
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="name">State</label>
                        <select class="form-control" formControlName="state" (change)="onStateChange($event.target.value)">
                            <option disabled selected value [ngValue]="null"> -- Select State -- </option>
                            <option *ngFor="let state of states" [value]="state.id">{{state.state_name}}</option>
                        </select>
                      </div>   
                </div>
            </div>
            <div class="help-block" *ngIf="studentForm.get('state').invalid && studentForm.get('state').touched">
                <div *ngIf="studentForm.get('state').errors.required">*state is enter code hererequired</div>
            </div>
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="name">City</label>
                        <select class="form-control" formControlName="city">
                            <option disabled selected value [ngValue]="null"> -- Select City -- </option>
                            <option *ngFor="let city of cities" [value]="city.id" >{{city.city_name}}</option>
                        </select>
                      </div>   
                </div>
            </div>
            <div class="help-block" *ngIf="studentForm.get('city').invalid && studentForm.get('city').touched">
                <div *ngIf="studentForm.get('city').errors.required">*city is required</div>
            </div>
    //then in component
    onCountryChange(countryId:number){
   this.studentServive.getSelectedState(countryId).subscribe(resData=>{
    this.states = resData;
   });
  }
  onStateChange(stateId:number){
    this.studentServive.getSelectedCity(stateId).subscribe(resData=>{
     this.cities = resData;
    });
   }`enter code here`
于 2021-02-17T05:20:48.507 回答
0

这实际上很简单。

请注意我是

I. 将name="selectedCorp"添加到您的选择开始标签中,并且

二、将您的[value]="corporationObj"更改为[value]=" corporation ",这与您的 *ngFor="letcorporation ofcorporations " 声明中的公司一致:

 <form class="form-inline" (ngSubmit)="HelloCorp(f)" #f="ngForm">
   <div class="select">
     <select class="form-control col-lg-8" #corporation name="selectedCorp" required>
       <option *ngFor="let corporation of corporations" [value]="corporation">{{corporation.corp_name}}</option>
     </select>
     <button type="submit" class="btn btn-primary manage">Submit</button>
   </div>
 </form>

然后在您的 .ts 文件中,您只需执行以下操作:

HelloCorp(form: NgForm) {
   const corporationObj = form.value.selectedCorp;
}

constcorporationObj现在是选定的公司对象,它将包括您定义的公司类的所有属性。

笔记:

在 html 代码中,通过语句[value]="corporation" 公司(来自 *ngFor="letcorporation ofcorporats " )绑定到[value]name属性将获得value

由于名称"selectedCorp" ,您可以通过在 .ts 文件中获取"form.value.selectedCorp"来获取实际值。

顺便说一句,实际上您不需要“选择”开始标签中的“#corporation” 。

于 2019-10-07T18:04:48.290 回答
0

而不是 $event。尝试使用下面的类型转换函数。

$any($event.target).value

这将停止模板中的类型检查。您可以在打字稿中创建一个函数来更新公司或直接分配给一个变量。

<select (change) = "updateCorporation($any($event.target).value)">
    <option>Corporation1</option>    
    <option>Corporation2</option>
</select>
于 2022-01-23T10:00:39.690 回答