/* * @Author: 疯狂秀才(lucas huang) * @Date: 2018-11-23 11:23:12 * @LastEditors: 疯狂秀才(Lucas Huang) * @LastEditTime: 2020-10-20 20:18:26 * @Company: Inspur * @Version: v0.3.x */ import { Component, Input, ViewChild, OnChanges, SimpleChanges, EventEmitter, OnInit, Injector, ComponentFactoryResolver, Output, ChangeDetectorRef, ViewEncapsulation, AfterViewInit, ViewContainerRef, forwardRef, ComponentRef, Type, ElementRef, NgZone, Renderer2, OnDestroy, HostListener, } from "@angular/core"; import { NG_VALUE_ACCESSOR } from "@angular/forms"; import { Observable, Subscription, of, Subject, BehaviorSubject } from "rxjs"; import { LocaleService } from "@farris/ui-locale"; import { IResizeEvent } from "@farris/ui-draggable"; import { MessagerService } from "@farris/ui-messager"; import { LoadingService, LoadingComponent } from "@farris/ui-loading"; import { DataTableComponent } from "@farris/ui-datatable"; import { TreeTableComponent, TreeNode } from "@farris/ui-treetable"; import { LayoutPanelComponent } from "@farris/ui-layout"; import { CommonUtils, FarrisComponentInstanceService } from "@farris/ui-common"; import { EntityFilter } from "@farris/ui-common/types"; import { ShortcutsService } from "@farris/ui-shortcuts"; import { InputGroupComponent } from "@farris/ui-input-group"; import { NotifyService } from "@farris/ui-notify"; import { FAVORITE_FIELD_NAME, INPUT_GROUP_ICON, LookupGridDisplayType, ExtInfoFormatter, CustomDataFormatter, } from "./lookup-displaytype"; import { LookupComponent } from "./lookup.component"; import { LookupGridOptions, lookupGridDefaults, LookupGridResult, NavigationOptions, DisplayInfo, displayInfoDefault, PickingResult, TreeInfo, LOAD_DATA_TYPE, ONLY_SELECT_LEAF, PersonalConfig, } from "./lookup-grid-options"; import { ILookupHttpService, ServerSideToken } from "./http/ILookupHttpService"; import { NavigationFilter } from "./http/RemoteParams"; import { LookupLeftComponent } from "./lookup-left.component"; import { LookupDefaultMapping } from "./lookup-defaut-mapping"; import { LookupUtils } from "./utils"; import { PersonalConfigService } from "./lookup-presonalConfig.service"; import { UtilService, TreeNodeHelper, FavoriteHelper, SelectionManager, DataTableEventManager, TreeTableEventManager, MultiSelectionManager, LookupHttpManager, LookupComponentManager, LookupDialogManager, onTextChanged, LookupSelectionService, } from "./services"; import { catchError, map, switchMap } from "rxjs/operators"; import { EventManager } from "@angular/platform-browser"; import { cloneDeep } from "lodash-es"; export const LOOKUPGRID_VALUE_ACCESSOR: any = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => LookupGridComponent), multi: true, }; @Component({ selector: "farris-lookup-grid", templateUrl: "./lookup-grid.component.html", styleUrls: ["./lookup-grid.component.scss"], providers: [ LOOKUPGRID_VALUE_ACCESSOR, ShortcutsService, LookupDefaultMapping, LookupUtils, PersonalConfigService, ], encapsulation: ViewEncapsulation.None, exportAs: "lookup", }) export class LookupGridComponent extends LookupComponent implements OnInit, AfterViewInit, OnChanges, OnDestroy { groupIcon = INPUT_GROUP_ICON; _displayType = ""; /** 使用表单设计器中的显示类型。否则使用元数据设置的显示类型。 默认:false */ @Input() customDisplayType = false; @Input() viewType: "text" | "tag" = "text"; @Input() get displayType() { return this._displayType; } set displayType(val: string) { if (val) { const types = Object.values(LookupGridDisplayType); const i = types.findIndex((n) => n === val.toUpperCase()); if (i > -1) { const keys = Object.keys(LookupGridDisplayType); this._displayType = LookupGridDisplayType[keys[i]]; } } else { this._displayType = val; } } /** 启用清空按钮 */ @Input() enableClear = true; /** 服务器端排序 */ @Input() remoteSort = true; @Input() condition: EntityFilter; /** 树表显示全选复选框。 默认不显示 */ @Input() showCheckAll = false; /** 是否启用多选 */ @Input() singleSelect = true; /** 多选分隔符 */ @Input() multipleChoiceSeparator = ","; /** 主键字段 */ @Input() idField?: string; /** 可以为元数据ID、webapiURL */ @Input() uri?: string; /** * BE REST RUI * - 此处设置后 uri 失效 */ @Input() beUri = ""; /** * 显示过滤工具条 */ @Input() showFilterBar = true; /** 是否启用分页 */ @Input() pagination = true; /** 当前页索引,从 0开始 */ @Input() pageIndex = 1; /** 每页记录数 */ @Input() pageSize = 20; /** 可用分页记录数列表 */ @Input() pageList = [10, 20, 30, 50, 100]; /** 总记录数 */ @Input() total = 0; /** 可拖动列 */ // @Input() resizableColumns = true; /** 显示列信息, 默认为 [] */ @Input() columns: any[] = []; /** 帮助查询是否为远端查询 */ @Input() remoteSearch = true; /** 文本变化后,进行服务器端查询 */ @Input() searchOnServer = true; /** 不进行服务器查询,有啥算啥 */ @Input() nosearch = false; /** * 启用任意输入后,值通过输入时触发 */ @Output() clearMappings = new EventEmitter(); /** * 允许输入的字符最大长度。 * 任意输入时,此属性有效 */ @Input() maxLength; @Input() mappingFn: (rowData, mapFields, bindingData?: any) => void; /** 数据列表 */ @Input() items: any; // 收藏列表 @Input() favoriteItems: any[] = []; /** 自定义数据 */ @Input() customData: any; /** 绑定值所在的对象 */ @Input() bindingData: {}; @Input() treeInfo: TreeInfo; /** 是否启用级联选择控制选项 */ @Input() enableCascade = false; /** 级联控制默认值: enable, up, down, disable */ @Input() cascadeStatus: "enable" | "up" | "down" | "disable" = "enable"; @Input() placeholder = ""; /** 显示已选记录列表。 默认为 false 不显示 */ @Input() showSelected = false; /** 应用收藏夹 */ @Input() useFavorite = false; /** 收藏数据来自于: locale: 本地存储, remote: 服务器端存储 */ @Input() favoriteDataFrom: "locale" | "remote" = "remote"; /** 使用提示,快捷选择 */ @Input() useTip = false; /** 记录窗口大小 */ @Input() isRecordSize = false; /** 快速选择 */ @Input() userId: string; // 是否启用选中value值对应的行数据 @Input() enableToSelect = true; @Input() enableFindText = false; /** -1: 不展开; 0: 全部展开;>0: 展开到指定级数 */ @Input() expandLevel = -1; @Input() navTreeTableOptions: any = {}; @Input() treeTableOptions: any = {}; @Input() dataTableOptions: any = {}; defaultTreeTableOptions = { maxLevel: 9, enableContextMenu: false, contextMenuItems: [], }; /** 树形帮助数据加载方式: default: 内置取数; loadall: 加载所有 layerload:分层加载 */ @Input() loadTreeDataType: "default" | "loadall" | "layerload" = "default"; /** 窗口打开后立即加载数据,默认为 true */ @Input() loadDataWhenOpen = true; /** * 导航列表,树列表在帮助打开后选中的数据; * 设置后,`selectFirstInNav` 失效! */ @Input() navSelectedIds = ""; /** * 导航帮助,选中第1条数据,默认为 false; * 注意:当`navSelectedIds`不为空时,此属性失效。 */ @Input() selectFirstInNav = false; /** 启用构造完整树过滤 */ @Input() enableFullTree = true; /** 显示文本自定义函数 */ @Input() displayFormatter: ( value: string, data: any, instance: any ) => string = undefined; /** 显示文本字段集合,以 英文 逗号隔开 */ @Input() displayFields = ""; @Input() displayTextSeparator = "_"; /** * 帮助元数据ID,不为空时调用指定的URI * /api/runtime/bcc/v1.0/help/data/{helpId} */ @Input() helpId = ""; /** 文本对齐方式; left | center | right; 默认 left */ @Input() textAlign = "left"; /** 鼠标滑过输入框时显示输入框内的文本信息 */ @Input() enableTitle = true; @Input() useExtendInfo = false; @Input() extInfoFields = ""; @Input() extInfoFormatter: ExtInfoFormatter; @Input() extendInfo = ""; /** IDE 设计器自定义格式化 2103 */ @Input() customFormatter: CustomDataFormatter = null; @Input() customNavFormatter: CustomDataFormatter = null; /** 自定义确定事件 */ @Input() okHandler = null; /** 自定义取消事件 */ @Input() cancelHandler = null; @Input() tagboxHeight = "auto"; @Input() maxTagboxHeight; /** 启用获取所有子级数据的功能 */ @Input() enableGetAllChildNodes = true; @Input() shortcutKey = { /** 打开帮助窗口 */ open: "ArrowRight", /** 确认选择数据 */ confirm: "Enter", /** 搜索框焦点 */ searchFocus: "F3", /** 选中上一条 */ moveUp: "ArrowUp", /** 选中下一条 */ moveDown: "ArrowDown", /** 展开节点 */ expand: "ArrowRight", /** 折叠节点 */ collapse: "ArrowLeft", /** 下一页 */ nextPager: "PageDown", /** 上一页 */ prevPager: "PageUp", }; /** 数据选择后,值映射前触发 * 返回 Observable * canSelect: 是否允许选择 * message: 不允许选择时的提示信息 */ @Input() beforeSelectData: (p: { instance: any; data: any; }) => Observable<{ canSelect: boolean; message: string } | boolean>; @Output() selectedData = new EventEmitter(); @Output() clear = new EventEmitter(); @Output() search = new EventEmitter(); // 帮助文本框中值变化事件 @Output() valueChanged = new EventEmitter(); @Output() loadSuccess = new EventEmitter(); @Output() pagerChanged = new EventEmitter(); @Output() expandTreeNode = new EventEmitter(); @Output() textChanged = new EventEmitter(); @Output() checkedChange = new EventEmitter<{ data: any; isCheck: boolean; }>(); @Output() tagRemoved = new EventEmitter(); /** 内容中留白边距 */ containerMargin = { top: 0, bottom: 5, left: 10, right: 10 }; containerStyle = { marginLeft: this.containerMargin.left + "px", marginRight: this.containerMargin.right + "px", marginTop: this.containerMargin.top + "px", marginBottom: this.containerMargin.bottom + "px", }; _gridOptions: LookupGridOptions = lookupGridDefaults; get gridOptions() { if ( this.useFavorite && this.columns && this.columns.length > 0 && !this.columns.find((item) => item.field === FAVORITE_FIELD_NAME) ) { this.columns.push({ field: FAVORITE_FIELD_NAME, title: "", width: 40, align: "center", formatter: this.favHelper.favoriteColumnFormatter, }); } this._gridOptions = Object.assign(this._gridOptions, { singleSelect: this.singleSelect, idField: this.idField, uri: this.uri, showFilterBar: this.showFilterBar, pagination: this.pagination, pageIndex: this.pageIndex, pageSize: this.pageSize, pageList: this.pageList, total: this.total, items: this.items, columns: this.columns, resizableColumns: true, fixedHeader: true, hover: true, treeInfo: this.treeInfo, }); return this._gridOptions; } @Input() set gridOptions(opts) { this._gridOptions = Object.assign({}, this._gridOptions, opts); this.selectedColumns = this.multiSelMgr.initSelectedColumns(); } @ViewChild("contentContainer", { read: ViewContainerRef }) contentContainer: ViewContainerRef; @ViewChild("favoritesContainer", { read: ViewContainerRef }) favoritesContainer: ViewContainerRef; @ViewChild("leftContainer", { read: ViewContainerRef }) leftContainer: ViewContainerRef; @ViewChild("centerContainer", { read: ViewContainerRef }) centerContainer: ViewContainerRef; @ViewChild("multiSelectDT") multiSelectDT: DataTableComponent; @ViewChild("inputgroup") inputGroup: InputGroupComponent; @ViewChild("leftPanel") leftPanel: LayoutPanelComponent; @ViewChild("tagbox") tagbox: ElementRef; @ViewChild("okbtn") okButton: ElementRef; componentRef: ComponentRef; leftComponentRef: ComponentRef; favoritesComponentRef: ComponentRef; public http: ILookupHttpService; public messagerService: MessagerService; public loadingService: LoadingService; loading: LoadingComponent; // dataFieldMaps: any; navigationOptions: NavigationOptions; // 导航帮助左则宽度 leftPanelWidth = 320; // 导航帮助窗口最小宽度 navLookupDialogMinWidth = 960; navigationFilter: NavigationFilter = null; subscriptions: Subscription[] = []; dialogOpenedSubscription: Subscription; dialogClosedSubscription: Subscription; isTextChange = false; isTabChanged = false; displayInfo: DisplayInfo = Object.assign({}, displayInfoDefault); tabChangeSubscription = null; // 暂存行点击数据 用于收藏 personalConf: PersonalConfig = {}; favoriteColumns: any[] = []; /** 临时查询参数 */ _searchState = null; allData: any = []; get selections() { const selectItems = this.lookupSelectionSer.getSelections(); if (this.singleSelect) { return selectItems[0]; } else { return selectItems; } } get usePersionalConf() { return this.useFavorite || this.useTip || this.isRecordSize; } get displayTextList() { if (this.displayText) { return this.displayText.split(this.multipleChoiceSeparator); } return []; } public personalConfigService: PersonalConfigService; public utilService: UtilService; public treeNodeHelper: TreeNodeHelper; public localService: LocaleService; public notifyService: NotifyService; allColumnsTitle = "所有列"; mustWriteSomething = "请输入关键字后查询。"; mustChoosAdatarow = "请选择一条记录!"; addFavoriteSuccess = "收藏成功。"; delFavoriteSuccess = "移除收藏成功。"; searching = false; /** 临时存储查询结果集 */ _searchResult = null; lookupinitializationSubject = new Subject(); /** 多选时,选中的数据 */ currentSelectedItems: Observable = of([]); /** 已选数据列信息 */ selectedColumns = []; activeTab: string | "datalist" | "favorite" | "selected" = "datalist"; favHelper: FavoriteHelper = null; ttEventMgr: TreeTableEventManager = null; multiSelMgr: MultiSelectionManager = null; httpMgr: LookupHttpManager = null; lookupCmpMgr: LookupComponentManager = null; dialogMgr: LookupDialogManager = null; selectionMgr: SelectionManager = null; dtEventMgr: DataTableEventManager = null; lookupSelectionSer: LookupSelectionService = null; controlId = ""; savingFaoriteData = false; isReady = false; showTagboxClearButton = false; hasError = false; isGetAllChidlNodes = false; eventManager: EventManager; /** 选中记录ID,自定义帮助取数时使用 */ selectedIds = []; private lookupSearchInputEvent = null; private farrisInstances: FarrisComponentInstanceService = null; /** 用户初始设置 */ private _userSettings: any = {}; get userInitialConfig() { return this._userSettings; } constructor( public injector: Injector, public cfr: ComponentFactoryResolver, public el: ElementRef, public utils: CommonUtils, private defaultMapping: LookupDefaultMapping, public changeDetector: ChangeDetectorRef, public shortcuts: ShortcutsService, public lookupUtils: LookupUtils, private zone: NgZone, private render2: Renderer2 ) { super(injector, el, changeDetector); this.createInstance(); this.currentSelectedItems = this.lookupSelectionSer.selected$; this.eventManager = this.injector.get(EventManager); this.farrisInstances = this.injector.get( FarrisComponentInstanceService, null ); } private cacheUserConfig() { this._userSettings._title = this.title; this.displayInfo.title = this.title; this._userSettings._columns = this.deepClone(this.columns || []); this._userSettings.getColumns = () => { return this._userSettings._columns; }; this._userSettings.reset = () => { this.title = this._userSettings._title; this.displayInfo.title = this.title; this.columns = this._userSettings.getColumns(); }; } private deepClone(obj) { if (obj === null) { return null; } const clone = Object.assign({}, obj); Object.keys(clone).forEach( (key) => (clone[key] = typeof obj[key] === "object" ? this.deepClone(obj[key]) : obj[key]) ); if (Array.isArray(obj)) { clone.length = obj.length; return Array.from(clone); } return clone; } ngOnInit() { super.ngOnInit(); this.cacheUserConfig(); if (!this.loadTreeDataType) { this.loadTreeDataType = "default"; } this.checkGridOptions(); this.displayInfo.title = this.title; /** 传递上下文 */ if (this.http) { this.http.context = this.context; } this.allColumnsTitle = this.localService.getValue("lookup.allColumns"); this.mustWriteSomething = this.localService.getValue( "lookup.mustWriteSomething" ); this.mustChoosAdatarow = this.localService.getValue( "lookup.mustChoosAdatarow" ); this.addFavoriteSuccess = this.localService.getValue("lookup.favoriteInfo.addFav") || this.addFavoriteSuccess; this.delFavoriteSuccess = this.localService.getValue("lookup.favoriteInfo.cancelFav") || this.delFavoriteSuccess; this.dialogMgr.onDialogCreated(); } ngOnDestroy() { super.ngOnDestroy(); this.subscriptions.forEach((n) => { if (n) { n.unsubscribe(); n = null; } }); if (this.selectionMgr) { this.selectionMgr.destroy(); } this.subscriptions = []; if (this.farrisInstances) { this.farrisInstances.destroy(this.el.nativeElement); } if (this.lookupSearchInputEvent) { this.lookupSearchInputEvent(); } this.lookupUtils.destroy(); } ngOnChanges(changes: SimpleChanges) { if (changes.columns && !changes.columns.isFirstChange()) { this.cacheUserConfig(); } } ngAfterViewInit() { this.lookupSearchInputEvent = onTextChanged.bind(this)(); // 初始化个性化配置 if (this.usePersionalConf) { this.favHelper.initPersonalInfo(); } if (this.useExtendInfo) { const jsonData = this.selectionMgr.getBindingData(); this.updateExtendInfo(jsonData, false); } if (this.viewType === "text") { // this.shortcuts.add({ // key: 'F2', // target: this.inputGroup.textbox.nativeElement, // command: () => { // this.showDialog(); // } // }); this.render2.listen( this.inputGroup.textbox.nativeElement, "keydown.F2", this.showDialog.bind(this) ); } else { this.registerMouseEventForTagView(); if (this.tagboxHeight) { const el = this.tagbox.nativeElement.querySelector(".multi-more"); let tbh = this.tagboxHeight; if (tbh !== "auto") { tbh += "px"; if (this.maxTagboxHeight) { this.render2.setStyle( el, "maxHeight", `${this.maxTagboxHeight}px` ); } } this.render2.setStyle(el, "height", tbh); } } if (this.el && this.farrisInstances) { this.farrisInstances.add(this.el.nativeElement, this); } } private createInstance() { this.http = this.injector.get(ServerSideToken, null); this.messagerService = this.injector.get(MessagerService); this.loadingService = this.injector.get(LoadingService); this.notifyService = this.injector.get(NotifyService, null); this.personalConfigService = this.injector.get( PersonalConfigService, null ); this.lookupSelectionSer = new LookupSelectionService(this); this.utilService = new UtilService(this); this.localService = this.injector.get(LocaleService); this.treeNodeHelper = new TreeNodeHelper(this); this.favHelper = new FavoriteHelper(this); this.ttEventMgr = new TreeTableEventManager(this); this.multiSelMgr = new MultiSelectionManager(this); this.httpMgr = new LookupHttpManager(this); this.lookupCmpMgr = new LookupComponentManager(this); this.dialogMgr = new LookupDialogManager(this); this.selectionMgr = new SelectionManager(this); this.dtEventMgr = new DataTableEventManager(this); } showDialog(): any { if (this.disabled || this.readonly) { return false; } this.selectionMgr.initDisplayValue(); this.dictPickingSubscription = this.dictPicking({ instance: this, }).subscribe((pr: PickingResult) => { this.dialogMgr.canOpenDialog(pr); }); return false; } /** 判断是否为双列表帮助 */ isDoublleList() { return ( this.displayType === LookupGridDisplayType.NavList || this.displayType === LookupGridDisplayType.NavTreeList ); } /** 判断是否显示为树帮助 */ isTree() { return ( this.displayType.toUpperCase() === LookupGridDisplayType.TreeList ); } onResized(e: any) { this.resizeCmp(e.size); this.resized.emit(e.size); } onResizing(pos: IResizeEvent) { this.resizing.emit(pos.size); this.resizeCmp(pos.size); if (this.isDoublleList() && this.leftComponentRef) { this.leftComponentRef.instance.resize({ width: this.leftPanel.width, height: this.dialogMgr.getHeight(), }); } } onMaxDialog(pos: IResizeEvent) { this.resizeCmp(pos.size); if (this.leftPanel) { this.leftComponentRef.instance.resize({ width: this.leftPanel.width, height: this.dialogMgr.getHeight(), }); } this.dialogMaxed.emit(pos.size); } resizeCmp(size?: any) { if (!this.componentRef || !this.componentRef.instance) { return; } if (!size) { size = this.dialog.size; } const _size = { width: size.width - this.containerMargin.left - this.containerMargin.right, height: this.dialogMgr.getHeight(), }; if (this.useFavorite && this.favoritesComponentRef) { this.favoritesComponentRef.instance.resize(_size); } if (this.isRecordSize) { this.personalConf.size = this.dialog.size; this.personalConfigService.updatePersonalConfig({ size: this.dialog.size, }); } if (this.isDoublleList()) { _size.width = size.width - this.leftPanel.width - 27; } this.componentRef.instance.resize(_size); } private checkGridOptions() { if (!this.gridOptions.idField) { console.warn("未设置主键字段 idField"); } if (!this.beforeSelectData) { this.beforeSelectData = () => { return of(true); }; } const ctxMenuLanguages = this.localService.getValue("lookup.contextMenu"); this.treeTableOptions = Object.assign( { language: ctxMenuLanguages }, this.defaultTreeTableOptions, this.treeTableOptions || {} ); // this.dataTableOptions = Object.assign({}, this.defaultTreeTableOptions, this.dataTableOptions); // this.navTreeTableOptions = Object.assign({}, this.defaultTreeTableOptions, this.navTreeTableOptions); } getComponentType(): Type { if (!this.displayType) { this.displayType = "LIST"; } switch (this.displayType) { case LookupGridDisplayType.List: case LookupGridDisplayType.NavList: case LookupGridDisplayType.NavTreeList: return DataTableComponent; case LookupGridDisplayType.TreeList: return TreeTableComponent; } } showLoading(msg = "") { if (this.dialog && this.dialog.modalContent && !this.loading) { const opts = { container: this.dialog.modalContent, delay: 200, }; if (msg) { opts["message"] = msg; } this.loading = this.loadingService.show(opts); } else { this.loading = this.loadingService.show(); } } closeLoading() { if (this.loading) { this.loading.close(); this.loading = null; } this.loadingService.clearAll(); } getSearchColumns(resdata: any) { const cols = resdata.columns || this.columns; if (resdata.searchFields) { return resdata.searchFields.map((sf) => { const c = cols.find( (col) => col.field.toLowerCase() === sf.value.toLowerCase() ); if (c) { sf.label = c.title; } return sf; }); } else if (cols) { return cols .filter((c) => c.searchField) .map((col) => { return { label: col.title, value: col.field, }; }); } return []; } private initOptions(resData: LookupGridResult) { let obser = of(true); this.gridOptions.searchFields = this.getSearchColumns(resData); if (resData) { // 如果组件中未设置显示列,则使用服务器端返回的设置; 否则将使用组件中配置的展示列 if ( (!this.columns || !this.columns.length) && resData.columns && resData.columns.length ) { this.columns = resData.columns; } this.setLookupTitleText(resData); if ( this.isDoublleList() && this.dialogWidth < this.navLookupDialogMinWidth && !this.isRecordSize ) { this.dialogWidth = this.navLookupDialogMinWidth; this.dialog.reSize({ width: this.dialogWidth }); } if (!this.customDisplayType) { this.displayType = resData.displayType || this.displayType || "LIST"; this.changeDetector.detectChanges(); this.lookupCmpMgr.createComponentWithServerData(resData); } if ( this.isDoublleList() && resData.navigation && !this.leftComponentRef ) { this.navigationOptions = resData.navigation; this.navigationOptions.hover = true; this.navigationOptions.searchFields = this.getSearchColumns( this.navigationOptions ); // update columns formatter if (this.customNavFormatter) { this.navigationOptions.columns.forEach((col) => { if (this.customNavFormatter[col.field]) { col.formatter = this.customNavFormatter[col.field]; } }); this.navigationOptions["rowStyler"] = this.customNavFormatter.rowStyler; this.navigationOptions["cellStyler"] = this.customNavFormatter.cellStyler; } // 20210926 树导航帮助中 左侧树支持分层加载 if (this.displayType === LookupGridDisplayType.NavTreeList) { let _nav_treeinfo_loadtype = this.navigationOptions.treeInfo.loadDataType; if (this.loadTreeDataType !== "default") { _nav_treeinfo_loadtype = this.loadTreeDataType === "loadall" ? "all" : "async"; } this.navigationOptions.treeInfo.loadDataType = _nav_treeinfo_loadtype; } obser = this.lookupCmpMgr.createLeftComponent( this.navigationOptions ); } } else { this.lookupCmpMgr.createContent(this.gridOptions); this.lookupCmpMgr.createFavoriteComponent(); } if (this.isTextChange) { this.componentRef.instance.searchData.value = this.displayText; } // update columns formatter if (this.customFormatter) { this.columns.forEach((col) => { if (this.customFormatter[col.field]) { col.formatter = this.customFormatter[col.field]; } }); if (this.customFormatter.rowStyler) { this.componentRef.instance.rowStyler = this.customFormatter.rowStyler; } if (this.customFormatter.cellStyler) { this.componentRef.instance.cellStyler = this.customFormatter.cellStyler; } } this.changeDetector.detectChanges(); return obser; } /** * 设置帮助窗口标题 */ private setLookupTitleText(resData: LookupGridResult) { if (resData.displayInfo) { this.displayInfo = resData.displayInfo; } // 如果自定义标题,将以此标题为准。否则加载服务器端返回的数据 if (this.title && this.title !== "此处显示帮助标题") { this.displayInfo.title = this.title; } if (this.displayInfo && resData.title) { if (!this.displayInfo.title) { this.displayInfo.title = resData.title; } } } private showGetAllChildrenCheckbox() { if (this.isTree() && this.treeInfo) { this.enableGetAllChildNodes = this.treeInfo.loadDataType !== "all" && this.treeInfo.layerType === "pathcode"; } else { this.enableGetAllChildNodes = false; } } initData() { const observer = { next: (data: LookupGridResult) => { // 服务器端发生错误,返回NULL 时,直接关闭窗口 if (data === null) { this.isShow = false; if (this.dialog) { this.dialog.close(); } return; } this.initOptions(data).subscribe(() => { this.selectedColumns = this.multiSelMgr.initSelectedColumns(); this.favoriteColumns = this.favHelper.getFavoriteColumns(); if (this.usePersionalConf) { if (!this.personalConfigService.getPersonalData()) { this.personalConfigService.savePersonalConfig( this.personalConf ); } } if (!this.isTabChanged) { this.lookupSelectionSer.loadSelections( data.selectedItems || [] ); } if (this.isDoublleList()) { // 导航帮助时,设置左侧选中数据时,不加载主数据列表。 if (this.navSelectedIds || this.selectFirstInNav) { this.loadDataWhenOpen = false; } } this.loadData(data); if (this.isTree()) { if (this.activeTab === "datalist") { const tt = this.componentRef .instance as TreeTableComponent; if ( tt.loadDataType === "all" && tt.searchData.value ) { if (this.items && this.items.length) { tt.toggleExpand(this.items[0], true); } } } this.showGetAllChildrenCheckbox(); } this.isTextChange = false; this._searchResult = null; // 清空临时查询 结果 this.closeLoading(); // this.isReady$.next(true); this.isReady = true; this.changeDetector.detectChanges(); this.lookupinitializationSubject.next(); }); }, error: (err: any) => { // this.isReady$.next(true); this.closeLoading(); this._searchResult = null; // 清空临时查询 结果 this.isTextChange = false; this.hasError = true; this.changeDetector.detectChanges(); if (typeof err === "string") { this.messagerService.error(err); } else { if (err) { if (err.Message) { this.messagerService.error(err.Message); } else { if (err.error) { this.messagerService.error(err.error.Message); } else { this.messagerService.error( "应用服务器错误,请联系系统管理员!" ); } } } console.log(err); } }, }; let p: any = { pageInfo: { pageSize: this.pageSize || 20, pageIndex: 1, }, }; const t: LOAD_DATA_TYPE = "all"; if (this.isTextChange) { p = { search: { field: "*", value: this.displayText, }, }; } if (!this.isTabChanged && this.enableToSelect) { const vals = this.selectionMgr.getSelectedIds(); if (vals && vals.length) { p["selectedInfo"] = { selected: true, selectedIds: vals, }; } else { if (this["selectedIds"]) { p["selectedInfo"] = { selected: true, selectedIds: this["selectedIds"], }; } } } this.showLoading(); this.hasError = false; this.httpMgr .lookupRequest(p, t) .pipe( map((restData: LookupGridResult) => { if (restData) { restData.selectedItems = restData["selectedData"] || []; } else { if (restData && typeof restData === "object") { restData.selectedItems = []; } } return restData; }) ) .subscribe(observer); } loadData(resData?: LookupGridResult, rebindEvent = true) { if (this.activeTab === "datalist") { if (this.useFavorite && !this.isTree()) { this.favHelper.updateFavoritesStatus(resData.items); } switch (this.displayType) { case LookupGridDisplayType.NavList: case LookupGridDisplayType.NavTreeList: case LookupGridDisplayType.List: this.loadDataTableData(resData); if (rebindEvent) { this.dtEventMgr.bindDataTableEvent(); } break; case LookupGridDisplayType.TreeList: this.loadTreeTableData(resData, rebindEvent); break; } } else if (this.activeTab === "favorite") { this.loadFavData(resData); } // 选中数据 this.selectionMgr.selectCurrentValue(); } private loadFavData(result: LookupGridResult) { // 加载收藏数据 if (this.useFavorite) { if (this.isTree) { this.setTreeInfo(result); } if (this.isTree()) { const treeNodes = this.favHelper.initFavoriteTreeData( result.items ); const treeData = this.treeNodeHelper .flatTreeNodes(treeNodes) .map((n) => { n.data["_addtional_"] = n["addtional"]; return n.data; }); this.lookupSelectionSer.initFavoriteItems(treeData); setTimeout(() => { this.favoritesComponentRef.instance.scrollToY(1); }); } else { this.lookupSelectionSer.initFavoriteItems(result.items); } this.favHelper.loadFavoritesData(result); } } loadDataTableData(resData?: LookupGridResult) { if (resData) { if (this.gridOptions) { if (resData && resData.columns && resData.columns.length) { if ( !this.gridOptions.columns || !this.gridOptions.columns.length ) { this.columns = resData.columns; } } this.items = resData.items; this.total = resData.total || resData.items.length; if (resData.pageInfo) { if ( resData.pageInfo.pageList && (!this.pageList || !this.pageList.length) ) { this.pageList = resData.pageInfo.pageList; } this.pagination = resData.pageInfo.enablePager; this.pageIndex = resData.pageInfo.pageIndex; this.pageSize = resData.pageInfo.pageSize; } else { this.pagination = false; } } else { this.gridOptions = resData as LookupGridOptions; } } this.updateDataTable(this.gridOptions); } private updateDataTable(opts: any) { if (opts) { const dt = this.componentRef.instance as DataTableComponent; if (!dt.columns || dt.columns.length === 0) { dt.columns = this.gridOptions.columns; } dt.allColumnsTitle = this.allColumnsTitle; dt.searchFields = opts.searchFields; dt.pagination = opts.pagination; dt.pageList = this.pageList; dt.remoteSort = this.remoteSort; if (this.loadDataWhenOpen) { dt.loadData({ pageSize: opts.pageSize, pageIndex: this.gridOptions.pageIndex, total: this.gridOptions.total, data: this.gridOptions.items, }); dt.cd.markForCheck(); } this.loadSuccess.emit(); } } private setTreeInfo(resData) { if (!resData) { return; } let _treeInfo = null; if (resData.treeInfo) { const onlySelectLeaf = resData.treeInfo.onlySelectLeaf; let _osl: ONLY_SELECT_LEAF = "no"; if (onlySelectLeaf !== undefined) { _osl = onlySelectLeaf ? "yes" : "no"; } _treeInfo = { ...resData.treeInfo, onlySelectLeaf: _osl }; } if (this.gridOptions.treeInfo) { const treeInfo = this.gridOptions.treeInfo; if (treeInfo) { if ( treeInfo.onlySelectLeaf === undefined || treeInfo.onlySelectLeaf === null ) { treeInfo.onlySelectLeaf = "no"; } if (typeof treeInfo.onlySelectLeaf === "boolean") { treeInfo.onlySelectLeaf = treeInfo.onlySelectLeaf ? "yes" : "no"; } // 20210902 if (this.loadTreeDataType === "default") { treeInfo.loadDataType = _treeInfo.loadDataType; } else { treeInfo.loadDataType = this.loadTreeDataType === "loadall" ? "all" : "async"; } if (treeInfo.onlySelectLeaf !== "default") { _treeInfo = Object.assign(_treeInfo, treeInfo); } } } this.treeInfo = _treeInfo; } private loadTreeTableData(resData?: LookupGridResult, rebindEvent = true) { const items = resData ? resData.items : this.gridOptions.items; this.items = items; if (resData) { this.setTreeInfo(resData); const treeInfo = this.gridOptions.treeInfo; if (!treeInfo["treeDataIsInit"]) { if (treeInfo.layerType.toLowerCase() === "pathcode") { this.items = this.lookupUtils.makeTree( this.items, treeInfo ); } else { this.items = this.lookupUtils.makeTreeWithParentID( this.items, "", `${treeInfo.dataField}.${treeInfo.parentField}`, this.idField ); } } } if (this.componentRef.instance instanceof TreeTableComponent) { const tt = this.componentRef.instance as TreeTableComponent; if (this.treeInfo) { tt.loadDataType = this.treeInfo.loadDataType; } if (!this.columns || !this.columns.length) { tt.columns = resData.columns || []; this.gridOptions.columns = tt.columns; } const isLoadAllTreeData = () => { if (this.loadTreeDataType === "default") { return tt.loadDataType === "all"; } else { return this.loadTreeDataType === "loadall"; } }; if (rebindEvent) { this.ttEventMgr.bindTreetableEvent(); } const isLoadAll = isLoadAllTreeData(); /** 完整树节点检查 By Lucas 20200302 */ this.items = this.checkNodeCanBeSelect(this.items, isLoadAll); tt.keepSelect = true; if (this.useFavorite) { this.favHelper.updateFavoritesStatus(this.items); } if (this.loadDataWhenOpen) { tt.loadData(this.items); } tt.resize(); } } /** * 在构完整树中,有部分节点因为条件被过滤,为显示完整树, * 这些节点在运行时是不允许被选中的, 返回新的节点数组 * By Lucas 20200302 */ checkNodeCanBeSelect(nodes, isAllTreeData = false): TreeNode[] { if (nodes && nodes.length) { return nodes.map((node: TreeNode) => { if (node.hasOwnProperty("addtional")) { node.selectable = !node["addtional"]; } if (node.children && node.children.length) { this.checkNodeCanBeSelect(node.children, isAllTreeData); } else { if (isAllTreeData) { node.leaf = true; } } return node; }); } return nodes; } onChanges(val) { if (!val) { this.onClear(); } else { this.displayText = val; this.isTextChange = true; if (this.nosearch) { this.setModelValue(val); this.clearMappings.emit({ instance: this, value: val, }); } this.onModelTouched(val); this.valueChanged.emit(val); this.textChanged.emit(val); } } onClear(emit = true) { this.isTextChange = false; this.displayText = ""; this.displayValue = ""; this.originalText = ""; this.extendInfo = ""; this.setModelValue(""); if (this.mappingFn) { this.mappingFn(null, this.mapFields); } else { if (this.mapFields) { const bindingData = this.selectionMgr.getBindingData(); if (bindingData) { this.defaultMapping.lookupFieldMap( null, this.mapFields, bindingData ); } } } this.multiSelMgr.clear(); if (emit) { this.clear.emit(); } } clearValue(emit = true) { this.onClear(emit); } selectItem(rowData?: any) { let selectedRow = null; if (rowData) { selectedRow = rowData; } else { selectedRow = this.selections; if (!selectedRow) { selectedRow = null; } else { if (Array.isArray(selectedRow) && !selectedRow.length) { selectedRow = null; } } } // 如果定义自定义处理确定事件,则由自定义事件处理后面的逻辑 if (this.okHandler) { this.okHandler({ data: selectedRow, instance: this }); } else { if (this.beforeSelectData) { const bsdResult = this.beforeSelectData({ instance: this, data: selectedRow, }); if (bsdResult && bsdResult.subscribe) { bsdResult.subscribe((e: any) => { this._beforeSelectDataCallBack(e, selectedRow); }); } else { console.error( "帮助数据选中前事件未返回值或返回类型非Observable, 请检查" ); } } else { this._beforeSelectDataCallBack(true, selectedRow); } } } private getParentPathCode(rows) { const maxBy = (arr, fn) => Math.max( ...arr.map(typeof fn === "function" ? fn : (val) => val[fn]) ); const { dataField, pathField, layerField } = this.treeInfo; const maxLayer = maxBy(rows, (x) => x[dataField][layerField]); for (let i = 1; i <= maxLayer; i++) { const _rows = rows.filter((n) => n[dataField][layerField] === i); if (_rows && _rows.length && _rows.length < rows.length) { _rows.forEach((r) => { const patchCode = r[dataField][pathField]; const _rows2 = rows.filter( (n) => n[dataField][pathField] !== patchCode && n[dataField][pathField].indexOf(patchCode) === 0 ); if (_rows2 && _rows2.length) { rows = rows.filter( (n) => n[dataField][pathField] !== patchCode ); } }); } } return rows; } private _beforeSelectDataCallBack(e, selectedRow) { let canSelect = e; let message = ""; if (typeof e === "boolean") { canSelect = e; } else { if (typeof e === "object") { canSelect = e.canSelect; message = e.message; } else { canSelect = false; } } if (!selectedRow) { message = this.mustChoosAdatarow; canSelect = false; } if (canSelect) { let selectedRows$ = of(selectedRow); // 多选 树帮助 异步加载 分级码 开启同步选择 或包含下级 if ( !this.singleSelect && this.enableCascade && this.isTree() && this.treeInfo.loadDataType !== "all" && this.treeInfo.layerType === "pathcode" && this.isGetAllChidlNodes ) { // const parentsIds = selectedRow.map(n => n[this.treeInfo.dataField][this.treeInfo.pathField]); let parentsIds = this.getParentPathCode(selectedRow); if (parentsIds && parentsIds.length) { parentsIds = parentsIds.map( (n) => n[this.treeInfo.dataField][this.treeInfo.pathField] ); this.showLoading(); selectedRows$ = this.httpMgr .getData({ parentsIds }, "allChildren") .pipe( map((r: LookupGridResult) => { const items = r.items ? r.items.map((d) => d.data) : []; const allitems = [...selectedRow, ...items]; let ids = allitems.map((n) => n[this.idField]); ids = Array.from(new Set(ids)); return ids.map((n) => allitems.find((a) => a[this.idField] === n) ); }) ); } } selectedRows$.subscribe((rows) => { this.closeLoading(); this.updateControlValue(rows); if (!this.useTip || !rows) { return; } if (this.useTip) { this.personalConfigService.updateQueckSelected( rows, this.localService.localeId ); } }); } else { if (message) { if (this.notifyService) { this.notifyService.warning(message); } else { this.messagerService.warning(message, "", true, () => { this.dialog.el.nativeElement.click(); }); } } } } private updateControlValue(selectedRow) { if (selectedRow) { this.setDisplayText(selectedRow); if (this.mappingFn) { this.mappingFn(selectedRow, this.mapFields, this.bindingData); } else { if (this.mapFields && this.bindingData) { this.defaultMapping.lookupFieldMap( selectedRow, this.mapFields, this.bindingData ); } } this.setModelValue(this.displayText); if (this["inDatagrid"] && selectedRow) { const selectItems = Array.isArray(selectedRow) ? selectedRow : [selectedRow]; this.updateBindData(selectItems); } this.selectedData.emit(selectedRow); this.runDictPickedEvent(selectedRow); this.isTextChange = false; } else { if (document.activeElement) { (document.activeElement as HTMLButtonElement).blur(); } this.messagerService.warning(this.mustChoosAdatarow); } } private updateBindData(selectedRow) { if (!this.mapFields) { return; } const helpFields = Object.keys(this.mapFields); if ( this.ngControl && this.ngControl.formDirective && this.ngControl.formDirective.form && this.ngControl.formDirective.form.bindingData ) { const bindingData = this.ngControl.formDirective.form.bindingData; if (bindingData) { helpFields.forEach((helpField: any) => { this.mapFields[helpField] .split(",") .forEach((formField: any) => { const val = selectedRow .map((r) => { return this.utils.getValue(helpField, r); }) .join(this.multipleChoiceSeparator); this.utils.setValue(bindingData, formField, val); }); }); } // if (bindingData.setValue) { // const bindingPath = this.ngControl.formDirective.form.bindingPath; // let pathArr: string[] = []; // if (bindingPath) { // pathArr = bindingPath.split('/').filter(n => n !== ''); // } // helpFields.forEach((helpField: any) => { // this.mapFields[helpField].split(',').forEach((formField: any) => { // const fieldPaths = pathArr.concat(formField.split('.')); // const val = selectedRow.map(r => { // return this.utils.getValue(formField, r); // }).join(this.multipleChoiceSeparator); // bindingData.setValue(pathArr.concat(fieldPaths), val, true, true); // }); // }); // } } else { // if (this.bindingData) { // helpFields.forEach((helpField: any) => { // this.mapFields[helpField].split(',').forEach((formField: any) => { // const val = selectedRow.map(r => { // return this.utils.getValue(formField, r); // }).join(this.multipleChoiceSeparator); // this.utils.setValue(this.bindingData, formField, val); // }); // }); // } } } private getExtendInfoFields(isHelpData = true) { if (!this.extInfoFields) { console.warn(`未设置扩展字段。`); return []; } const tipFieldArr = this.extInfoFields.split(","); if (isHelpData) { let extendInfoFields = []; extendInfoFields = tipFieldArr.map((tf) => { const mapKey = Object.keys(this.mapFields).find((k) => { return this.mapFields[k] === tf; }); if (mapKey) { return mapKey; } else { console.warn(`在帮助映射字段中未找到${tf}`); return ""; } }); return extendInfoFields; } return tipFieldArr; } onUpdateExtendInfo() { const jsonData = this.selectionMgr.getBindingData(); this.updateExtendInfo(jsonData, false); } // 选中帮助数据后,更新扩展信息 private updateExtendInfo(data: any, isHelpData = true) { if (data) { if (this.extInfoFormatter) { if (Array.isArray(data)) { const tipString = data.map((n) => { return this.getExtendInfoText(n); }); this.extendInfo = tipString.join(","); } else { this.extendInfo = this.getExtendInfoText(data); } } else { const extendInfoFields = this.getExtendInfoFields(isHelpData); if (extendInfoFields && extendInfoFields.length) { if (Array.isArray(data)) { const tipString = data.map((n) => { return this.getExtendInfoText(n, extendInfoFields); }); this.extendInfo = tipString.join(","); } else { this.extendInfo = this.getExtendInfoText( data, extendInfoFields ); } } } } } private getExtendInfoText(itemData, fields = null) { if (typeof this.extInfoFormatter === "function") { return this.extInfoFormatter({ bindingData: itemData, instance: this, }); } else { const tipString = []; const tipValues = fields.map((t) => { const tfv = this.utils.getValue(t, itemData); tipString.push(tfv); return { [t]: tfv }; }); return tipString.join(" "); } } private getDisplayText(rows: any) { const df = this.displayFields ? this.displayFields.split(",") : [this.textField]; const txtArr = rows.map((r) => { const t = []; df.forEach((n) => { t.push(this.utils.getValue(n, r)); }); return t.join(this.displayTextSeparator); }); if (this.gridOptions.singleSelect) { return txtArr.join(""); } else { if (this.displayFields) { return txtArr.map((t) => "[" + t + "]").join(","); } else { return txtArr.join(","); } } } private setDisplayText(selectedRow: any) { this.originalText = this.displayText; if (this.gridOptions.singleSelect) { if (this.displayFormatter) { this.displayText = this.utils.getValue( this.textField, selectedRow ); if (!this.isTree()) { this.displayText = this.displayFormatter( this.displayText, [selectedRow], { lookup: this, datatable: this.componentRef .instance as DataTableComponent, } ); } else { const tt = this.componentRef.instance as TreeTableComponent; this.displayText = this.displayFormatter( this.displayText, [selectedRow], { lookup: this, tree: tt } ); } } else { this.displayText = this.getDisplayText([selectedRow]); } this.displayValue = selectedRow[this.valueField]; } else { if (selectedRow.length) { if (this.displayFormatter) { this.displayText = selectedRow .map((r) => { return this.utils.getValue(this.textField, r); }) .join(this.multipleChoiceSeparator); if (!this.isTree()) { this.displayText = this.displayFormatter( this.displayText, selectedRow, { lookup: this, datatable: this.componentRef .instance as DataTableComponent, } ); } else { const tt = this.componentRef .instance as TreeTableComponent; this.displayText = this.displayFormatter( this.displayText, selectedRow, { lookup: this, tree: tt } ); } } else { this.displayText = this.getDisplayText(selectedRow); } this.displayValue = selectedRow .map((r) => { return this.utils.getValue(this.valueField, r); }) .join(this.multipleChoiceSeparator); } } this.originalText = this.displayText; } runDictPickedEvent(rowData: any) { if (this.dictPicked) { if (this.okButton) { this.okButton.nativeElement.disabled = true; } this.dictPickedSubscription = this.dictPicked(rowData).subscribe( (v: any) => { if (this.okButton) { this.okButton.nativeElement.disabled = false; } if (typeof v === "boolean") { if (v) { this.closeDialog(rowData); } } else if ( typeof v === "object" && v.closeDialog !== undefined && !v.closeDialog ) { if (v.message) { this.messagerService.warning(v.message); } else { this.closeDialog(rowData); } } else { this.closeDialog(rowData); } } ); } else { this.closeDialog(rowData); } } private focusToInput(): void { this.zone.runOutsideAngular(() => { setTimeout(() => { if (this.inputGroup && this.inputGroup.textbox) { this.inputGroup.textbox.nativeElement.focus(); } }); }); } closeDialog(rowData = null) { this.isShow = false; if (this.dialog) { this.dialog.close(); } if (rowData) { this.multiSelMgr.save(rowData); } this.focusToInput(); } cancelSelect() { this.closeDialog(); this.isTextChange = false; if (!this.nosearch) { this.displayText = this.originalText; this.setModelValue(this.displayText); } if (this.cancelHandler) { this.cancelHandler(this); } } setModelValue(v) { if (this.onModelChange) { this.onModelChange(v); this.valueChanged.emit(v); } } // 数据列表,收藏, 已选数据 tab 页切换 onTabChange(e: any) { this.activeTab = e.tabIndex; this.personalConf.tabIndex = this.activeTab; const _firstChange = this.isTabChanged; this.isTabChanged = true; this.personalConfigService.updatePersonalConfig({ tabIndex: e.tabIndex, }); if (this.activeTab === "datalist") { if (this.isDoublleList() && !this.leftComponentRef) { if (this.navigationOptions) { this.lookupCmpMgr.createLeftComponent( this.navigationOptions ); } else { this.initData(); return; } } if (!this.items || !this.items.length) { this.initData(); } else { if (!_firstChange) { if (this.isTree()) { this.loadTreeTableData(); } else { this.loadDataTableData(); this.dtEventMgr.bindDataTableEvent(); } } // this.selectionMgr.selectCurrentValue(); } this.showGetAllChildrenCheckbox(); } else { if (this.activeTab === "favorite") { if (this.isTree()) { this.initData(); } else { if ( !this.favoriteItems || !this.favoriteItems.length || this.favoriteItems.length !== this.favHelper.getFavoritIds().length ) { this.initData(); } else if (!_firstChange) { this.favHelper._loadFavoriteData(this.favoriteItems); // this.selectionMgr.selectCurrentValue(); } // else { // this.selectionMgr.selectCurrentValue(); // } } } } this.changeDetector.detectChanges(); setTimeout(() => { this.resizeCmp(); if (this.isTree()) { const y = this.componentRef.instance.state.scrollY; this.componentRef.instance.scrollToY(y, 0); if (this.enableCascade) { this.ttEventMgr.cascadeValueChanged(this.cascadeStatus); } this.selectionMgr.selectCurrentValue(); } }); } //#region Tag View ---------------------------------------------------------------------- private registerMouseEventForTagView() { if (this.enableClear) { this.tagbox.nativeElement.addEventListener( "mouseenter", this.onTagboxMouseEnter.bind(this) ); this.tagbox.nativeElement.addEventListener( "mouseleave", this.onTagboxMouseLeave.bind(this) ); } } private toggleClearIcon(event: any, isShow = false) { const str = isShow ? "" : "none"; const clearIcon = event.target.querySelector(".input-group-clear"); if (clearIcon) { clearIcon.style.display = str; } } private onTagboxMouseEnter(event) { if (this.displayText && this.enableClear) { if (!this.readonly && !this.disabled) { this.showTagboxClearButton = true; } } if (this.showTagboxClearButton) { this.toggleClearIcon(event, true); } } private onTagboxMouseLeave(event) { this.toggleClearIcon(event); } onRemoveSelectItem($event, txt) { // console.log($event, txt); $event.stopPropagation(); const textArray = Array.from(this.displayTextList); const removedIndex = this.displayTextList.indexOf(txt); textArray.splice(removedIndex, 1); this.displayText = textArray.join(this.multipleChoiceSeparator); this.setModelValue(this.displayText); if (this.displayValue) { const vals = this.displayValue.split(this.multipleChoiceSeparator); vals.splice(removedIndex, 1); this.displayValue = vals.join(this.multipleChoiceSeparator); } if (this.mapFields) { this.updateOtherFieldDataWhenTagremoved(removedIndex); } this.tagRemoved.emit({ removedIndex, instance: this }); } private updateOtherFieldDataWhenTagremoved(removedIndex) { const helpFields = Object.keys(this.mapFields); const textFieldIndex = helpFields.indexOf(this.textField); if ( this.ngControl && this.ngControl.formDirective && this.ngControl.formDirective.form && this.ngControl.formDirective.form.bindingData ) { const bindingData = this.ngControl.formDirective.form.bindingData; if (bindingData.setValue) { const bindingPath = this.ngControl.formDirective.form.bindingPath; let pathArr: string[] = []; if (bindingPath) { pathArr = bindingPath.split("/").filter((n) => n !== ""); } helpFields.forEach((helpField: any) => { this.mapFields[helpField] .split(",") .forEach((formField: any) => { const fieldPaths = pathArr.concat( formField.split(".") ); const val = bindingData.getValue(fieldPaths); const valArr = val.split( this.multipleChoiceSeparator ); valArr.splice(removedIndex, 1); const newVal = valArr.join( this.multipleChoiceSeparator ); bindingData.setValue( pathArr.concat(fieldPaths), newVal, true, true ); }); }); } } else { if (this.bindingData) { if (textFieldIndex > -1) { helpFields.splice(textFieldIndex, 1); } helpFields.forEach((helpField: any) => { this.mapFields[helpField] .split(",") .forEach((formField: any) => { const val = this.utils.getValue( formField, this.bindingData ); const valArr = val.split( this.multipleChoiceSeparator ); valArr.splice(removedIndex, 1); const newVal = valArr.join( this.multipleChoiceSeparator ); this.utils.setValue( this.bindingData, formField, newVal ); }); }); } } } //#endregion onAllChildNodesClick($event: any) { this.isGetAllChidlNodes = !this.isGetAllChidlNodes; } }