Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 12, 2022 11:16 am GMT

Text Formatting on HTML using JS Functions vs Angular 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()  }}
<p> {{ getModifiedText(' JS Functions') }} </p>

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

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()  }}

Now in our template

<p> {{ ' Angular Pipe' | capitalize }}</p>

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 !


Original Link: https://dev.to/shrihari/text-formatting-on-html-using-js-functions-vs-angular-pipe-1f8g

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To