How to get comma separated KeyValue Pipe in Angular ?
Last Updated :
24 Apr, 2025
The KeyValue Pipe is an Angular built-in feature that transforms objects or maps into an array of key-value pairs. We can use the last variable of *ngFor directive to achieve the desired result. We will compare that if the element is last then add a comma. In this article, we will learn how to get a comma-separated KeyValue Pipe in Angular.
Steps for Installing & Configuring the Angular Application
Step 1: Create an Angular application using the following command.
ng new appname
Step 2: After creating your project folder i.e. appname, move to it using the following command.
cd appname
Project Structure
It will look like the following:
Example 1: In this example, we use the last variable of *ngFor directive to achieve the desired result. We will compare that if the element is last then add a comma.
HTML
<!-- app.component.html -->
<h2 style="color: green">
GeeksforGeeks
</h2>
<h2>
How to get comma separated
KeyValue Pipe in Angular?
</h2>
<div *ngFor="let item of gfg | keyvalue; last as isLast">
<b>{{item.key}}:</b> {{item.value}}
<span *ngIf="!isLast">, </span>
</div>
JavaScript
// app.component.ts
import { Component, OnInit }
from '@angular/core';
import { KeyValue }
from '@angular/common';
import { Pipe, PipeTransform }
from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: "./app.component.html",
styleUrls: ['./app.component.css']
})
export class AppComponent {
gfg: any = {
"HTML": "Hyper Text Markup Language",
"CSS": "Cascade Style Sheet",
"XML": "Xtensive Markup Language",
"JS": "Javascript"
}
}
JavaScript
// app.module.ts
import { NgModule }
from '@angular/core';
import { BrowserModule }
from '@angular/platform-browser';
import { HttpClientModule }
from '@angular/common/http';
import { AppComponent }
from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }