Search code examples
angularpipeuppercase

Angular pipe toLocaleUpperCase


It's my pipe:

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

@Pipe({
  name: 'transformFullName'
})
export class TransformFullNamePipe implements PipeTransform {

  transform(value: string, ...args: unknown[]): string {
    let fullName: string[] = value.split(' ');
    fullName[0].charAt(0).toLocaleUpperCase();
    fullName[1].charAt(0).toLocaleUpperCase();
    console.log(fullName);
    if (fullName[0].length + fullName[1].length > 41) {
      return fullName[0].charAt(0) + '. ' + fullName[1].charAt(0) + '.';
    }
    return fullName[0] + ' ' + fullName[1];
  }

}

I get on consoles:

(2) ["male", "male"]
0: "male"
1: "male"
length: 2
__proto__: Array(0)

and one error: core.js:6157 ERROR TypeError: Cannot read property 'charAt' of undefined at TransformFullNamePipe.transform (transform-full-name.pipe.ts:11). Why?


Solution

  • There is pipe in Angular - titlecase:

    {{'tHIs is mIXeD CaSe' | titlecase}}
    <!-- output is expected to be "This Is Mixed Case" -->
    

    https://angular.io/api/common/TitleCasePipe

    I think this is what you tried to do:

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
      name: 'transformFullName'
    })
    export class TransformFullNamePipe implements PipeTransform {
    
      transform(value: string): string {
        const fullName: string[] = value.trim().split(' ');
        fullName[0] = fullName[0].charAt(0).toLocaleUpperCase();
        fullName[1] = fullName[1].charAt(0).toLocaleUpperCase();
        console.log(fullName);
        if (fullName[0].length + fullName[1].length > 41) {
          return fullName[0].charAt(0) + '. ' + fullName[1].charAt(0) + '.';
        }
        return fullName[0] + ' ' + fullName[1];
      }
    
    }