import {Component, Input, OnChanges, OnDestroy, OnInit, SimpleChanges, ViewChild} from "@angular/core"; import {AbstractControl} from "@angular/forms"; import {HelperFunctions} from "../../utils/HelperFunctions.class"; import {Subscription} from "rxjs"; import {MatSelect} from "@angular/material/select"; export interface Option { icon?: string, iconClass?: string, value: any, label: string } @Component({ selector: '[dashboard-input]', template: `
{{label + (required ? ' *' : '')}}
{{hint}}
{{placeholder}} {{option.label}}
{{formControl.errors.error}} {{warning}} {{note}}
{{label}} `, styleUrls: ['input.component.css'] }) export class InputComponent implements OnInit, OnDestroy, OnChanges { @Input('formInput') formControl: AbstractControl; @Input('type') type: 'text' | 'textarea' | 'select' | 'checkbox' = 'text'; @Input('label') label: string; @Input('rows') rows: number = 3; @Input('options') options: Option[]; @Input('hint') hint = null; @Input('placeholder') placeholder = ''; @ViewChild('select') select: MatSelect; @Input() extraLeft: boolean = true; @Input() gridSmall: boolean = false; @Input() hideControl: boolean = false; @Input() icon: string = null; @Input() iconLeft: boolean = false; @Input() warning: string = null; @Input() note: string = null; public required: boolean = false; private initValue: any; private subscriptions: any[] = []; constructor() { } ngOnInit(): void { this.reset(); } ngOnChanges(changes: SimpleChanges) { if(changes.formControl) { this.reset(); } } reset() { this.unsubscribe(); this.initValue = HelperFunctions.copy(this.formControl.value); if (this.formControl && this.formControl.validator) { let validator = this.formControl.validator({} as AbstractControl); this.required = (validator && validator.required); } this.subscriptions.push(this.formControl.valueChanges.subscribe(value => { value = (value === '')?null:value; if(this.initValue === value || (this.initValue === '' && value === null)) { this.formControl.markAsPristine(); } })); if (!this.formControl.value) { this.formControl.setValue(''); } } unsubscribe() { this.subscriptions.forEach(subscription => { if(subscription instanceof Subscription) { subscription.unsubscribe(); } }); } openSelect() { if(this.select) { this.select.open(); } } ngOnDestroy(): void { this.unsubscribe(); } stopPropagation() { event.stopPropagation(); } }