【问题标题】:dropdown selected value in typescript angularjs打字稿angularjs中的下拉选择值
【发布时间】:2017-02-08 16:54:37
【问题描述】:

我的 html 中有一个下拉和应用按钮,在我的 ts 文件中,我声明了 apply() 函数和数组。我可以在我的前端显示带有值的下拉列表,但是当我单击应用按钮时,我没有从下拉列表中获取选定的值。我现在使用一个 lert 框来显示选定的值。

 <div class="form-group">
                <label for="inputdefault" class="control-label col-sm-2">Portal:</label>
                 <div class="col-sm-10">

                    <select class="form-control" id="inputdefault" name = "portal">
                        <option *ngFor="let c of portalValues">{{c.group}}</option>
                    </select>
                </div>
            </div>
          <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <button type="button" class="btn btn-primary" (click)="apply(portal)">Apply</button>                    
                    <button type="reset" class="btn btn-default" (click)="cancel()">Clear</button>
                </div>
            </div> 

在ts中,

 portalValues: Array<Object> = [{id:1, group:'Enterprise'},{id:2, group:'Business'}];

apply(portal:any) {
     alert(portal);
  }

并且警报值显示为未定义。如何从下拉列表中获取选定的值。

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    这是因为您传递的 portal 参数未定义。有多种方法可以做到这一点。一种是简单地声明一个Template Reference Variable

    例如:

    <select class="form-control" id="inputdefault" name = "portal" #portalSelect>
      <option [value]="c.group" *ngFor="let c of portalValues">{{c.group}}</option>
    </select>
    

    这里发生了两件事:

    1. 我在选择元素中添加了#portalSelect,以便可以引用它。
    2. 我将[value]属性绑定添加到选项元素并将其绑定到group属性(您可以将其绑定到您认为合适的位置,但如果您想绑定到对象本身,则需要使用@ 987654329@ 代替)

    然后,当您将选定的门户传递给您的组件函数时,您可以使用apply(portalSelect.value)

    如果您需要表单支持或者您想将选择绑定到您的组件,您将需要使用[(ngModel)]。在这种情况下,您可能希望在组件上为所选值提供一个属性,并像这样绑定到它:

    <select [(ngModel)]="selectedPortal">
    ...
    

    在你的组件中

    selectedPortal: any;
    
    apply() {
      // do something with this.selectedPortal
    }
    

    【讨论】:

    【解决方案2】:

    您需要在select 输入中包含ngModel。像这样的事情应该这样做。这样,变量portal 绑定到下拉列表中选择的值。 name 属性不这样做。

    <select class="form-control" id="inputdefault" [(ngModel)]="portal" name = "portal">
         <option *ngFor="let c of portalValues">{{c.group}} </option>
    </select>
    

    您可能还需要在您的 select 标记中包含此内容: #name="ngModel"

    【讨论】:

      猜你喜欢
      • 2017-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-19
      • 1970-01-01
      • 2016-11-21
      • 2019-06-04
      相关资源
      最近更新 更多