Angular 2 camel case or title case or proper case conversion

If you are a front end developer then I’m sure that you might’ve seen at least once that the text you get from back-end APIs is not appropriate to show as is in the UI. Possible cases are that text is in capital letters or small letters or combination of both.

In such situations, we might need to convert it to different case before rendering it in the UI. There are plenty of options to manipulate text in the UI either with vanilla JavaScript, Jquery, Angular framework (I’m positive that other frameworks will provide such a method as well) or even using CSS style property.

Angular 2 offers these transformations through pipes feature. There are many default pipe implementations comes with angular framework to transform text to different cases like lower, upper and title case etc. Angular provides a default pipe titleCase. which can be used for title case/proper case transformations.

Usage:

<p> {{ 'Text to be transformed' | titleCase }} </p>
<!-- <p> Text To Be Transformed <p> -->

If you want to transform text from a variable

import {Component} from 'angular2/core';
@Component({
    selector: 'my-app',
    template: `
    <h1>Inline template</h1>
    <p> {{ textVar | titleCase}}</p> 
    `
})
export class AppComponent {
 const textVar = 'Text to be transformed';
}

If you want to transform a field from a list of objects. For ex. If your api returns unknown number of Person objects and you want person.name field to be shown in titleCase then

class Person {
  name: string;
  email: string;
  rating: number;
}

Component

@Component({
    selector: 'my-app',
    template: `
    <h1>Inline template</h1>

    <ul>
        <!-- without transformation -->
       <li *ngFor="let person of personList">{{ person.name }}</li>
    </ul> 

    <ul>
       <!-- With transformation -->
       <li *ngFor="let person of personList">{{ person.name | titleCase }}</li>
    </ul> 

    `
})
export class AppComponent implements OnInit {

private personList: Person[] = [];
 
 ngOnInit() {
   this.personList = // API call to fetch Persons List   
  }
}

That is it, Hope you enjoyed the article.

Please comment and share if you think this will help someone.