How to Create Truncate Pipe in Angular?

Introduction

In this article, we will learn how to create a truncate pipe in an Angular application. Using the truncate pipe, we limit the displayed text to a given length.

Prerequisites

  • Basic Knowledge of Angular 2 or higher
  • Visual Studio Code
  • Node and NPM installed
  • Bootstrap (Optional)

Create an Angular project by using the following command.

ng new angapp

Now install Bootstrap by using the following command.

npm install bootstrap --save

Now open the styles.css file and add the Bootstrap file reference. To add a reference in the styles.css file, add this line.

@import '~bootstrap/dist/css/bootstrap.min.css';

Create a Truncate Filter Pipe

Now, create a custom pipe by using the following command.

ng generate pipe truncate

Now open the truncate.pipe.ts file and add the following code.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'truncate' })
export class TruncatePipe implements PipeTransform {
  transform(value: string, limit: number): string {
    return value.length < limit
      ? value
      : value.slice(0, limit) + '...';
  }
}

Now, import this pipe into the app module. Add the following code in app.module.ts.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { TruncatePipe } from './truncate.pipe';
import { TruncateappComponent } from './truncateapp/truncateapp.component';
@NgModule({
  declarations: [
    AppComponent,TruncatePipe, TruncateappComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now, create a new component by using the following command.

ng g c truncateapp

Now open the truncateapp.component.html file and add the following code.

<div class="container">
    <div>
        <p>{{ values | truncate: 5 }}</p>
    </div>
</div>

Now open the truncateapp.component.ts file and add the following code.

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-truncateapp',
  templateUrl: './truncateapp.component.html',
  styleUrls: ['./truncateapp.component.css']
})
export class TruncateappComponent  implements OnInit{
  values:any ;
  constructor() {
  }
  ngOnInit(): void {
    this.values="How to create Custom File Size Pipe in Angular";
  }
 
}

Now open the app.component.html file and add the following code.

<div class="container" style="margin-top:10px;margin-bottom: 24px;">
  <div class="col-sm-12 btn btn-info">
    How to Create Truncate Pipe in Angular Application
  </div>
</div>
<app-truncateapp></app-truncateapp>

Now run the application using npm start and check the result.

Angular


Similar Articles