【问题标题】:Angular pipe toLocaleUpperCase角管道到LocaleUpperCase
【发布时间】:2021-03-14 14:57:52
【问题描述】:

这是我的烟斗:

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 property 'charAt' of undefined 在 TransformFullNamePipe.transform (transform-full-name.pipe.ts:11)。为什么?

【问题讨论】:

  • 你能创建一个stackblitz
  • 我认为错误来自没有第二名的字符串中的空格。要解决它,您可以像 value.trim().split(' '); 那样添加trim - 请参阅下面的评论
  • @Szyszka947 另外,检查 fullName 的长度。

标签: angular pipe uppercase


【解决方案1】:

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

}

【讨论】:

  • 非常感谢!我不知道这个管道:D!
【解决方案2】:

您没有将值分配给 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

【讨论】:

    猜你喜欢
    • 2018-03-09
    • 2020-07-23
    • 1970-01-01
    • 2021-02-02
    • 2017-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多