How can we make a string title case in Angular.
TL; D(WT)R;
Too long; Don't want to read;
We can use the angular TitleCasePipe in the following manner,
<!-- For Text -->
<button>{{ label | titlecase }}</button>
<!-- For Properties -->
<button [attr.aria-label]="label | titlecase">X</button>
<!-- For Attributes -->
<button aria-label="{{ label | titlecase }}">X</button>
The TitleCasePipe is exported from @angular/common so we do not need to import it separately.
Javascript has no predefined functions to change a string into a title case string. We have methods like toUpperCase() and toLowerCase() but we don't have a toTitleCase()
We could use the css text transform and have something like,
text-transform: capitalize
This would work for text, but not for attributes. For example if we wanted to set the aria-label this wouldn't work.
We could do something convoluted likem
str = "hello";
str = str[0].toUpperCase() + str.slice(1);
Or, we could create a function.
toTitleCase(str) {
return str[0].toUpperCase() + str.slice(1);
}
And use that in the template.
<button aria-label="toTitleCase(label)">X</button>
These would have been our only options if angular didn't provide us with the TitleCasePipe. With this pipe we can make our code cleaner and use more of angular.
<button>{{ label | titlecase }}</button>
Or we can use the in an attribute,
<button aria-label="{{ label | titlecase }}">X</button>