Angular Ctrl click?

28.3k views Asked by At

How can I catch when user press Ctrl click ?

I can do it for single click using:

<input ng-click="some_function()"/>

but I need something like:

<input ng-CTRL-click="some_nice_function()"/>

Is that possible?

2

There are 2 answers

2
Andy Ecca On BEST ANSWER

HTML

<input ng-click="some_function($event)"/>

JS

$scope.some_function = function(event){
    if (event.ctrlKey)
    {
       // logic here
    }
}
0
Víctor On

You have to create your own ctrl-click directive. To do this, navigate to your "directives" folder in your editor and create ones.

You can do it by terminal writting:

ng generate directive ctrl-click

Once created, you have to edit it like following:

import { 
    Directive, ElementRef, EventEmitter, OnDestroy, OnInit, Output, Renderer2 } from '@angular/core';

@Directive({
    // tslint:disable-next-line:directive-selector
    selector: '[ctrl-click]',
})

export class CtrlClickDirective implements OnInit, OnDestroy {
    private unsubscribe: any;

    // tslint:disable-next-line:no-output-rename
    @Output('ctrl-click') ctrlClickEvent = new EventEmitter();

    constructor(private readonly renderer: Renderer2, private readonly element: ElementRef) {}

    ngOnInit() {
        this.unsubscribe = this.renderer.listen(this.element.nativeElement, 'click', event => {
            if (event.ctrlKey) {
                event.preventDefault();
                event.stopPropagation();
                // unselect accidentally selected text (browser default behaviour)
                document.getSelection().removeAllRanges();

                this.ctrlClickEvent.emit(event);
            }
        });
    }

    ngOnDestroy() {
        if (!this.unsubscribe) {
            return;
        }
        this.unsubscribe();
    }
}

If there is a conflict with "spec.ts" file, you can comment its constructor.

Finally, you need to add to app.modules.ts file if it has not been added automatically:

import { CtrlClickDirective } from './shared/directives/ctrl-click.directive';

@NgModule({
imports: [
    ...
    CtrlClickDirective
],

And then, you can use it in your html files.

NOTE: You can not add listeners for both (click) and (ctrl-click) on the same element. The (click) event will fire every time. If you need both event listeners, then you need to nest them, like this:

<a (click)="this.openSomething(params...)" style="cursor: pointer">
    <span (ctrl-click)="this.openSomethingNewTab(params...)">New Tab</span>
</a>

This should work fine, I hope I help you.