从Angular 2中的选定下拉列表中获取价值 [英] Get value from selected dropdown list in Angular 2

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

问题描述

我有一个具有两个属性(Name_of_Game和Type_of_Game)的数据库表.我曾经将 Name_of_Game 提取到选择下拉列表中.但是,这就是我现在想做的.从下拉列表中选择游戏后,如何将类型输入自动设置为游戏的各自类型?

I have a database table with two attributes (Name_of_Game and Type_of_Game). I have been to extract the Name_of_Game into a select dropdown list. But this is what i want to do now. After selecting the game from the dropdown list, how can the type input be set to the game's respective type automatically?

示例

游戏
指环王

Game
Lord of the Rings

类型

冒险

从下拉列表中选择指环王"后,类型输入框应自动设置为冒险".

After selecting Lord of the rings from the dropdown list, the type input box should be automatically set to Adventure.

    //Component 

    export class ChatComponent{

         Game : Games [];
         constructor(private http:HttpService){

         // list all games into the dropdown list
            this.http.listgames()
            .subscribe(data => {

                this.Games = data;
    })

    }

   //html

            <div class="form-group">
            <select class="form-control" name="game"  [(ngModel)]="game.name" required>
                <option *ngFor="let games of Games" [ngValue]="games" > {{games.name}} </option>


            </select>
            </div>
    <div class="form-group">
                <label for="type">Type:</label>
                <input type="type" class="form-control" name="type"   [(ngModel)]="game.type">
            </div>

推荐答案

请查看命名约定,我在示例中对名称进行了一些更改,以更好地反映我们通常使用的小写/大写形式;)

Please look at the naming convention, I have changed names in my example a bit, to more reflect the lower/uppercase we usually use ;)

您在使用[ngValue]的正确轨道上.让您的名字绑定整个对象,然后我们可以在类型中使用它来显示相应的类型.因此,让我们创建一个变量,当用户从下拉列表中选择一个名称时,将存储所选游戏的变量命名为selectedGame:

You are on the right track for using [ngValue]. Have your name bind the whole object, which we can then use in the type, to show the corresponding type. So let's create a variable to which we will store the chosen game when user chooses a name from the drop down list here let's call it selectedGame:

组件:

selectedGame: Object = {};

模板:

<select [(ngModel)]="selectedGame" required>
  <option *ngFor="let game of games" [ngValue]="game">{{game.name}}</option>
</select>

现在我们已将整个对象绑定到selectedGame,因此输入字段将反映出我们进行了更改,因为我们将selectedGame.type用作输入字段的两种方式绑定.因此您的模板如下所示:

Now we have bound the whole object to selectedGame, so the input field will reflect that we make a change, as we use selectedGame.type as two way-binding for the input field. So your template would look like this:

<label>Name:</label>
<select [(ngModel)]="selectedGame" required>
   <option *ngFor="let game of games" [ngValue]="game" > {{game.name}} </option>
</select>
<label>Type:</label>
<input type="type"name="type" [(ngModel)]="selectedGame.type">

这里是

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

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