问题描述
这是我的烟斗:
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 错误类型错误:无法读取未定义的属性 'charat' 在 TransformFullNamePipe.transform (transform-full-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