背景:系统中很多字典数据都是在后台获取,通常是一些数字或者字母。我们要把他转换成用户看得懂的文字
一.列表字典数据转换(只能在页面使用)
1.创建pipe文件
dictData 为页面查询到的字典数据,传到pipe 管道里使用
import {Pipe, PipeTransform} from '@angular/core';
import {DictService} from "../components/dict-data-select/dict-data-select/dict.service";
@Pipe({
name: 'dictData'
})
export class DictDataPipe implements PipeTransform {
transform(value: unknown, dictList: Array<any>) {
return value ? this.returnIt(value, dictList).label : '';
}
returnIt(code: any, dictList: any) {
for (const item of dictList) {
if (item.value === code) {
return item;
}
}
}
}
2.页面使用
dictData 为页面查询到的字典数据,传到pipe 管道里使用
{{data.officeType | dictData:dictList}}
二.通过自定义组件实现列表和表单下拉框的转换(可在页面和表单使用)
1.自定义组件dict-data-select
可选参数:
dictKey // 用于传到组件查询字典数据库的参数
mode // ‘list’参数代表页面使用,'form'代表表单使用
value // 字典的值
import {Component, EventEmitter, forwardRef, Input, OnChanges, OnInit, Output} from '@angular/core';
import {DictService} from "./dict.service";
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from "@angular/forms";
export const EXE_COUNTER_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => DictDataSelectComponent),
multi: true
};
@Component({
selector: 'app-dict-data-select',
templateUrl: './dict-data-select.component.html',
styleUrls: ['./dict-data-select.component.less'],
providers: [EXE_COUNTER_VALUE_ACCESSOR]
})
export class DictDataSelectComponent implements OnInit, OnChanges, ControlValueAccessor {
@Output() dataChange = new EventEmitter();
@Output() event = new EventEmitter();
@Input() dictKey: any = {};
@Input() value: any = '';
@Input() mode: 'form' | 'list' | 'searchForm' = 'form';
@Input() width: string = '100%';
dictList: any = []
// value: string = null;
constructor(private dictService: DictService) {
}
ngOnInit() {
this.getDictList();
}
ngOnChanges() {
// this.getDictList();
}
getDictList() {
const self = this;
self.dictService.getDictList((_ary: Array<any>, _count: number) => {
this.dictList = _ary;
}, (_code: string, _msg: string) => {
}, self.dictKey);
}
change(ev: any) {
this.onChange(ev);
const obj = this.dictList.filter((v: { value: any; }) => v.value === ev);
if (obj && obj.length > 0) {
this.dataChange.emit(obj[0]);
}
}
/* ControlValueAccessor */
onChange(_: any) {
}
writeValue(value: any) {
this.value = value;
}
registerOnChange(fn: any) {
this.onChange = fn;
}
registerOnTouched(fn: any) {
}
/* end ControlValueAccessor */
}
<ng-container *ngIf="mode=='form'">
<nz-select style="width: {{width}}" [(ngModel)]="value" (ngModelChange)="change($event)">
<nz-option *ngFor="let item of dictList" [nzLabel]="item.label" [nzValue]="item.value"></nz-option>
</nz-select>
</ng-container>
<ng-container *ngIf="mode=='list'">
<ng-container *ngFor="let item of dictList"><span *ngIf="item.value==value">{{item.label}}</span></ng-container>
</ng-container>
2.在表单页面使用

3.在普通页面使用

参考文档:


1万+

被折叠的 条评论
为什么被折叠?



