angular6 pipe管道分割字符串&首字母大写

2018-09-13  本文已影响287人  小宝薯
原数据样子 字符串首字母大写 + 字符串分割

目标

思路

一、html文件

// app.component.html
<div class="detail-staus" *ngFor="let status of detailStatusData">
  <div>{{status | detailStatus }}</div>
</div>

二、ts文件数组数据

// app.component.ts
detailStatusData = [
    'ISSUE_CONFIRMED',  // ---> Issue confirmed
    'NO_ISSUE',
    'REVIEW_REQUIRED',
    'REVIEW_REQUIRED',
  ];

三、新建pipe.ts文件

cd 到你想要的文件目录
ng g  pipe detailStatus // 你的pipe名字
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'detailStatus',
})

export class DetailStatusPipe implements PipeTransform {
//value就是数据绑定遍历的每一项
  transform(value: string): any {

    temp = value.toLowerCase().split('_');  //---> [ 'issue', 'confirmed' ]

// 对第一项的第一个字母大写,然后拼接起来就是新的第一项
    temp[0] = temp[0].charAt(0).toUpperCase() + temp[0].slice(1);
// temp[0] = temp[0].substring(0, 1).toUpperCase() + temp[0].substring(1);
 
    const strValue = temp.join(' '); // join方法不会改变原数组,会产生新数组
    return strValue;
  }
}

app.module.ts


import { DetailStatusPipe } from './pipes/detail-status.pipe'; // 导包
 declarations: [  // 声明
     DetailStatusPipe
]
上一篇 下一篇

猜你喜欢

热点阅读