An Interest In:
Web News this Week
- March 20, 2024
- March 19, 2024
- March 18, 2024
- March 17, 2024
- March 16, 2024
- March 15, 2024
- March 14, 2024
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 )
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.
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 !
Mistakes I made when I started Nodejs + MongoDb
Shrihari Mohan Jun 4 3 min read
Original Link: https://dev.to/shrihari/text-formatting-on-html-using-js-functions-vs-angular-pipe-1f8g
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To