Issue with Hostlistener causing incorrect values for nativeelement.value and click events

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.

Answer №1

Replace the use of click with document:click, and utilize ev.target.value instead of this._el.nativeElement.value.

Implement them as shown below:

  @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);
    }
  }

VIEW WORKING DEMO

We trust this information proves valuable to you!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Determining when it is necessary to loop over a variable

I'm facing a situation where I have two different responses based on whether we need to loop over an object or just display a variable. My attempted solution involved using ng-if else, but unfortunately, it didn't work as expected. This is the ...

Automatically select the default value in mat-select if the array contains only one element, otherwise, populate the dropdown

I am facing a situation where I need to handle a select dropdown list (classification array). If the select list contains multiple values, it should be displayed as a dropdown. However, if there is only one element in the array, it should be automatically ...

Typescript error TS2345: The argument 'Buffer' cannot be passed as a 'string' parameter

I'm currently retrieving data from a RabbitMQ channel and converting it into a JSON object. However, I've encountered an issue at this specific line of code. let communicationInformation = JSON.parse(newCommunication.content); The error message ...

The downloaded zip file appears to be corrupt and cannot be opened

As a newcomer to TypeScript, I embarked on creating a simple function to download a zip file. This is the code I've managed to put together: import fs from 'fs'; import https from 'https'; export function handler(): void { https ...

Having difficulty implementing Angular 4 redirection for transitioning from old hash URLs to new non-hash URLs

In our single page application, we originally had a simple tab structure where each tab click led to a corresponding #url. Examples: , After transitioning to Angular 4, the urls no longer contain hash symbols. They now look like this: , I have added the ...

Unable to pass parameters through the URL in Angular's POST request

Hey there! I'm currently facing an issue with passing a parameter in the POST method URL within an Angular service to construct a URL for fetching data from an API. However, when I try calling it in the component file, I keep getting an error response ...

Guide to showing a form following a button click in Angular 9

I am trying to create a feature on my page where when I click a button, a form will appear directly below it. Additionally, I would like the number of forms displayed to match the number of times the button is clicked. Being a newcomer to Angular 9, I am ...

Prevent deep linking in Ionic 3 by disabling URLs

I need assistance with a current project in Ionic 3. We are looking to disable URL deep linking, but I am unsure of the proper steps to take. Any guidance on how this can be achieved would be greatly appreciated. ...

Implementing role-based authentication in Angular using jwtHelper for accessing the admin component

I have built a frontend using Angular 6 and I am trying to implement role-based authorization using JWT helper-service. However, I am facing an issue where I am unable to access the admin component even though I have the necessary authorization. Below is ...

Tips on filtering an array in a JSON response based on certain conditions in Angular 7

Looking to extract a specific array from a JSON response based on mismatched dataIDs and parentDataIDs using TypeScript in Angular 7. { "data":[ { "dataId":"Atlanta", "parentDataId":"America" }, { "dataId":"Newyork", ...

The '&&' operator cannot be used with method groups in the tst file

I am currently facing an issue while trying to verify a condition in the tst (typescript generator) file within my C# application. The error message I am encountering states that the Operator '&&' cannot be applied to operands of type 'metho ...

Creating an Angular 8 build that can be executed from a subdirectory

As I develop using the standard localhost:4200, I also want to understand how a build works. To achieve this, I made some modifications in the angular.json file. The alteration is as follows: "outputPath": "D:/a_root/dist", The 'a_root' represe ...

Encountering an error in the WebStorm 2017.1.1 editor

My current editor is WebStorm 2017.1.1 and everything seems to be working fine in terms of output. The issue I'm facing is that the editor keeps displaying red syntax errors, even though I can't pinpoint what's causing it or which plugin ne ...

The module "node_modules/puppeteer/lib/types" does not contain the export "Cookie"

Currently facing an issue with puppeteer types. I am attempting to import the Cookie type, but it seems to be not functioning on versions above 6.0.0. import { Cookie } from 'puppeteer'; Here is the error message: /node_modules/puppeteer/lib/typ ...

Is it possible to generate type definitions for inner classes?

I'm currently exploring the usage of TypeScript within a Salesforce project involving RemoteObject One challenge I'm facing is creating typings for the external JavaScript object syntax. For example, in JavaScript: var ct = new RemoteObjectMod ...

A mistake was made: The template contains errors stating that 'app-my-profile' is an unknown element

I encountered an error message: "Uncaught Error: Template parse errors: 'app-my-profile' is not a known element," while working on setting up my profile service. import { BrowserModule } from '@angular/platform-browser'; import { NgM ...

Why aren't the validations being set when creating Angular forms using formControl.values?

I had to structure the form in a specific way in my app.ts file -> courseNameControl = new FormControl("", [Validators.required,Validators.minLength(2)]); contentControl = new FormControl("", Validators.required); form = { cours ...

How can I set the default bindLabel for a dropdown in @ng-select/ng-select when the self change event occurs in Angular

I have a scenario where I need to set the default value to null in the ng-select. If the user selects an option from the dropdown first, then on the change event it should check if the Amount model is not null or blank. If the Amount model is blank, then ...

When conducting TS code scanning, errors may not be returned, but TSLint will provide a comprehensive list

Experiencing an unusual issue - SonarQube is running for TS sources but not returning any errors. Utilizing the SonarTS plugin results in SonarQube reporting 0% errors. Any thoughts on what might be causing this? Thank you. The sonar-project.properties fi ...

JavaScript: Remove duplicate values from one array by comparing and utilizing a search filter against another array

There are two arrays available: public favoriteTeams: any[] = [ { name: 'Team Batman' }, { name: 'Team Superman' }, { name: 'Team Darkseid' }, { name: 'Team Wonder Woman' } ]; public searchTeams: any[] = [ ...