【问题标题】:Get Value From Select Option in Angular 4从Angular 4中的选择选项中获取价值
【发布时间】:2018-03-08 22:00:49
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: angular angular-directive angular4-forms


    【解决方案1】:

    一般情况下(请参阅此处的 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);
    }
    

    【讨论】:

    • 是这个吗?不再 (ngSubmit) 了吗?
    • 是的,就是这样。您可以使用 ngSubmit 触发事件,例如:console.log(corporationObj),并查看您选择的输入,但corporationObj 变量会立即更改,无需提交。
    • 你能看到我的代码吗?我忘了写这个 {{corporation.corp_name}}。这是选项值。你的还没有定义??
    • 我上面的一般例子应该适合你。如果不确定您是否已导入 FormsModule 并将其添加到 app.module.ts 中的导入数组中。
    【解决方案2】:

    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> 

    【讨论】:

    • 这是一个纯代码的答案,在 StackOverflow 中被认为质量不是很好。请详细说明这个 sn-p 的作用以及为什么它有助于解决原始问题。
    • 小修正:selectOption函数的第二行不应该是console.log(this.selected);(把“number”换成“selected”吗?
    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      您只需将[(ngModel)] 放在您的选择元素上:

      <select class="form-control col-lg-8" #corporation required [(ngModel)]="selectedValue">
      

      【讨论】:

      • 那么如何在component.ts中赋值呢?
      【解决方案5】:

      这其实很简单。

      请注意我是

      我。将 name="selectedCorp" 添加到您的 select 开始标签,然后

      二。将您的 [value]="corporationObj" 更改为 [value]="corporation",这与您的 *ngFor= 中的 corporation 一致“让corporation 公司”声明:

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

      而 const corporationObj 现在是选定的公司对象,它将包含您定义的公司类的所有属性。

      注意:

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

      由于 name"selectedCorp",因此您可以通过在 . ts 文件。

      顺便说一句,实际上您的 "select" 开始标记中不需要 "#corporation"

      【讨论】:

        【解决方案6】:
            //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`
        

        【讨论】:

        • 虽然此代码可能会为问题提供解决方案,但最好添加有关其工作原理/方式的上下文。这可以帮助未来的用户学习并最终将这些知识应用到他们自己的代码中。解释代码时,您也可能会得到用户的积极反馈/赞成。
        猜你喜欢
        • 2018-02-03
        • 1970-01-01
        • 2020-03-23
        • 2018-04-05
        • 2019-01-23
        • 2020-11-04
        • 2020-03-12
        • 2018-05-30
        • 1970-01-01
        相关资源
        最近更新 更多