DEV Community

Shrihari Mohan
Shrihari Mohan

Posted on

Don't use js functions to format your text on HTML in Angular. Instead use this Pipe.

Consider this basic example of a component with a function called getModifiedText() and our template with interpolation

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent {
  title = 'dummy-angular-app';

  constructor() { }

  getModifiedText(text: string) {
    console.log("🚀 ~ getModifiedText")
    return text.toUpperCase()
  }
}
Enter fullscreen mode Exit fullscreen mode
<p> {{ getModifiedText('😯 JS Functions') }} </p>
Enter fullscreen mode Exit fullscreen mode

Can you guess the output in the console ?
Hint : There is a console.log inside getModifiedText()

Even though we're calling the function only one time in template , if we see the console we will be getting more than one time. ( 4 times )

Console log getModifiedText

The function getModifiedText() will be called every time Angular runs change detection for the component.

This is because updating DOM is part of change detection and Angular needs to call getModifiedText() to know what value to use for DOM update.

And change detection cycle can run quite often. Learn more about change detection

But this additional usage of JS may cost us processing power when the app grows siginificantly larger.

Hence comes the role of Angular Pipes.

Creating a angular pipe called capitalize ( make sure you are inside your angular app )

ng generate pipe capitalize
Enter fullscreen mode Exit fullscreen mode

If you are using lazy loading or other modules , Make sure to put a entry in your corresponding module.ts declarations

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

@Pipe({
  name: 'capitalize'
})

export class CapitalizePipe implements PipeTransform {

  transform(text: string): string {
    console.log("🚀 ~ CapitalizePipe")
    return text.toUpperCase()
  }

}
Enter fullscreen mode Exit fullscreen mode

Now in our template

<p> {{ '😌 Angular Pipe' | capitalize }}</p>
Enter fullscreen mode Exit fullscreen mode

There is a console in our pipe and when we open our console we just see only one log.

Pipe Console log

If its a text formatting always use Angular Pipes to reduce javascript usage. More on Angular Pipes


And If you like these type of small articles , Don't forget to follow me @shrihari , It motivates to write more and contribute open source.

🕊 Peace !

More Free articles from me !

Discussion (0)