Angular中的标题案例在撇号后没有大写

时间:2017-11-09 15:21:34

标签: javascript angular

默认的Angular Titlecase管道会在撇号后大写单词。怎么解决这个问题?如何有选择地不把一些词大写?

2 个答案:

答案 0 :(得分:2)

这是一个需要处理的自定义管道。

native_arg

答案 1 :(得分:2)

这是类似的内容,也可以从组件动态接受介词

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
    name: 'customTitleCase'
})
export class CustomTitleCase implements PipeTransform{
    except:string[] = []; 
    transform(value: string, ...except: string[]){ // accepts any number of arguments
        this.except = [...except];
        console.log(this.except);
        if(!value) return null;

        let words = value.split(" ");
        for (var index = 0; index < words.length; index++) {
        var word = words[index];
        if (index > 0 && this.isPreposition(word)) {
            words[index] = word.toLowerCase();
        }
        else {
            words[index] = this.toTitleCase(word);
        }
        }

        return words.join(" ");
    }
    private isPreposition = (word: string):boolean => {
        let lowerCaseWords  = [...this.except];   
        console.log(lowerCaseWords); 
        return lowerCaseWords.includes(word.toLowerCase());
    }

    private toTitleCase = (word: string):string => 
         word.substr(0, 1).toUpperCase() + word.substr(1).toLowerCase();

}

   @Component({
    selector: 'inputTitleCase',
    template: `
            <input [(ngModel)] = "text"/>
            <h4>{{text | customTitleCase:'of':'the' }}</h4> <!--only strings to be passed  -->
        `
})

export class inputTitleCase {
    text = "";
}

This is how the result looks like