CristiKL
CristiKL

Reputation: 5

Directive to title case fields in Angular

I want to use a directive to transform all table column data to titlecase. To achieve that, I create this custom directive.Pipes are not counted:

@Directive({
selector: '[appTitleCase]'
})
export class TitleCaseDirective implements OnInit {
    @Input() titleCaseInput:string

  constructor(private el: ElementRef) {
  }

  ngOnInit() {

  }

   toTitleCase(input) {
    return input.replace(/\w\S*/g, (txt => txt[0].toUpperCase() + txt.substr(1).toLowerCase()));
   }
}

And HTML:

<td appTitleCase>PENDING</td>

Upvotes: 0

Views: 908

Answers (1)

Nkubito Pacis
Nkubito Pacis

Reputation: 81

You can use this

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

@Pipe({
  name: 'titleCasing'
})
export class TitleCasingPipe implements PipeTransform {

  transform(value: string,): any {
    if(!value)return null;

    const words = value.split(' ');
    for(let i = 0;i<words.length; i++){
      if( this.isPreposition(words[i])&& i !== 0){
        words[i] = words[i].toLowerCase();
      }
      else{
        words[i] = this.toTilteCase(words[i]);
      }
    }
    return words.join(' ');
  }
   private isPreposition(word: string) : boolean{
      const prepositions = [
        'of','the'
      ];
      return prepositions.includes(word.toLowerCase());
  }
  private toTilteCase(word: string): string{
    return word.substr(0,1).toUpperCase() + word.substr(1).toLowerCase();
  }
}

Upvotes: 1

Related Questions