Angular Custom Autocomplete Validation Implementation


<div class="form-group elasticResContainer">
  <label>User Name: </label>
  <input type="text" class="form-control" placeholder="Type Here" formControlName="userName" (keyup)="newEsearch($event)" (blur)="validateAutoComplete()">
  <span class="eLoader" *ngIf="eSearching"><i class="fas fa-circle-notch fa-spin"></i></span>
  <div class="elasticResDiv" *ngIf="showAutocompleteList">
	<ul class="list-group">
	  <li class="list-group-item" *ngFor="let user of eResults" (click)="eSelectUser(user)">{{}}</li>


I have made an autocomplete functionality in angular 9. Following describes my functionality implementation:

  1. I have a formControl named “userName”, on which there is an event attached on “keyup” called “newEsearch()”.
  2. User will enter a name or letter and according to that, userNamess will be searched through an API, which has been implemented.
  3. The API will return an array of users along with their IDs in an object called {id: number, name: string}.
  4. The array of results will be assigned to a variable called eResults, which eventually will render in the component through ngFor.
  5. I have to validate the autocomplete input element.
  6. Only the values present in the list(eResults) will be accepted otherwise rejected.
  7. So, I defined a function called eSelectUser() which will be called when I click any list item, which then patch the value in the formControl and removes the list from the DOM.
  8. If I don’t click any list item then, the value inside the userName formControl will be empty string or null and then removes the list from DOM, which I implemented in the validateAutoComplete().
  9. validateAutoComplete() will be called when input gets blurred.
  10. Everything works fine. I just finished the description of my implementation.


Now, my question is described as following:

The problem is, when I click any list item, the validateAutoComplete() gets called first because input gets blurred which eventually removes the list from the DOM.
And the eSelectUser() never gets called. How will I validate the input ?

Any help will be a great help.