PAR
PAR

Reputation: 441

Angular 2:How to bind GET service response data to the dropdown

Clientlist.service.ts

     getClientList()
   { 
     let headers = new Headers();
     headers.append('Content-Type', 'application/json');
     let authToken = localStorage.getItem('auth_token');
     console.log(authToken);
     headers.append('X-auth-Token', authToken)
      return this._http.get('http://localhost:8080/api/v1/client/list?isClient=Y', {headers})
      .map((res) => {
      var clientList = res;
      console.log(clientList);
    })
  }

response:

[{"userId":"mind.com","clientCode":"75","clientName":"ABC COMPANY, THE"},{"userId":"mind.com","clientCode":"51","clientName":"infotech"}]

Here i am getting a list of clients in clientList,Now how can i bind this response to the dropdown in angular 2.please help me.

Upvotes: 2

Views: 9648

Answers (2)

Dnyaneshwar
Dnyaneshwar

Reputation: 158

You can simply use it like

<select [(ngModel)]="client.clientCode">
      <option value="" disabled selected>Select Client Name</option> 
      <option *ngFor="let user of ClientList" [value]="user.clientCode">{{user.clientName}}</option>
</select>

Upvotes: 1

Smit
Smit

Reputation: 2148

You need to create object of the following client object, it becomes easier to parse and display on the dropdown list.

Below is the model for the client:

export class Client
{
userId: string;
clientCode: string;
clientName: string;
}

Once you have created the object, in your component.ts:

clients: Client[];
currentSelection: Client;

ngOnInit()
{
//... do your calls do get res(client list)
var clientList = res;
this.clients = JSON.parse(clientList);
}
onChange(value: Client)
{
this.currentSelection = value;
}

Then after do the following in ur html code:

<select (change)="onChange($event.target.value)">
    <option *ngFor="let client of clients">{{client.clientName}}</option>
</select>

Upvotes: 1

Related Questions