Capitalization of First Letter in Angular with a Custom Filter (And JavaScript generally too).

Capitalization of First Letter in Angular with a Custom Filter (And JavaScript generally too).
Capitalization of First Letter in Angular with a Custom Filter (And JavaScript generally too).

Capital not Capitol.

Angular has some great built in filters, but one case that comes up the Angular doesn’t handle automatically capitalizing the first letter in a string. (Skip to the bottom to get the code snippet if you don’t care about my babbling)

For capitalizing the first letter, but leaving the rest of the string the same, we’ll use the substring, toLowerCase and toUpperCase methods.

I’m assuming you have a module set up, I’m using the app convention.

The regular JavaScript for capitalizing goes like this:

Notice the substring method treats the string as an array, the first argument in the substring is the index (or start position) and starts counting at zero. The second argument in substring is optional, and tells how many letters/characters you want to count through and send forward into the next method or return.

Notice the filter method on app (our module), the first argument is the name and the second is the function. Within, we’re returning another function which takes the input (the value from the template) with the capitalized first letter. Also note, I’ve added in a conditional, dependent on input being defined. That way if there’s no value there it won’t produce an error. In the template we’d include something like this {{ value | firstUpper }}

Written By StevenLacks