Files
bbq/src/app/shared/components/dict-select/dict-select.component.ts
Taric Xin 81c42f2cea edit
2022-03-25 13:35:56 +08:00

73 lines
2.1 KiB
TypeScript

import { ChangeDetectionStrategy, ChangeDetectorRef, Component, forwardRef, Input, OnInit } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { AddressComponent } from '@shared';
import { DictSelectService } from './dict-select.service';
@Component({
selector: 'app-dict-select',
templateUrl: './dict-select.component.html',
styleUrls: ['./dict-select.component.less'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => DictSelectComponent),
multi: true
}
],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class DictSelectComponent implements OnInit, ControlValueAccessor {
private onChangeFn?: (val: string) => void;
private onTouchedFn?: () => void;
defaultUrl = `/api/mdc/pbc/dictItems/getDictValue`;
@Input() value: any = '' || []; // 默认选中值
@Input() url: string = ''; // 获取字典数据的地址
@Input() params = {}; // 请求参数
dictList: any[] = [];
@Input() containsAllLabel = true; // 是否包含全部这一选项
@Input() mode: 'multiple' | 'tags' | 'default' = 'default';
constructor(public service: DictSelectService, public cdr: ChangeDetectorRef) {}
writeValue(geo: string): void {
if (geo == null) {
if (this.mode === 'multiple' || this.mode === 'tags') {
this.value = [];
} else {
this.value = '';
}
return;
}
this.value = geo;
}
registerOnChange(fn: any): void {
this.onChangeFn = fn;
}
registerOnTouched(fn: any): void {
this.onTouchedFn = fn;
}
ngOnInit(): void {
this.service.getDictList(this.url || this.defaultUrl, this.params).subscribe(res => {
if (res) {
this.dictList = res || [];
if (this.dictList.length > 0 && this.containsAllLabel !== false) {
const obj = { label: '全部', value: '' };
this.dictList.unshift(obj);
console.log(this.dictList);
}
this.cdr.markForCheck();
}
});
}
change($event: any) {
this.onChangeFn!($event);
}
isEmpty(val: any) {
return val === undefined || val === null || val === '';
}
}