Ways to avoid triggering a button's click event

Creating a custom directive named is-login.directive

<button type="button" appIsLogin (click)="sayHello()">
     down
    </button>
    

In the component:

  sayHello() {
        console.log('clicked');
    }
    

File: is-login.directive.ts

import {Directive, HostListener} from '@angular/core';

    @Directive({
    selector: '[appIsLogin]'
    })
    export class IsLoginDirective {

    isLoggedIn = false;

    constructor() {
    }

    @HostListener('mousedown', ['$event'])
    onClick(event: Event): boolean {
        if (!this.isLoggedIn) {
            console.log('mousedown');
            event.preventDefault();
            event.stopPropagation();
            return false;
        }
        return true;
    }
    

Current behavior: When the button is clicked, both events are triggered. The desired outcome is for only the mouse down event to occur.

View console screenshot.

The aim is to monitor the user's click event using the directive. If the user is not logged in, prevent the execution of the click event.

Answer №1

Give this a shot:

(click)="sayHello(); $event.stopPropagation()"

Answer №2

If you want to deactivate pointer events, try this:

this.elRef.nativeElement.classList.add('deactivated');

Next, add the following code to your component's CSS:

.deactivated {
  pointer-events: none;
}

Answer №3

To achieve this, I utilized the pointerEvents style by setting it to none:

import {Directive, HostListener} from '@angular/core';

@Directive({
    selector: '[appIsLogin]'
})
export class IsLoginDirective {

    isLoginIn = false;

    constructor(element: ElementRef) {
    }

    @HostListener('click')
    onClick() {
       if (!this.isLoginIn) {
           this.element.nativeElement.style.pointerEvents='none';
       }
    }
}

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

Ways to exchange data between different "input" sources

Is there a way to automatically transfer data entered in the first "input" field (full_name) to the second one (short_name)? <form [formGroup]="form"> <div class="row"> <div class="input-field col s12 m6"> <input formContro ...

Position filter forms on the left side to align with bootstrap cards

I'm having trouble aligning the cards using Bootstrap's row and col- classes. The first three are behaving as expected, but the fourth one isn't cooperating. Any idea why this might be happening and any solutions you can suggest? View the i ...

Tips for identifying when a div reaches the top or bottom of the browser window in Angular 4

This question has solutions available for JQuery (which I prefer not to use in the current project) and Angular1 (which I am unfamiliar with). ...

Trouble configuring a React TypeScript router has arisen

Recently, I have successfully set up multiple routers in TypeScript. However, I am facing challenges in implementing the same in a new project for some unknown reason. import React from 'react'; import Container from './Components/Containers ...

Adding URL path in Angular 7's .ts file

I currently have the following code in my component's HTML file: <button mat-flat-button class="mat-flat-button mat-accent ng-star-inserted" color="accent" (click)="playVideo(video)"> <mat-icon [svgIcon]="video.type === 'external' ...

Show the values of an array if the array name matches the string name

Is there a way to dynamically display the values of an array based on a matching string in Angular 4 or 6? Let's say we have two arrays, A and B: A = ['aaa','arrr','aeee','aqqqq','awwww','axxxx& ...

What is the best way to retrieve an accurately matched array?

I am working on a function that analyzes a string of DNA and should return an accurately matched DNA array. Here is the code snippet I have experimented with: function checkDNA(dna) { var dnaarr = []; for(var i = 0; i < dna.length; i++) { ...

Merge MathJax into SystemJS compilation

I utilize SystemJS to construct an Angular 2 project and I am interested in incorporating MathJax into a component. To start using it, I executed the following commands: npm install --save-dev mathjax npm install --save @types/mathjax Now, I have success ...

What sets apart `import http = require('http');` from `import * as http from 'http';`?

After searching for a quality NodeJS with Typescript tutorial without success, I've decided to navigate this learning journey unassisted. However, I have encountered a question along the way. I'm confused about the distinction between these two ...

Tips for passing parameters to an Angular compilation process?

Typically, Angular gets its environment settings from environment.[env].ts files during build time. However, I find myself in a situation where I need to be able to override those settings based on arbitrary parameters like apiUrl or connectionString that ...

The issue with converting a string into an object in Typescript

I am having trouble converting the JSON response from the websocket server to a TypeScript object. I've been trying to debug it but can't seem to find where the error lies. Can anyone assist me in resolving this issue? Below is the code snippet ...

The issue with the Angular Dropdown directive persists

Currently, I am working with Angular 6.0.5 and Bootstrap 4.1.1, where I have incorporated a directive for dropdowns. However, despite my efforts, I am unable to get it to function properly. While searching for a solution, I noticed that similar issues have ...

Passing validators for reactive forms from parent to child components is proving to be a challenge

Currently, I have a situation where a parent form component is utilizing a child form component within an Angular reactive forms setup. While I am able to successfully set the values in the child form component, it seems that the validators are no longer f ...

What methods are most effective for transferring data into Excel?

Currently, I have a report data that is coming from a back-end service written in .NET and the report format is in an HTML table using Angular. I am looking to export this report to Excel using the Angular front end. What would be the most efficient ...

Error: The value of "$tweetId" cannot be parsed as it is set to "undefined". Please ensure that string values are properly enclosed

I am utilizing sanity, and if you require more details, I will furnish it promptly. When I try to access http://localhost:3000/api/getComments, I encounter the following error message: ClientError: Unable to process value of "$tweetId=undefined". Kindly ...

Can we specify a more specific type for an argument in Typescript based on another argument in a function?

I'm in the process of developing a compact DSL for filter operations and crafting helper methods to support it. Suppose I have a function const equals = (left, right) => {} This function needs to be typed so that the left value is a field within ...

Is there a way to restrict the type of the value returned by URLSearchParams.get() to a specific union type?

When handling a search parameter in the URL, such as ?mode=view, it is important to validate the value of mode to ensure it is either 'edit' or 'view'. To achieve this, a custom type called ModeTuple is created and converted to a union ...

What is the correct way to utilize a variable as a parameter in React Query while employing the axios.request(options) method?

I'm currently working on a React Query component with the following structure: function test () { const [var, setVar] = useState("") const options = { method: "GET", url: "https://api.themoviedb.org/3/search/tv" ...

The service class adorned with the NgModule decorator

Is it possible to manage dependencies for both services in the code snippet by adding a @NgModule({ imports: [... ]}) decorator to each service class? I would like to avoid adding the modules in app.module.ts as each service has different module dependenc ...

Angular 2 - Ensuring service executes only when boolean condition is met

I am currently dealing with a navigation menu that utilizes the ng2-page-scroll module. When scrolling through the page using hashtag links, I encountered an issue. If I navigate across routes, there is a delay in loading the data. As a result, the servic ...