Alan He
Alan He

Reputation: 121

How to prevent button click event

I create a is-login.directive

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

component

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

is-login.directive.ts

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

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

isLoginIn = false;

constructor() {
}

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

Current behavior When I clicked the button, both events happened.I hope click event does not happen.

console

I want to monitor the user's click event by the directive, if the user is not logged in, do not execute the click event.

Upvotes: 3

Views: 2908

Answers (3)

Marius
Marius

Reputation: 3643

I did it by setting the pointerEvents style 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';
       }
    }
}

Upvotes: 0

Crava
Crava

Reputation: 76

Try this:

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

Upvotes: 2

Zlatko
Zlatko

Reputation: 19569

You can disable pointer events:

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

Then in your component CSS:

.disabled {
  pointer-events: none;
}

Upvotes: 0

Related Questions