From ead64cdf8d917fa0d6a20271e42378f38e5f2407 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Tue, 9 Feb 2021 16:35:48 +0100 Subject: Support custom value in ng-select --- .../select/select-custom-value.component.ts | 76 ++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 client/src/app/shared/shared-forms/select/select-custom-value.component.ts (limited to 'client/src/app/shared/shared-forms/select/select-custom-value.component.ts') diff --git a/client/src/app/shared/shared-forms/select/select-custom-value.component.ts b/client/src/app/shared/shared-forms/select/select-custom-value.component.ts new file mode 100644 index 000000000..a8e5ad0d3 --- /dev/null +++ b/client/src/app/shared/shared-forms/select/select-custom-value.component.ts @@ -0,0 +1,76 @@ +import { Component, forwardRef, Input, OnChanges } from '@angular/core' +import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms' +import { SelectOptionsItem } from './select-options.component' + +@Component({ + selector: 'my-select-custom-value', + styleUrls: [ './select-shared.component.scss' ], + templateUrl: './select-custom-value.component.html', + providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => SelectCustomValueComponent), + multi: true + } + ] +}) +export class SelectCustomValueComponent implements ControlValueAccessor, OnChanges { + @Input() items: SelectOptionsItem[] = [] + @Input() clearable = false + @Input() searchable = false + @Input() groupBy: string + @Input() labelForId: string + + customValue: number | string = '' + selectedId: number | string + + itemsWithCustom: SelectOptionsItem[] = [] + + ngOnChanges () { + this.itemsWithCustom = this.getItems() + } + + propagateChange = (_: any) => { /* empty */ } + + writeValue (id: number | string) { + this.selectedId = id + + if (this.isSelectedIdInItems() !== true) { + this.selectedId = 'other' + this.customValue = id + } + } + + registerOnChange (fn: (_: any) => void) { + this.propagateChange = fn + } + + registerOnTouched () { + // Unused + } + + onModelChange () { + if (this.selectedId === 'other') { + return this.propagateChange(this.customValue) + } + + return this.propagateChange(this.selectedId) + } + + isSelectedIdInItems () { + return !!this.items.find(i => i.id === this.selectedId) + } + + getItems () { + const other: SelectOptionsItem = { + id: 'other', + label: $localize`Custom value...` + } + + return this.items.concat([ other ]) + } + + isCustomValue () { + return this.selectedId === 'other' + } +} -- cgit v1.2.3