Angular 管道 toLocaleUpperCase

Angular pipe toLocaleUpperCase

这是我的烟斗:

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];
  }

}

我上游戏机了:

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

和一个错误:core.js:6157 ERROR TypeError: Cannot read 属性 'charAt' of undefined 在 TransformFullNamePipe.transform(转换完整-name.pipe.ts:11)。为什么?

Angular中有管道 - titlecase:

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

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

我想这就是你想做的:

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];
  }

}

您没有将值分配给 fullName[0]fullName[1]。 你应该这样做:

fullName[0] = fullName[0].charAt(0).toLocaleUpperCase();
fullName[1] = fullName[1].charAt(0).toLocaleUpperCase();

这是一个例子: https://stackblitz.com/edit/angular-custom-pipes-slnu4k?file=app/exponential-strength.pipes.ts