0

I have a dropdown which binds data from database

<select (ngModelChange)="load($event)">
 <option *ngFor="let type of types" [ngValue]="type">{{type.Name}}</option>
</select>

On another button click (not the dropdown change event) I get the type.Id which should be bound to this select, show the selected name and hold it for further use. How can I do that.

2 Answers 2

1

You should be using two way binding with ngModel

<select [(ngModel)]="selectedElement">
 <option *ngFor="let type of types" [ngValue]="type.id">{{type.Name}}</option>
</select>
{{selectedElement |json}}

Onclick of the button you access the selected id using

this.selectedElement.id

Update 1 : If you are looking to change the selected value based on the service response, use the below code,

HTML {{type.Name}}

Component

types:any[]=[
                {id:1,Name:'abc'},
                {id:2,Name:'abdfsdgsc'}
    ];
  /*item to be preselected should be in the below object which 
  *is returned by the web  service
  */
  selectedElement:any= 2;

Updated LIVE DEMO

Sign up to request clarification or add additional context in comments.

15 Comments

I want to do the opposite. On button click, I want the dropdown to bind to the id which is returned from database
where does the data comes to the dropdown, then?
It comes from a separate query on ngOnInit. There is nothing selected initially. After another button click, I need to select the value which maps to the dropdown list values. I hope I am clear
I want to do something like this in angular: dropdown.SelectedValue = reader[0].ToString();(this is in C#)
did u see the demo which is in the answer?
|
0

You could do something like this:

Set the selected if it matches the number you receive:

<select >
  <option value="select" disabled>--Select--</option>
  <option *ngFor="let type of types" [selected]="type.id == id" [ngValue]="type">{{type.name}}</option>
</select>

And when you receive your number, you set that value to id (or whatever variable you want). Here's a

Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.