0

I am trying to bind some data to a select option in Angular 6, I am using *NgFor for this: The Json data structure is as follows:

{  
   "addresses":[  
      {  
         "address":"xxxxxxx",
         "address_line1":"None",
         "address_line2":"None",
         "address_line3":"",
         "billing":false,
         "id":79,
         "name":"xxxxx",
         "phone_number":null,
         "postal_code":"xxxxx",
         "town":"xxxxx"
      },
   ]
}

So to bind this into my select option I am doing:

<option value="null" disabled="true" [selected]="true">Select your option</option>
<option *ngFor="let item of address" [value]="item">
    {{item.address}}
</option>

Ts file to get data:

customerAddress = []; 

private getCustomerAddress() {
    this.service.getCustomerAddress(this.customer_id).subscribe((data) => {
      console.log('Result - ', data);
      console.log('Customer address data is received');
      this.customerAddress = data;
    })
  }

Service linked to this:

  getCustomerAddress(customerId): Observable<any> {
    return this.http.get<any>(this.customerAddressApiUrl + "/" + customerId)
      .pipe(
        catchError(this.handleError)
      );
  }

There is no data being displayed in the select option? But data is fine in the console.log.

3
  • set value to [value]="item.id" Commented Mar 21, 2019 at 10:53
  • That did not work Commented Mar 21, 2019 at 10:54
  • Have pasted the correct code because you should loop on customerAddress Commented Mar 21, 2019 at 10:58

2 Answers 2

3

This is the correct way to do it:

<option *ngFor="let item of customerAddress.addresses" [value]="item">
    {{item.address}}
</option>
Sign up to request clarification or add additional context in comments.

5 Comments

That gives this error: Only arrays and iterables are allowed
That worked thanks, although My placeholder has disappeared now?
That did not work unfortunately, it appears for 1 sec and then goes
try <option value="" disabled selected>Select your option</option>
for non string values use [ngValue] instead of [value] as value will not work with complex objects and you will lost type in case of numeric values.
-2

The name of the array that your are browsing is customerAddress and not adresses

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.