Open In App

How to make input appear as sentence case based on typing using Angular 8 ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this example, we will see how to make input appear sentence case based on typing using angular8.

Approach:

  • First, we need to write code for the input type in the HTML file.
  • After writing the input type as text in HTML, using two-way binding i.e., using ngModel we can bind the value of the input field.
  • Now in order to make the input field sentence case, we can use the ngModelChange event to manipulate the value according to the requirement.
  • Make sure you are importing ‘FormsModule’ from ‘@angular/forms’.
  • After importing the module now we need to implement the function in the ts file where we can modify the input value using regex according to the requirement like sentence case and can display in the input field.
  • Once the above steps are done, start, or serve the project to run.

Code Implementation:

app.component.ts:

Javascript




import { Component } from '@angular/core';
  
@Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    inputvalue = ''
  
    changeToSentenceCase(event) {
  
        this.inputvalue = event.replace(/\b\w/g, 
            event => event.toLocaleUpperCase());
  
    }
}


app.component.html:

HTML




<p>Type in textbox to make as sentence case.</p>
  
<input type='text' [(ngModel)]="inputvalue" 
    (ngModelChange)="changeToSentenceCase($event)">


app.module.ts:

Javascript




import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
  
@NgModule({
    imports: [BrowserModule, FormsModule],
    declarations: [AppComponent],
    bootstrap: [AppComponent]
})
  
export class AppModule { }


Output:



Last Updated : 17 Dec, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads