Telerik blogs

If you want to use a pipe to change the way your text displays, try out UpperCasePipe for all caps or create your own. Here are some examples.

To make building web apps easier, we often use pre-built components to build the frontend of our Angular app.

Oftentimes, we want to capitalize the text that is displayed on the screen. In this article, we will look at ways to capitalize text displayed on the screen with pipes.

What are Pipes?

Pipes in Angular are functions that transform values into a preferred format. We put them in template expressions to easily return text displayed in the format we want. The value that is transformed is not changed by pipes.

Pipes are applied by putting them after the expression and the pipe (|) symbol.

Angular comes with some built-in pipes. They include:

  • DatePipe - Formats a date value according to locale rules.
  • UpperCasePipe - Transforms text to all uppercase.
  • LowerCasePipe - Transforms text to all lowercase.
  • CurrencyPipe - Transforms a number to a currency string, formatted according to locale rules.
  • DecimalPipe - Transforms a number into a string with a decimal point, formatted according to locale rules.
  • PercentPipe - Transforms a number to a percentage string, formatted according to locale rules.

Therefore, to capitalize text with the built-in pipe, we can use the UpperCasePipe to format text we want into an all uppercase string.

For instance, we write:

app.component.ts

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

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  title = "hello world";
}

to add the title string.

app.component.html

{{ title | uppercase }}

Then we display the text as uppercase by using uppercase after the pipe symbol to render title as all uppercase text with the UpperCasePipe.

If we want to capitalize text any other way, then we have to make our own pipe.

Create Custom Pipe to Capitalize Text

To customize how text is capitalized in our Angular component templates, we can create our own pipe. We can create a new pipe easily and register it in our Angular app with the Angular CLI.

Assuming our Angular project is created with the Angular CLI, we can use the ng generate command to create a new pipe. We run ng generate pipe with the name of our pipe to create a new pipe.

For instance, we run:

ng generate pipe capitalize

to create the capitalize pipe and register it in the app module.

We can shorten the command to:

ng g pipe capitalize

As a result, we should see some new code get added.

In app.module.ts, we see something like:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CapitalizePipe } from './capitalize.pipe';

@NgModule({
  declarations: [
    AppComponent,
    CapitalizePipe
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

We see the CapitalizePipe added to the declarations array. This means the CapitalizePipe is registered in the AppModule.

We should also see capitalize.pipe.ts created. It should have something like the following:

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

@Pipe({
  name: 'capitalize'
})
export class CapitalizePipe implements PipeTransform {

  transform(value: unknown, ...args: unknown[]): unknown {
    return null;
  }

}

The pipe itself is a class that implements the PipeTransform interface. This requires us to add the transform function to the class which takes an unlimited number of arguments and returns some value.

The name property is set to a string with the name we use in the template to apply the pipe.

We change value's type to string since we want to transform strings. And we make the transform function’s return type to string.

For instance, if we want to capitalize the first letter of each word in a sentence, we write:

capitalize.pipe.ts

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

@Pipe({
  name: 'capitalize',
})
export class CapitalizePipe implements PipeTransform {
  transform(value: string, ...args: unknown[]): string {
    const splitString = value
      .split(' ')
      .map((s) => `${s[0].toUpperCase()}${s.slice(1)}`);
    return splitString.join(' ');
  }
}

In the transform function, we get the value string and split it by the spaces with split into a string array.

Then we call map with a function that capitalizes the first letter of each word with s[0].toUpperCase().

And then we combine that with the rest of the string which is returned by s.slice(1).

Then we call join with a space string to return a string that combines the words back into a sentence string with the first letter of each word capitalized.

Next, in the component, we write:

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  title = 'The quick brown fox jumps over the lazy dog';
}

to add the title string to AppComponent.

Then we write:

app.component.html

{{ title | capitalize }}

to apply the capitalize pipe.

It’ll call the transform method in the CapitalizePipe to return the string with the first letter of each word capitalized.

Therefore, we should see The Quick Brown Fox Jumps Over The Lazy Dog displayed on the screen.

We can expand the CapitalizePipe so we can capitalize strings in different ways.

For instance, we write:

capitalize.pipe.ts

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

@Pipe({
  name: 'capitalize',
})
export class CapitalizePipe implements PipeTransform {
  transform(
    value: string,
    capitalizationMethod: 'allUpperCase' | 'titleCase' | 'sentenceCase'
  ): string {
    if (capitalizationMethod === 'allUpperCase') {
      return value.toUpperCase();
    } else if (capitalizationMethod === 'titleCase') {
      const splitString = value
        .split(' ')
        .map((s) => `${s[0].toUpperCase()}${s.slice(1)}`);
      return splitString.join(' ');
    } else if (capitalizationMethod === 'sentenceCase') {
      const splitString = value.split('.').map((s) => {
        const trimmedString = s.trim();
        if (trimmedString.length > 0) {
          return `${trimmedString[0].toUpperCase()}${trimmedString.slice(1)}`;
        }
        return '';
      });
      return splitString.join('. ');
    }
    return '';
  }
}

to add a capitalizationMethod parameter to let us choose how to capitalize our text.

We give three choices for this argument. And for each choice we return the string that corresponds to the argument’s value.

Therefore, if capitalizationMethod is 'allUpperCase' we return the value string transformed to all uppercase.

If it’s 'titleCase', then we return a string with each word’s first letter converted to uppercase.

And if it’s 'sentenceCase', we only capitalize the first letter of each sentence by splitting the string by the period.

Then we call map with a function to return a string without the starting and ending whitespaces with trim.

Next we transform each sentence by returning a string with the first letter uppercase and the rest the same as before by returning ${trimmedString[0].toUpperCase()}${trimmedString.slice(1)} if the string has a length longer than 0 and an empty string otherwise.

Then we combine that back into a sentence with join.

After this, in our component, we write:

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  title =
    'The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.';
}

to add the title string.

Then we use the capitalize with the arguments we accept by writing:

app.component.html

<p>{{ title | capitalize : "allUpperCase" }}</p>
<p>{{ title | capitalize : "titleCase" }}</p>
<p>{{ title | capitalize : "sentenceCase" }}</p>

The capitalizationMethod argument is the string after the colon.

Therefore, we see:

THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG. THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.

The Quick Brown Fox Jumps Over The Lazy Dog. The Quick Brown Fox Jumps Over The Lazy Dog.

The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.

displayed on the screen.

Conclusion

Angular provides us with an organized way of building frontend web apps, including several pre-built components.

One such tool is the UpperCasePipe, which will render text in all uppercase.

We can also create our own pipe to capitalize text the way we want to render text capitalized. I showed you some examples of this.


About the Author

John Au-Yeung

John Au-Yeung is a frontend developer with 6+ years of experience. He is an avid blogger (visit his site at https://thewebdev.info/) and the author of Vue.js 3 By Example.

Related Posts

Comments

Comments are disabled in preview mode.