Angular中标题大小写字段的指令



我想使用一个指令将所有表列数据转换为标题大小写。为了实现这一点,我创建了这个自定义指令。管道未计数:

@Directive({
selector: '[appTitleCase]'
})
export class TitleCaseDirective implements OnInit {
@Input() titleCaseInput:string
constructor(private el: ElementRef) {
}
ngOnInit() {
}
toTitleCase(input) {
return input.replace(/wS*/g, (txt => txt[0].toUpperCase() + txt.substr(1).toLowerCase()));
}
}

和HTML:

<td appTitleCase>PENDING</td>
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();
}
}

最新更新