绑定并获取Typescript和Angular2中的下拉列表值 [英] Bind and fetch dropdown list value in typescript and Angular2

查看:509
本文介绍了绑定并获取Typescript和Angular2中的下拉列表值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题被问了很多遍,对我的问题无济于事.不确定该方法有什么问题,并希望有一些新鲜的眼睛"

This question was asked many times and couldn't help me with my problem. Not sure whats wrong with the approach and hope some fresh "eyes"

这是我在HTML中的下拉列表绑定:我正在绑定programName,它是一个同时包含值和文本属性的字符串.

Here is my dropdownlist binding in HTML: I am binding programName which is a string to both value and text properties.

<select [ngModel]="selectedObject">
   <option *ngFor="let p of programs" value= {{p.programName}}>
         {{p.programName}}
   </option>
</select>

在我的.ts文件中,这是将默认值绑定到选择"的操作

In my .ts file, here is the what i am doing to bind the default value to the "select"

 loadData(pList: IProgram[]) {
    this.programs = pList;
    if (this.programs.length > 0) {
        this.selectedObject = this.programs[0];
    }
}

数据绑定到选择"

  • 但是默认值显示为空文本,我需要单击并选择一个值.
  • 另一个问题是,当我将下拉列表的值从A更改为B时,"selectedObject"值始终为我提供"A"而不是"B".由于它是[ngModel],因此需要进行两种方式的绑定.但是,它没有发生,因为我可能在这里错过了一些东西.

有人可以用这种方法解决什么问题吗?

Can someone help whats the problem with this approach?

推荐答案

请尝试以下

<select [(ngModel)]="selectedObject">
   <option *ngFor="let p of programs" 
           [ngValue] = "p"
           [selected]="p.programName == selectedObject.programName"
          >
         {{p.programName}}
   </option>
</select>

检查此柱塞!

希望这会有所帮助!

这篇关于绑定并获取Typescript和Angular2中的下拉列表值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆