argos/dmp-frontend/src/app/form/dynamic-fields/dynamic-field-autocomplete/autocomplete-remote.compone...

96 lines
2.1 KiB
TypeScript

import { Field } from '../../../models/Field';
import { Component, OnInit, Input, Output, EventEmitter, forwardRef } from '@angular/core';
import { ControlValueAccessor, FormControl, FormGroup, NG_VALUE_ACCESSOR, Validators } from '@angular/forms';
import { ServerService } from '../../../services/server.service';
import { UUID } from 'angular2-uuid';
import { NguiAutoCompleteModule } from '@ngui/auto-complete';
declare var $: any;
@Component({
selector: 'df-autocomplete',
templateUrl: './autocomplete-remote.component.html',
styleUrls: ['./autocomplete-remote.component.css']
})
export class AutocompleteRemoteComponent implements OnInit/* , ControlValueAccessor */ {
@Input() field: Field;
@Input() form: FormGroup;
private textFormGroup = new FormGroup({text:new FormControl("")});
private loading: boolean;
values: any[] = new Array();
typeaheadMS: number = 1400;
constructor(private serverService: ServerService) {
}
ngOnInit() {
let valueChanges = this.textFormGroup.controls['text'].valueChanges.share();
valueChanges.subscribe(searchTerm => {
this.loading = true;
if (this.form.controls['text'].value)
this.resetFormGroupValue();
});
valueChanges
.debounceTime(this.typeaheadMS)
.subscribe(searchTerm => {
if (typeof searchTerm === 'string') {
this.updateByQuery(searchTerm)
}
});
}
resetFormGroupValue() {
this.form.patchValue({ value: null }, { emitEvent: false });
}
updateByQuery(query: string) {
this.serverService.getThroughProxy(this.field.data.url, query).subscribe(
response => {
this.values.length = 0;
response.data.forEach(element => {
this.values.push(element.attributes.name);
});
},
error => {
console.log(error);
}
);
}
onChange: any = () => { };
onTouched: any = () => { };
registerOnChange(fn) {
this.onChange = fn;
}
registerOnTouched(fn) {
this.onTouched = fn;
}
/* writeValue(value) {
if (value) {
this.value = value;
}
} */
}