sona mondal
sona mondal

Reputation: 69

Hostlistener giving wrong values of nativeelement.value and click event

I am learning Angular 4 and creating 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);
    }
  }
}

So if clicked in the textbox a dropdown will come which will go away clicking on anywhere on the document. Which is handled by the click hostlistener and the keyup hostlistener is for the value entered in the textbox , Now I am facing two issues.

1) On clicking in the textbox is showing but on clicking anywhere else it's not closing.

2) On entering any value in the text box console.log(str); prints undefined.

Any help would be appreciated

Upvotes: 1

Views: 1054

Answers (1)

coder
coder

Reputation: 8712

Instead of click use document:click and use ev.target.value instead of this._el.nativeElement.value.

Use them like following way:

  @HostListener('document: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 = ev.target.value;
      console.log(str);
    }
  }

WORKING DEMO

Hope this will help you!

Upvotes: 1

Related Questions