DragonBorn
DragonBorn

Reputation: 1809

Using ngFor in Array

I have data showing up in my console as this. I want to show them in a dropdown.

["Hello", "Hello"]
0:"Hello"
1:"Hello"
length:2
__proto__:Array(0)

This is what I tried:

<select>
  <option *ngFor="let x of greeting" [value]="x">{{x}}<option>
</select>

But nothing is showing up.

And when I use it this way:

<select>
  <option>{{greeting}}<option>
</select>

It shows up as one single item in the dropdown as Hello,Hello

UPDATE: Actual Response

{
status: 200,
message: "Rooms are available",
available: "yes",
remaining_room: 10,
price: "[1800,1200]",
extra_person_price: "["500","200"]",
extra_child_price: "["500","100"]",
plan_type: "["EP","PT"]",
plan_name: "["Summer Plan","Winter Plan"]",
}

Response from Network Tab

{status: 200, message: "Rooms are available", available: "yes", remaining_room: 10,…}
available
:
"yes"
extra_child_price
:
"["500","100"]"
extra_person_price
:
"["500","200"]"
message
:
"Rooms are available"
plan_name
:
"["Summer Plan","Costume Plan"]"
plan_type
:
"["CP","others"]"
price
:
"[1800,1200]"
remaining_room
:
10
status
:
200

Upvotes: 1

Views: 373

Answers (1)

AVJT82
AVJT82

Reputation: 73337

As per our discussion you tried to iterate the wrong variable (which was still a string), so:

This works: Since you have mixed data in your response, from which you need to parse some of, so in your subscribe you could create an object, where you then parse the parts you need, here's just the partial data:

getData() {
  this.service.getData()
    .subscribe(data => {
      // assign values to obj, and parse the ones you need to parse:
      this.obj = {"remaining_room":data.remaining_room, "price":JSON.parse(data.price)}
    })
}

Then you can refer to the object in your select:

<select>
  <option *ngFor="let price of obj?.price">{{price}}</option>
</select>

Here's a Plunker with the above code.

Upvotes: 2

Related Questions