Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value from selected dropdown list in Angular 2

Tags:

angular

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?

Example

Game
Lord of the Rings

Type

Adventure

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>
like image 207
XamarinDevil Avatar asked Dec 03 '22 13:12

XamarinDevil


1 Answers

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

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:

Component:

selectedGame: Object = {};

Template:

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

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">

Here's a

Demo

like image 65
AT82 Avatar answered Dec 23 '22 03:12

AT82