Home > Mobile >  Trigger Function with Mouse Click or Keyboard Tab using Angular 2
Trigger Function with Mouse Click or Keyboard Tab using Angular 2

Time:10-29

I use Angular 2 in my project and I need to trigger a function either by mouse click or by tab. Currently I am able to trigger the removeFilterMsg function using mouse click, but not by tab. Here's the code:

<button _ngcontent-tvl-14="" class="c-refine-item" name="refine" role="option" aria-selected="true" title="Remove Filter">
      <span class="facet" style="color:white;font-size:20px;cursor:pointer;" aria-hidden="true" (click)="removeFilterMsg()"> </span>
</button>

For the .ts function:

removeFilterMsg() {
        const $message = document.createElement('span');
        $message.classList.add('RemoveFilterItem');
        $message.setAttribute('aria-live', 'assertive');
        $message.setAttribute('display', 'none');
        window.setTimeout(() => {
            $message.innerHTML = "Filter item is removed";
        }, 100);
        document.body.appendChild($message);
    }

Is there any way to trigger this function either by mouse click or by tab? I tried to change from (click) to (select) but it doesn't work

CodePudding user response:

You need to use the @HostListener decorator. You can add it over your current function. If the tab key is pressed it will fire that function.

@HostListener('keydown.tab', ['$event'])
removeFilterMsg() {
    const $message = document.createElement('span');
    $message.classList.add('RemoveFilterItem');
    $message.setAttribute('aria-live', 'assertive');
    $message.setAttribute('display', 'none');
    window.setTimeout(() => {
        $message.innerHTML = "Filter item is removed";
    }, 100);
    document.body.appendChild($message);
}

  • Related