在数据库里我们通常用数字表达不同的情况, 比如 1 喜欢 2不喜欢 3讨厌 但是在前端和保存下来的表格里面我们往往想看到对应的文本。
现在有两种方法来解决 1 后端sql语句解决
select A.STATUS, (CASE BAPP.STATUS WHEN 1 THEN '喜欢' WHEN 2 THEN '不喜欢' WHEN 3 THEN '讨厌' END) AS STATUSSTR,直接增加一个字段 他根据读取的数字是不同的文本
2 前端使用pipe管道 这里后端查出来还是数值 但是前端拿到这个数字通过管道来转成对应文字
// .html 一个表格里面显示下 attitude <p-column field="vehicleLevel" header="喜不喜欢" [style]="{'width':'100px','text-align':'center'}"> <ng-template let-row="rowData" pTemplate="body"> {{row.attitude|ATTITUDE}} </ng-template> </p-column>pips.ts创立一个 pipe 文件夹 里面两个文件,一个pips.module.ts 和 一个pips.ts
pips.ts
// pips.ts @Pipe({name: 'ATTITUDE'}) export class AttitudePipe implements PipeTransform { transform(value: any): any { if (util.isNullOrUndefined(value)) { return ""; } return DictionaryConstants.getLabel(value, DictionaryConstants.ATTITUDE) } }pips.module.ts
// pips.module.ts import {NgModule} from '@angular/core'; import {CommonModule} from '@angular/common'; import { AttitudePipe, } from './dictionary-pips'; @NgModule({ imports: [ CommonModule ], declarations: [ AttitudeLevelPipe ], exports: [ AttitudeLevelPipe ] }) export class DictionaryPipsModule { }用@pipe 注解就可以全局使用这个pipe了
不同的数字对应什么文本,可以写在一个 dictionary-constants.ts文件里面
// dictionary-constants.ts static ATTITUDE: Array<any> = [ {value: 1, label: "喜欢"}, {value: 2, label: "不喜欢"}, {value: 3, label: "讨厌"} ];