MY CODE:
<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)">{{user.name}}</li>
</ul>
</div>
</div>
DESCRIPTION:
I have made an autocomplete functionality in angular 9. Following describes my functionality implementation:
- I have a formControl named “userName”, on which there is an event attached on “keyup” called “newEsearch()”.
- User will enter a name or letter and according to that, userNamess will be searched through an API, which has been implemented.
- The API will return an array of users along with their IDs in an object called {id: number, name: string}.
- The array of results will be assigned to a variable called eResults, which eventually will render in the component through ngFor.
- I have to validate the autocomplete input element.
- Only the values present in the list(eResults) will be accepted otherwise rejected.
- 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.
- 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().
- validateAutoComplete() will be called when input gets blurred.
- Everything works fine. I just finished the description of my implementation.
QUESTION:
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.