import { Component, OnInit, OnChanges, Input } from '@angular/core'; import { FormControl, Validators } from '@angular/forms'; import { DropdownOptions } from './DropdownOptions'; import { Defaults } from '../../constant/defaults.constant'; import { Helper } from '../../helper'; import { QueryService } from '../../service/query.service'; @Component({ selector: 'rss-dropdown', templateUrl: './dropdown.component.html', styleUrls: ['./dropdown.component.scss'] }) export class DropdownComponent implements OnInit, OnChanges { @Input() config: DropdownOptions; @Input() control: FormControl; @Input() readonly: Boolean; @Input() multiple: Boolean; @Input() label: string; @Input() options: any; @Input() displayKey: string = 'label'; @Input() valueKey: string = 'value'; @Input() required: boolean = Defaults.REQUIRED; @Input() requiredError: string = Defaults.REQUIRED_ERROR_MESSAGE; @Input() placeholder = Defaults.PLACEHOLDER; @Input() url: string; selectControl: FormControl = new FormControl(); readonlyDisplayValue: string; emptyResponseMsg = Defaults.EMPTY_RESPONSE_MSG; constructor(private queryService: QueryService) { } ngOnInit() { if (this.config) { const config = new DropdownOptions(this.config); Helper.merge(this, config); } this.initializeControl(); } ngOnChanges() { this.initializeControl(); } initializeControl() { if (!this.readonly) { this.selectControl.valueChanges.subscribe(() => { let value = null; if (this.options && this.selectControl.value) { if (this.multiple) { value = this.options.filter(option => this.selectControl.value.includes(option[this.valueKey])); } else { value = this.options.find(option => this.selectControl.value === option[this.valueKey]); } } this.control.setValue(value); }); if (this.required) { this.control.setValidators(Validators.required); } if (this.url) { this.queryService.query(this.url).subscribe(options => this.updateControl(options)); } else { this.updateControl(this.options); } } else { if(this.control.value) { this.readonlyDisplayValue = Array.isArray(this.control.value) ? this.control.value.map(option => option[this.displayKey]).join(', ') : this.control.value[this.displayKey]; } } } updateControl(options) { this.options = options && options.length ? options : null; let value = null; if (this.options && this.control.value) { if (this.multiple) { value = Array.isArray(this.control.value) ? this.control.value.map(option => option[this.valueKey]) : [this.control.value[this.valueKey]]; } else { value = Array.isArray(this.control.value) ? this.control.value[0][this.valueKey] : this.control.value[this.valueKey]; } } this.selectControl.setValue(value); } displayRequiredError(fc: FormControl) { return fc ? this.control.touched && (this.control.status === 'INVALID') : false; } }