Disclaimer: I am a consultant at Amazon Web Services, and this is my personal blog. The opinions expressed here are solely mine and do not reflect the views of Amazon Web Services (AWS). Any statements made should not be considered official endorsements or statements by AWS.
To capitalize the first letter of the input textbox, we can create a custom directive in the Angular application.
The directive which we are going to create is an Attribute Directive because we are manipulating only the behavior of the DOM element. There is one more type of directive which manipulates the DOM (add or remove DOM elements) known as a Structural Directive.
In this example, I have created a custom directive TitleCaseDirective
.
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appTitleCase]'
})
export class TitleCaseDirective {
constructor(private el: ElementRef) {
}
@HostListener('blur') onBlur() {
if (this.el.nativeElement.value) {
const arr: string[] = this.el.nativeElement.value.split('');
arr[0] = arr[0].toUpperCase();
this.el.nativeElement.value = arr.join('');
}
}
}
<input appTitleCase type="text" class="form-control" />
This custom directive will now turn the first letter to uppercase once the user loses focus from the input.