angular自定义管道省略字符

要求是中文的时候显示10个字符,英文的时候显示20个字符,不知道怎么具体实现,就想到了管道

下面是实现方法 

1.自定义实现一个管道功能,继承了方法,还处在看api的状态,具体怎么实现的还没弄清楚

 

2.transform参数的方法

首先声明管道,继承方法transform,如图所示,除了第一个是传过来的具体参数,其余都是自己随意定的参数。

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'fiterCodeLength'
})
export class FiterCodeLengthPipe implements PipeTransform {

    transform(value: any, wordwise?: any, max?: any, tail?: any): any {
}
}

 3.具体功能实现省略字符

 首先根据中英文转换获取字符具体的长度,然后根据长度来截取字符

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'fiterCodeLength'
})
export class FiterCodeLengthPipe implements PipeTransform {

    transform(value: any, wordwise?: any, max?: any, tail?: any): any {

        if (!value) return '';
        max = max == undefined ? 20 : parseInt(max, 10);
        var length = this.getChars(value);
        if (length <= max) return value;

        let i = 0; let c = 0; let rstr = '';

        // 开始取
        for (i = i; c < max; i++) {
            let unicode = value.charCodeAt(i);
            if (unicode < 127) {
                c += 1;
            } else {
                c += 2;
            }
            rstr += value.charAt(i);
        }
        return rstr + (tail || ' …');
    }

    getChars(str) {
        
        var length = 0.0;
        var unicode = 0;
        if (str == null || str == "") {
            return 0;
        }
        var len = str.length;
        for (var i = 0; i < len; i++) {
            unicode = str.charCodeAt(i);
            if (unicode < 127) { //判断是单字符还是双字符
                length += 1;
            } else {  //chinese
                length += 2;
            }
        }
        return length;
    }
}

4.页面具体实现方法

// 传参的形式,用:隔开
{{data.Cust_Name|fiterCodeLength:true:16}}

猜你喜欢

转载自blog.csdn.net/ab31ab/article/details/92135326