import {Component, OnInit, OnChanges, Input} from '@angular/core'; import {FormControl, Validators} from '@angular/forms'; import {InputUnitOptions} from './InputUnitOptions'; import {Defaults} from '../../../constant/defaults.constant'; import {Helper} from '../../../helper'; @Component({ selector: 'rss-input-unit', templateUrl: './input-unit.component.html', styleUrls: ['./input-unit.component.scss'] }) export class InputUnitComponent implements OnInit, OnChanges { @Input() control: FormControl; @Input() config: any; @Input() inputConfig: any; @Input() label: any; @Input() options: any; @Input() type: string = Defaults.INPUT_TYPE; @Input() placeholder: string = Defaults.PLACEHOLDER; @Input() required: boolean = Defaults.REQUIRED; @Input() requiredError: string = Defaults.REQUIRED_ERROR_MESSAGE; @Input() readonly: Boolean; @Input() url: string; emptyResponseMsg = Defaults.EMPTY_RESPONSE_MSG; inputControl: FormControl = new FormControl(); dropdownControl: FormControl = new FormControl(); constructor() { } ngOnInit() { if (this.config) { this.label = this.config.label; const temp = this.label; this.config.label = undefined; this.inputConfig = new InputUnitOptions(this.config); this.inputConfig.required = Defaults.REQUIRED; Helper.merge(this, this.inputConfig); this.config.label = temp; this.required = this.config.required; } if (!this.control) { console.error(Defaults.MISSING_FORM_CONTROL_ERROR_MESSAGE); } else { if (this.required) { this.control.setValidators(Validators.required); } } // Edit mode if (this.control && this.control.value && this.control.value.inputText) { this.inputControl.setValue(this.control.value.inputText); } if (this.control && this.control.value && this.control.value.units) { this.dropdownControl.setValue(this.control.value.units); } // Composite output from two different controls is attached to the input control this.inputControl.valueChanges.subscribe(() => this.control.setValue(Object.assign({}, this.control.value, {inputText: this.inputControl.value}))); this.dropdownControl.valueChanges.subscribe(() => this.control.setValue(Object.assign({}, this.control.value, {units: this.dropdownControl.value}))); } ngOnChanges() { if (this.control && !this.control.value) { this.inputControl.patchValue(''); this.dropdownControl = new FormControl(); this.dropdownControl.valueChanges.subscribe(() => this.control.setValue(Object.assign({}, this.control.value, {units: this.dropdownControl.value}))); } } valueOfInputUnit() { return Helper.valueOfInputUnit(this.control.value); } displayRequiredError(fc: FormControl) { if (this.required) { if (this.dropdownControl.value || this.inputControl.value) { this.control.markAsTouched({onlySelf: true}); } const validator = fc ? (this.control.touched && !this.inputControl.value) || (this.control.touched && !this.dropdownControl.value) : false; if (validator) { this.control.setErrors(Validators.required); } return validator; } } }