Does anyone know how to use titlecase in component.ts file instead in html file?

11.4k Views Asked by At

I tried the following code but it's not working.

import { Component } from '@angular/core';
import { TitleCasePipe } from '@angular/common';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  title = 'Working with Pipe';
  testValue = this.titleCasePipe.transform('firstletter should be upper case.');


  constructor(
    public titleCasePipe: TitleCasePipe
  ){}

}

enter image description here

4

There are 4 best solutions below

3
Gérôme Grignon On BEST ANSWER

Add TitleCasePipe in the providers array of the metadata of your component :

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
providers: [TitleCasePipe]
})

Stackblitz example

4
Indrajeet On

Put your code inside constructor like this,

 testValue: string;


 constructor(
    public titleCasePipe: TitleCasePipe
 ){
    this.testValue = this.titleCasePipe.transform('firstletter should be upper case.');
 }
2
Eliseo On

You can just create an object, else, add in providers as @Gérôms say

  title = 'Working with Pipe';
  titleCasePipe=new TitleCasePipe()
  testValue = this.titleCasePipe.transform('firstletter should be upper case.');

  constructor(){
  }
0
Kiran Mistry On

Without Pipe


Here is your Simple Solution with TitleCase

you can use directly like this you don't have to put extra code angular already give's this features

HTML

<p>
  {{name | titlecase}} <!-- this is titlecase by default -->
</p>

TS

name = 'Working with Pipe';

With Pipe

you can check in input field also like this

HTML

<input type="text" id="firstName" name="name" 
[ngModel]="name | titleCase" 
(ngModelChange)="name=$event" 
#firstName="ngModel">

TS

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({name: 'titleCase'})
export class TitleCasePipe implements PipeTransform {
    public transform(input:string): string{
        console.log(input);
        if (!input) {
            return '';
        } else {
            return input.replace(/\b\w/g, first => first.toLocaleUpperCase()) 
        }
    } 
}

and don't forgot to add in declaration like this

declarations: [ TitleCasePipe ],

Here is my stackBlitz you can check here