import { Component, EventEmitter, inject, Input, OnInit, Output } from '@angular/core'; import { FormControl, ReactiveFormsModule } from '@angular/forms'; import { MatAutocompleteModule } from '@angular/material/autocomplete'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { ActivatedRoute } from '@angular/router'; import { Group } from '../../shared/models/group'; @Component({ selector: 'group-dropdown', imports: [ MatAutocompleteModule, MatFormFieldModule, MatInputModule, ReactiveFormsModule, ], templateUrl: './group-dropdown.component.html', styleUrl: './group-dropdown.component.scss' }) export class GroupDropdownComponent implements OnInit { private readonly route = inject(ActivatedRoute); @Input() formControl = new FormControl(undefined); @Input() errorMessages: { [errorKey: string]: string } = {}; @Input({ required: true }) groups: Group[] = []; @Input() group: string | undefined; @Input() groupDisabled: boolean | undefined; @Input() search: boolean = false; @Output() readonly groupChange = new EventEmitter(); errorMessageKeys: string[] = []; constructor() { this.route.data.subscribe(data => { if (!data['groups']) return; this.groups = data['groups']; }); if (this.groupDisabled) this.formControl.disable(); } ngOnInit(): void { this.errorMessageKeys = Object.keys(this.errorMessages); if (!this.group) return; const group = this.groups.find(r => r.id == this.group); this.formControl.setValue(group); } get filteredGroups() { const value = this.formControl.value; if (typeof value == 'string') { return this.groups.filter(r => r.name.toLowerCase().includes(value.toLowerCase())); } return this.groups; } select(event: Group) { this.groupChange.emit(event.id); } input() { if (this.search && typeof this.formControl.value == 'string') { this.groupChange.emit(this.formControl.value); } } blur() { if (!this.search && typeof this.formControl.value == 'string') { const name = this.formControl.value; const nameLower = name.toLowerCase(); let newValue: Group | undefined = undefined; const insenstiveGroups = this.filteredGroups.filter(a => a.name.toLowerCase() == nameLower); if (insenstiveGroups.length > 1) { const sensitiveGroup = insenstiveGroups.find(a => a.name == name); newValue = sensitiveGroup ?? undefined; } else if (insenstiveGroups.length == 1) { newValue = insenstiveGroups[0]; } if (newValue) { this.formControl.setValue(newValue); //this.groupChange.emit(newValue.name); } else if (!newValue) this.formControl.setValue(undefined); //this.groupChange.emit(undefined); } } displayFn(value: Group) { return value?.name; } }