How to detect a click event in any area of an Angular2

Hey there, I'm new to typescript and angular 2 and I've encountered an error in my code. Can someone lend me a hand in fixing this?

import { Component, HostListener } from '@angular/core'  
export class TooltipComponent {
    public show: boolean = false;

    @HostListener('document:click',['$event'])    

    documentClick(event: MouseEvent) {
        this.show = false;    
    }

    showTooltip() {
        this.show = true;
        this.documentClick('????');    
    }
}

Answer №1

  @HostListener('document:click', ['$event'])
  public handleDocumentClick(event: Event): void {
    //performAction() --> Your custom logic for handling document clicks
  }

The question may be a bit ambiguous, but the code provided will execute when a click event occurs on the document.

Answer №2

Here is an alternative method to register a listener on the DOCUMENT (check out this Plunker example):

import {Component, Inject, OnInit, HostListener, VERSION} from '@angular/core';
import { DOCUMENT } from "@angular/platform-browser";

@Component({
  selector: 'demo-app',
  template: `
    <div>
      {{ text }}
    </div>
  `
})
export default class DemoAppComponent implements OnInit{

  public text: string
  public show: boolean

  //constructor
  constructor(@Inject(DOCUMENT) private document: Document) {

    document.addEventListener('click', this.onDocument1Click);
    this.text =  "Angular " + VERSION.full
  }

  //init
  ngOnInit() { }

  onDocument1Click(){
    this.show = !this.show
    alert(this.show)
  }


  //add hostlistner on document:click
  //@HostListener("document:click", ['$event'])
  //onDocumentClick(event: Event): void {
  //  this.show = !this.show
  //  alert(this.show)
  //}

}

Answer №3

Perhaps you could consider creating a fresh component, specifying a host property within it, and incorporating other components

An alternative is to utilize the (document:click) event:

@Component({
  host: {
    '(document:click)': 'onClick($event)',
  },
})
class AnotherComponent() {
  constructor(private _eref: ElementRef) { }

  onClick(event) {
     // Your implementation goes here...
  }
}

Answer №4

Here is the corrected version:

import {ChangeDetectorRef, Renderer } from '@angular/core';

export class TooltipComponent {

    public isVisible: boolean = false;

    clickHandler: Function;

    constructor(
        private elementReference: ElementRef,
        private renderService: Renderer,
    ) {
        this.clickHandler = renderService.listenGlobal(
            'document',
            'click',
            (event: MouseEvent) => this.handleDocumentClick(event)
        );
    }

    handleDocumentClick(event: MouseEvent) {
        console.log(event.target);
        if (!this.elementReference.nativeElement.contains(event.target)) {
            this.isVisible = false;
        }
    }
}

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

Retrieve data from a specific page on a URL using AJAX

window.onload= function(){ var page = window.location.hash; if(window.location.hash != ""){ page = page.replace('#page:', ''); getdata('src/'.page); } } Once the window has loaded, I want to check ...

Attach an event listener to the HTML content

Being new to Javascript, I am attempting to add an event listener for each button on every card. However, the code seems to only apply the event 'click' to the last card (button). Is there a way to make this work with the innerHTML of the card? l ...

Prevent the Mat Dialog from showing up depending on the situation

I am attempting to prevent a Mat Dialog from appearing unless a specific condition is met. I originally thought about using Angular Guard, but since there is no associated route with the component (besides the main webpage it's called from), that appr ...

The server has sent cookies headers, however, the browser did not store the cookies

I need assistance in understanding why browsers such as Chrome are not setting cookies, even though the Set-Cookie header is present in the Response Headers: Access-Control-Allow-Origin: * Connection: keep-alive Content-Length: 345 Content-Type: applicati ...

No routes found to match. URL Segment: ''. This issue occurs when attempting to utilize child routes with Angular 2

I am having issues with this specific plunker that seems to not be working correctly. To try and fix the problem, I attempted to comment out a section of code... RouterModule.forRoot([ { path: "", component: TestComponent, ...

The index declaration file has not been uploaded to NPM

After creating a Typescript package and publishing it on NPM, I encountered an issue with the declaration files not being included in the published version. Despite setting declaration: true in the tsconfig.json, only the JavaScript files were being publis ...

The issue you're encountering in React Native Expo is a restriction where Hooks can only be invoked within the body of a function

I'm currently working on a mobile app with React Native expo, but I've encountered an issue: Invalid hook call. Hooks can only be called inside the body of a function component.... I have checked other solutions on Stack Overflow and verified th ...

What is the best way to run tests on this method using Jest?

import { format, getDaysInMonth, getMonth, getYear, isValid, parse } from "date-fns"; export class DateService { public getDaysInMonth(month?: Date) { return getDaysInMonth(month || new Date()); } What is the best way to test this func ...

React's constructor being invoked twice

As a newcomer to react, I am in the process of developing a simple web application but encountering an issue. It seems like my Constructor is being called twice when I load a class component. Can anyone provide some assistance? Home.js import React from ...

jquery unable to retrieve element

I have implemented a piece of code that adds the 'nav-pills' class to an element with the class 'nav-tabs' when the window width is less than 768px. $(window).on('resize', function () { $('.nav-tabs').toggleClass(&a ...

The 'ReactNode' binding element is automatically assigned an 'any' type

Just started a new project using create-react-app app --template typescript. In the src/components/MyButton/MyButton.tsx file, I have the following code: import React, { ReactNode } from "react"; const MyButton = ({ children: ReactNode }) => ...

Why is my Javascript XMLHttpRequest onreadystatechanged event not triggering?

I am facing an issue with my html file and a .txt file stored in the same directory on a webserver. In the html file, I have the following code: <html> <head> <script> window.onload = function() { receiveMessage(); } function recei ...

Why would someone opt to utilize process.env.PORT in their code?

Setting the environment variable PORT to a specific value, such as set PORT=5000, provides explicit instructions on which port the program should use. How does this method differ from simply instructing it to use port 3000? ...

The functionality of two-way binding in a distinct controller is not functioning properly when integrated with angular-wizard

I've been working hard to integrate this amazing wizard controller into my project: However, I've hit a roadblock with two-way binding not functioning as expected outside of the <section> attribute: http://plnkr.co/edit/N2lFrBRmRqPkHhUBfn ...

The issue persists with the $slice function in MongoDb

I am attempting to retrieve records using an aggregate function in MongoDB, but I keep encountering the error message stating that the operator $slice is invalid: db.getCollection('test').aggregate( [ { $match: { 'subjectId': &apos ...

Encountering an issue in Angular 8 flex-layout 8: Unable to export member ɵNgClassImpl

I encountered an issue while trying to install flex-layout 8.0.0-beta.26 in my Angular 8 project. The error I received during the build process is as follows: ERROR in node_modules/@angular/flex-layout/extended/typings/class/class.d.ts(9,19): error TS2305 ...

Steps for Loading HTML5 Video Element in Ionic 2

Struggling to showcase a list of videos from my server, here's the issue I'm encountering and the layout of the app. https://i.stack.imgur.com/HWVt3.png This is the code snippet in HTML: <ion-list> <button ion-item *ngFor="let v ...

JavaScript's GET method fails to retrieve the complete JSON file

I am facing an issue with a substantial JSON file that my JavaScript code is unable to pull in entirely. When I check the Network tab in Firefox developer tools, it shows that the data stops at around line 57,301 out of 528,342 lines in the JSON file. Ini ...

Symfony2 and asynchronous JavaScript and XML (AJAX)

Is there a way to perform asynchronous actions in Symfony2 without having to refresh the page? I haven't been able to find any information about this in the official "Book" or "Cookbook". (The only mention I came across was 2 sentences about hinclude. ...

Compiling Vue.js without the need for a build tool

Vue.js is the framework I've chosen for my PHP + JS application, and I'm using the full build of Vue by directly including it via a script tag without any build tool. I'm now wondering how I can pre-compile my templates without relying on b ...