How to Concatenate Pipe Value in Angular with a String
In Angular, pipes are powerful tools that allow us to transform data within templates. Common examples include converting numbers to currency or formatting dates. In this article, we will learn how to concatenate a pipe-transformed value within a string using Angular.
Let’s walk through the steps with a practical example.
Step 1: Initialize the Angular Project
To get started, create a new Angular project using the following commands:
ng new angular-project
cd angular-project
This will create the Angular project and navigate into it.
Project Dependencies:
Here’s what the package.json dependencies look like in the Angular project:
"dependencies": {
"@angular/animations": "^18.0.0",
"@angular/common": "^18.0.0",
"@angular/compiler": "^18.0.0",
"@angular/core": "^18.0.0",
"@angular/forms": "^18.0.0",
"@angular/platform-browser": "^18.0.0",
"@angular/platform-browser-dynamic": "^18.0.0",
"@angular/router": "^18.0.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}
Step 2: Modify app.component.ts to Include a Date Value
In this step, we’ll add a new variable, currentDate, which will store the current date. We’ll use this variable to demonstrate how to format and concatenate it within a string in the template.
Code for app.component.ts:
import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet, CommonModule],
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
title = 'angular-project';
// Store current date
currentDate = new Date();
}
currentDate: This variable holds the current date which will be formatted in the next step.
Step 3: Use the Date in the Template
Now, let’s use the currentDate variable in the template, format it using the date pipe, and concatenate it with a string.
Code for app.component.html:
<p>{{ "The formatted date is: " + (currentDate | date : "longDate") }}</p>
Describe:
The string “The formatted date is: ” is concatenated with the currentDate value.
The date pipe is used to format the currentDate into a long date format (“longDate”).
Step 4: Run the Application
To see the output, start the application by running the following command:
ng serve
Output:
When you run the app, it will display something like:
The formatted date is: September 15, 2024
This tutorial shows how easy it is to concatenate pipe-transformed values with strings in Angular. By using the | pipe symbol, you can format data directly in your templates while keeping your code clean and efficient.
Keep Learning 🙂