So I'm trying to build an "autocomplete" directive for a project that will query the API and display a list of results to select from. I have a component that displays a modal with a simple input box. I need to be able to type into the box to search Members, click on a member and add that to an array in the component.
Edit:
The issue I'm having is that when I call this.wlAutocomplete.next(value);, it goes back into my component and makes the API call with the correct value from the input field, it doesn't return the data back to the directive to handle the response from the API there.
StackBlitz Example: https://stackblitz.com/edit/angular-11erew
The Component will track the array of selected members. I need to be able to:
- Call my API in the Component to get the data and return to the directive
- The directive will need to read the data and display a list below the input box (I can do the HTML here)
- Clicking a list item in the dropdown will send that selection back to the component to handle as it needs, eg. add it to an array.
My component has a method:
queryMembers(value: string): Subscription {
return this.memberService.query({ term: value, groupKey: this.group.groupKey })
.subscribe((members) => {
console.log(members);
return this.searchMemberList = members;
});
}
Which I'm using in the template like this:
<input (wlAutocomplete)="queryMembers($event)" class="uk-search-input" type="search" placeholder="Search...">
Here 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); // I need to get the data from component method passed into `wlAutocomplete`
});
}
@Output() wlAutocomplete: EventEmitter<any> = new EventEmitter();
@HostListener('input', ['$event'])
onChange($event) {
this.modelChanged.next($event.target.value);
}
}