firasKoubaa
firasKoubaa

Reputation: 6857

Angular : loop over object and concatinate into a string

i have this data :

"commercialRanges": [
      {
        "rangeId": "700",
        "rangeName": "POSTPAID"
      },
      {
        "rangeId": "500",
        "rangeName": "PREPAID"
      },
    ]

In my my vew i want to display the rangeNames as one continated , joined string like this : POSTPAID,PREPAID

i ve tried this :

      <div  *ngFor="let g of gammes.data.commercialRanges">
          {{g.rangeName}},
      </div>

But this resulted me such a view : (separated strings)

FIXE,
POSTPAID,

Which is wrong ,

suggestions ?

Upvotes: 0

Views: 401

Answers (4)

bmgh1985
bmgh1985

Reputation: 789

The reason for the line break is because you are using divs and not spans, as divs are not inline by default.

Instead of using a for loop, can you not just display

{{gammes.data.commercialRanges.map(range => range.rangeName).join(", ")}}

This should also mean you do not get an extra , at the end

Upvotes: 0

Teddy Sterne
Teddy Sterne

Reputation: 14201

There are a couple things you could do. You could just use the join function and display the result. Or you could display the text inline.

Join:

<div>
  {{games.data.commercialRanges.map(({rangeName}) => rangeName).join(', ')}},
</div>

Inline:

<div>
  <span *ngFor="let g of gammes.data.commercialRanges">
    {{g.rangeName}},
  </span>
</div>

Upvotes: 1

Frank Modica
Frank Modica

Reputation: 10516

You could pre-process the data in your component and just display that:

this.rangeNames = games.data.commercialRanges.map(range => range.rangeName).join(",")

<div>{{ rangeNames }}</div>

Upvotes: 3

Sandip Jaiswal
Sandip Jaiswal

Reputation: 3720

Use following code:

<span  *ngFor="let g of gammes.data.commercialRanges">
          {{g.rangeName}},
      </span>

div is block level element. So it will use a block. That's why view looks like that.

You can also also use your code like this:

<div  *ngFor="let g of gammes.data.commercialRanges" style="display: inline-block">
          {{g.rangeName}},
      </div>

Upvotes: 0

Related Questions