Files

60 lines
2.2 KiB
TypeScript

import {Component, EventEmitter, Input, OnInit, Output} from "@angular/core";
import {MatFormField, MatInput} from "@angular/material/input";
import {FormControl, ReactiveFormsModule} from "@angular/forms";
import {MatAutocompleteModule, MatAutocompleteSelectedEvent} from "@angular/material/autocomplete";
import {AsyncPipe} from "@angular/common";
import {map, Observable, startWith} from "rxjs";
import {LoadingIndicatorComponent} from "@component/common/loading-indicator/loading-indicator.component";
import {ProfessorResponse} from "@api/v1/professorResponse";
@Component({
selector: 'app-professor',
standalone: true,
imports: [
MatAutocompleteModule,
MatFormField,
AsyncPipe,
ReactiveFormsModule,
MatInput,
LoadingIndicatorComponent
],
templateUrl: './professor.component.html',
styleUrl: './professor.component.css'
})
export class ProfessorComponent implements OnInit {
protected professorControl = new FormControl();
protected filteredProfessors!: Observable<ProfessorResponse[]>;
@Input() professors: ProfessorResponse[] = [];
@Output() professorSelected = new EventEmitter<number>();
@Input() professorsLoaded: boolean | null = false;
@Output() professorsLoadRetry: EventEmitter<void> = new EventEmitter<void>();
ngOnInit(): void {
this.filteredProfessors = this.professorControl.valueChanges.pipe(
startWith(''),
map(value => this._filterProfessors(value))
);
}
private _filterProfessors(value: string | number): ProfessorResponse[] {
if (typeof value === 'string') {
if (value === '') return [];
const filterValue = value.toLowerCase();
return this.professors.filter(teacher => teacher.name.toLowerCase().includes(filterValue));
} else {
const selectedTeacher = this.professors.find(teacher => teacher.id === value);
return selectedTeacher ? [selectedTeacher] : [];
}
}
protected onOptionSelected(event: MatAutocompleteSelectedEvent) {
const selectedOption = this.professors.find(teacher => teacher.id === event.option.value);
if (selectedOption) {
this.professorControl.setValue(selectedOption.name);
this.professorSelected.emit(selectedOption.id);
}
}
}