Home > Software design >  How to create a comma seperated list from multiple items in angular?
How to create a comma seperated list from multiple items in angular?

Time:09-23

At my angular application, I'm trying to create a comma separated list of values I've got from my API response.

The API response looks like this:

    {
       "release_date":"2012-03-14",
       "some_relation":[
          {
             "id":"2604ebbf-4eb5-46e3-89d8-ab4e8ecc8275",
             "name":"ABC"
          },
          {
             "id":"5267a0c6-9423-4e28-a413-133cc3435612",
             "name":"DEF"
          },
          {
             "id":"13d1454a-fc0e-457c-9f8e-9a9952984d8c",
             "name":"GHI"
          }
       ],
    }

some_relation in nested, so I created an interface for this logic to work:

    export interface SomeResponse {
        some_relation: some[];
    }

    export interface some {
      id: string;
      name: string;
    }

At my html template, I now do this:

      <div *ngFor="let some of some_response.some_relation">
        <small>{{ some.name }}</small>
      </div>

Which returns the following output:

ABC

DEF

GHI

Instead of multiple lines outputted, I would like to have it that way:

ABC, DEF, GHI

How can this be accomplished?

Thanks in advance.

CodePudding user response:

You can do it like this:

  • Change div for span so it would not put each item in new line
  • Add , only if it's not the last item
<span *ngFor="let item of some_response.some_relation; let last = last">
  <small>{{ item.name }}</small><span *ngIf="!last">, </span>
</span>

CodePudding user response:

That's because you are using *ngFor on division tag instead of small tag and it is creating 3 division with a small tag in each division. Division is a block element and each division is rendered on the next line. Try doing something like this for single line rendering:

<small *ngFor="let some of some_response.some_relation" >
{{ some.name }} 
</small>

Edit: Since you want the comma in between you can use this:

<small> 
{{ some_response.some_relation.reduce((total, obj, index) => index? total   ", "   obj.name: obj.name, "") }} 
</small>
  • Related