I have been diving into Angular 4 and working on an autocomplete application.
HTML:
<form novalidate [formGroup] ="formG">
<input type="text" formGroupName="formCont" id="searText" class="searchBox">
</form>
<div class="seracDropDown" *ngIf = "showDropDown">
</div>
AppComponent:
import { Component, HostListener, ElementRef } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: "app-root",
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private _el: ElementRef)
{ }
showDropDown: boolean = false;
formG = new FormGroup({
formCont: new FormControl()
})
@HostListener('click', ['$event.target'])
onClickCalled(target) {
if (target.id == "searText") {
this.showDropDown = true;
}
else {
this.showDropDown = false;
}
}
@HostListener("keyup", ['$event'])
onKeyUp(ev) {
var str: string;
if (ev.target.id == "searText") {
str = this._el.nativeElement.value;
console.log(str);
}
}
}
When clicking in the textbox
, a dropdown
appears which should disappear when clicking anywhere else on the document. This behavior is handled by the click hostlistener
, and the keyup
hostlistener
monitors the value entered in the textbox
. However, I am encountering two issues.
1) The dropdown
does not close when clicking anywhere other than the textbox
.
2) When entering a value in the text box, console.log(str);
prints undefined
.
Any assistance or guidance would be greatly appreciated.