Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Comma separated KeyValue Pipe in Angular

In Angular 12, I am using a keyvalue pipe to loop through an object. I want to add a comma at the end of each value, if there is more than one and not add it to the last one. This code seems to add it to the last one too. How do I fix it?

results: {
  "Status": "Disabled",
  "Preference": "Enabled",
  "Security": "Enabled",
  "Profile": "Disabled"
}

<div *ngFor="let item of results | keyvalue; index as i">
  {{item.key}}:&nbsp;{{item.value}}
  <span *ngIf="i != item.length-1">,&nbsp;</span>
</div>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Instead of index you can you the last variable of *ngFor directive. Your code should look like this then:

<div *ngFor="let item of results | keyvalue; last as isLast">
  {{item.key}}:&nbsp;{{item.value}}
  <span *ngIf="!isLast">,&nbsp;</span>
</div>

There are also a bunch of other variables too:

index
first
last
even
odd

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading