Currently, I am in the process of creating an "autocomplete" directive for a project. The aim is to have the directive query the API and present a list of results for selection. A component with a modal containing a simple input box has been set up. The objective is to search for Members by typing into the input box, selecting a member, and adding them to an array within the component.
Edit:
An issue that has arisen is when I invoke this.wlAutocomplete.next(value);
, it triggers the API call correctly using the value from the input field within my component. However, the returned data does not go back to the directive for handling the response from the API.
StackBlitz Example: https://stackblitz.com/edit/angular-11erew
The Component monitors the array of selected members. Here are the requirements:
- Initiate the API call in the Component, fetch the data, and return it to the directive
- The directive should parse the data and display a list beneath the input box (HTML implementation can be done here)
- Upon clicking on an item in the dropdown list, send that choice back to the component for necessary actions, such as adding it to an array.
The following method exists in my component:
queryMembers(value: string): Subscription {
return this.memberService.query({ term: value, groupKey: this.group.groupKey })
.subscribe((members) => {
console.log(members);
return this.searchMemberList = members;
});
}
Utilizing the method in the template looks like this:
<input (wlAutocomplete)="queryMembers($event)" class="uk-search-input" type="search" placeholder="Search...">
Below is the code for the Directive:
@Directive({
selector: 'input[wlAutocomplete]'
})
export class AutocompleteDirective {
modelChanged: Subject<string> = new Subject<string>();
subscription: Subscription;
debounce: number = 500;
constructor() {
this.subscription =
this.modelChanged
.pipe(debounceTime(this.debounce))
.subscribe(value => {
this.wlAutocomplete.next(value); // Data needs to be passed from the component method into `wlAutocomplete`
});
}
@Output() wlAutocomplete: EventEmitter<any> = new EventEmitter();
@HostListener('input', ['$event'])
onChange($event) {
this.modelChanged.next($event.target.value);
}
}