While typing the text it will be in lower case, but while the mouse focused out, then the first letter have to change to uppercase.
-
Can you show the tried code? – Prashant Pimpale Mar 21 '19 at 05:18
-
i'm new to angular – Unni Krishnan SJ Nair Mar 21 '19 at 05:19
-
Are you using reactive forms? Or are you using plain old template-driven forms (using ngmodel)? – wentjun Mar 21 '19 at 05:25
-
Then try it! [This](https://stackoverflow.com/a/25633198/7124761) is an onBlur event and [this](https://stackoverflow.com/a/30207330/7124761) is for AutoCaptalize Directive – Prashant Pimpale Mar 21 '19 at 05:28
1 Answers
I am assuming you are not using reactive forms. There is no need for a separate directive, as all you need to do is to handle the focus out event. Basically, you can bind the focusout
event to your input. Upon focusing out, the trigger()
method will be fired.
On your component.html,
<input class="form-control" (focusout)="trigger($event)" [(ngModel)]="sampleInput" type="text">
And on your component.ts, the trigger()
method converts the first letter to uppercase. Then, we assign the converted string to your model (sampleInput
)
sampleInput: string = undefined;
.
.
trigger(event) {
const inputValue = event.target.value;
const result = inputValue.charAt(0).toUpperCase() + inputValue.slice(1);
this.sampleInput = result;
}
However, on a not-so-related note, my personal favourite would be to handle it via pure CSS. But of course, there are limitations to this solution, as it capitalises the first letter of every word in your string (eg. 'hi john' -> 'Hi John'), instead of only the first letter of your entire string. One obvious advantage of this method is that does not mutate the underlying value of that string, as only the 'display' is affected.
input {
text-transform: capitalize;
}

- 40,384
- 10
- 95
- 107