Step-by-step Guide to Setting Up Angular 2 click-outside Dependency

Greetings everyone, I'm currently attempting to initiate a clickOutside event in my application. When the variable show == true, a div is displayed, but I encounter trouble hiding it again upon clicking anywhere else. Therefore, I decided to implement the clickOutside functionality.

I referenced the following command from this resource: angular2-click-outside

npm i angular2-click-outside

Here is an excerpt from my component:

<div class="row hidden_one" (clickOutside)="close()">

This snippet showcases my HTML structure:

<div class="container-fluid">
  <div class="row wrapper">
  <div class="col-lg-8 col-md-8 col-sm-9 first">
  <input type="text" class="form-control title" placeholder="{{placeholder}}" #task>
</div>
<div class="col-lg-4 col-md-4 col-sm-3 second hiddden">
  <div class="row">
    <div class="col-lg-8 col-md-8 col-sm-8 col-xs-8">
      <input type="text" class="form-control right" value="00:00:00" (click)="showdiv()" [(ngModel)]="timer" #time>
    </div>
    <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4 font">
      <i class="fa fa-play-circle fa-3x first" aria-hidden="true" *ngIf="play" (click)="startPause()"></i>
      <i class="fa fa-stop-circle fa-3x second" aria-hidden="true" *ngIf="pause" (click)="startPlay(task.value, time.value)"></i>
    </div>
  </div>
  <div class="row hidden_one" (clickOutside)="close()">
    <div class="start-end" *ngIf="show" (clickOutside)="hide($event)">
      <div class="col-lg-6">
        <div class="form-group">
          <label for="Start">Start</label><br>
          <input type="text" class="form-control" class="startTime" value="{{startTime}}" #val (blur)="validate(val.value)">
        </div>
      </div>
      <div class="col-lg-6">
        <div class="form-group">
          <label for="Start">Stop</label><br>
          <input type="text" class="form-control" class="startTime" [(ngModel)]="stopTime" [disabled]="pause">
        </div>
      </div>
    </div>
  </div>
</div>

Lastly, here's the TypeScript code utilized:

import { Component } from '@angular/core';
import { timeInterface } from './timeInterface';
import { timesList } from './times-list-component';
import { TimeService } from './time-service';
import * as moment from 'moment';

@Component({
 selector: 'my-app',
 templateUrl: './html/app-component.html',
 styleUrls: ['./css/app-component.css']

})

export class AppComponent  { 
   // Code snippets and functions defined within the TypeScript are shown here.
}

Upon console logging, there doesn't seem to be any output suggesting that the event isn't functioning correctly. Any assistance would be greatly appreciated. Thank you in advance.

Answer №1

Even though it may be a bit delayed, ensure you include the ClickOutsideModule dependency in the imports array of your component's module.ts file to get things up and running smoothly.

Remember to also add it to your package.json file (for example, "ng-click-outside": "^5.1.1") or install it directly using npm.

npm install --save ng-click-outside

Answer №2

Ensure you pass an event parameter in the following manner:

<div class="row hidden_one" (clickOutside)="onClickOutside($event)">

Then, in your JS file, add the following method:

onClickOutside(event:Object) {
    alert('this is working');
}

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

The Number.toLocaleString function does not work properly in the pt-BR locale when tested in

A function named toCurrency has been created for converting strings or numbers to locale-specific formats: function toCurrency( value: string | number, locale: string = "en-US", currency: string = "USD", options?: Intl.N ...

Using Angular to Apply a Custom Validation Condition on a FormGroup Nested Within Another FormGroup

I am facing an issue with my form validation logic. I have a set of checkboxes that need to be validated only when a specific value is selected from a dropdown. The current validator checks the checkboxes regardless of the dropdown value. Here's the c ...

JavaScript Error: Cannot read property 'b' of undefined

Whenever I attempt to establish inheritance in TypeScript, the following JavaScript code is generated: var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constr ...

Retrieve all Tableau workbooks stored on the server

I am currently working with Tableau Server and have multiple workbooks published on it. My goal is to create a dropdown list that displays all the workbook names along with their corresponding URLs. This way, when a user selects a value from the dropdown, ...

Various modules in the project need to have distinct GitHub origins, particularly in the case of Spring-Angular

My goal is to create a well-structured project with separate frontend and backend modules. Here is the initial project structure: https://i.stack.imgur.com/EghPA.png I have attempted this in various configurations before, but every time I try, git recogn ...

Is there a way to adjust the background color of the clicked tab with divs and revert the others back to their original color?

<span class="row top-bar-left align-items-center" style="width: 80%; float:left"> <div tabindex="1" class="link tab" routerLink="details" routerLinkActive="active" [qu ...

Unable to access structuredClone on the global object within a Node.js application

structuredClone is causing issues in my NodeJS application. Whenever I try to utilize it, I encounter the error: structuredClone is not defined nodejs. To troubleshoot, I created a simple file and executed the following: console.log({ globals: Object. ...

The latest version of IntelliJ Idea Ultimate, 2023.2.5, does not offer compatibility with the updated control flow features in Angular

I recently made the switch to Angular 17 in my project and noticed that Idea is not recognizing the new syntax in HTML templates. <mat-menu #menu="matMenu"> @for (menuItem of getData().menu.items; track menuItem) { & ...

ESLint's no-unused-vars rule is triggered when Typescript object destructuring is employed

I'm encountering an issue with my Typescript code where I am destructuring an object to extract a partial object, but it's failing the linter check. Here is the problematic code snippet: async someFunction(username: string): Promise<UserDTO> ...

What is the best method for obtaining user data when additional custom data is stored in Cloud Firestore?

Storing the user's information such as email, name, age, phone number, and uid is essential. In the user.model.ts file: export interface User { uid: string, name: string, email: string, phoneNumber: string, age: string } In auth. ...

Creating a mat-tree component in Angular Material 6.0.1: Step-by-step guide

I am encountering an issue with my material angular mat-tree based application. The code runs without errors, but the values are not displayed on the screen. I need help resolving this problem so that I can proceed with the development. Upon opening the a ...

Using IONIC and NGRX to initialize state from an indexed database

In my current project, I am developing an Ionic application with Angular. To ensure that the state remains persistent even after restarting the app, I decided to utilize the @ionic/storage-angular plugin. This plugin allows me to save the current state and ...

Pass a ng-template as a parameter to a component

When using PrimeNG Table, it allows for the use of body and header templates to customize how the table is rendered. I recently developed a component that encapsulates the PrimeNG table functionality. My question is, how can I successfully pass an ng-tem ...

Issue found: functions within pipe operation in fp-ts are being skipped

I've recently started delving into function programming and encountered some unexpected behavior. I'm facing an issue where a function containing a tryCatch isn't being called within a pipe function for fp-ts. Despite reaching the next line ...

Ways to transfer a value from an HTML element to be accessed by other functions within a TypeScript component

I am facing an issue where I have a dropdown menu, and I need to pass the ID of the selected value ($event.target.value) to other functions in different components. <div class="dropdown ml-auto"> <select (change)=getSelectedVariantProject($ ...

Guidelines for deploying an Angular production build to an external server using Bitbucket pipeline with an SSH key

We are currently exploring the use of Bitbucket Pipelines to automate the deployment of a simple Angular application to a virtual machine hosted on Google Cloud. However, we are facing challenges in establishing an SSH connection to the server in order to ...

Using conditional statements to localize in Angular

In my Angular application, I am utilizing i18n for internationalization purposes. When it comes to HTML, I use i18n="@@<unique_Id>" and for dynamic elements defined in TypeScript class files, I use $localize. For example: this.buttontext = ...

Issue with asynchronous function: "Cannot assign type 'Promise<MyType[]>[]' to type 'MyType[]'"

After converting this function to async, I've been encountering issues with type annotations being out of sync: export default async function formatCallRecordsForPGPromise( rawCalldata: CallRecord[], ): Promise<SaveableCallRecord[]> { const ...

The issue of data being duplicated when clicking on react-cookie-consent

Currently, I am utilizing the npm package https://www.npmjs.com/package/react-cookie-consent to implement a cookies consent feature in my react TypeScript application. However, I have encountered two issues with this package. Firstly, upon clicking the acc ...

What is the process for calling a recursive constructor in TypeScript?

I am working on a class constructor overload where I need to recursively invoke the constructor based on the provided arguments. class Matrix { /** * Construct a new Matrix using the given entries. * @param arr the matrix entries */ ...