'event.preventDefault() or event.stopPropagation() not working with keyUp event

Directive file: I am trying to do that if my counter goes above two it should stop event or keyUp to reflect but is it not working. Can someone help me on this?

import { Component, HostListener, HostBinding } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

export enum KeyCodes {
  LEFT = 37,
  RIGHT = 39,
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  counter: number = 0;
  fragment: string;
  classBorder: string = '';

  constructor(private _route: ActivatedRoute) {
    // this.fragment = _route.snapshot.fragment;
  }

  @HostListener('document:keyup', ['$event'])
  KeyUpEvent(event: KeyboardEvent) {
    if (event.keyCode == KeyCodes.LEFT) this.counter--;
    if (event.keyCode == KeyCodes.RIGHT) this.counter++;

    if (this.counter > 2) {
      event.preventDefault();
      event.stopPropagation();
    }
  }
}


Solution 1:[1]

You might want to create an observable in the OnInit for the event and then pipe it to only take the first 2 values emitted:

export class AppComponent implements OnInit {

  ngOnInit() {
    fromEvent(document, 'keydown').pipe(
      filter((e: KeyboardEvent) => e.keyCode === KeyCodes.LEFT),
      take(2),
    ).subscribe(
      (x: KeyboardEvent) => console.log(x)
    )
  }
}

The preventDefault() only disables default behaviors of the browser, it is commonly used to prevent refreshing on certain events and things like that.

You can also use takeUntil() to wait on another observable to fire, for slightly more complex logic like yours.

counter = 0
countSubject = new Subject

get count$() {
  return this.countSubject.asObservable()
}

ngOnInit() {
  fromEvent(document, 'keydown').pipe(
    tap((e: KeyboardEvent) => {
      if (e.keyCode === KeyCodes.LEFT) {
        this.countSubject.next(++this.counter)
      }
      if (e.keyCode === KeyCodes.RIGHT) {
        this.countSubject.next(--this.counter)
      }
    }),
    takeUntil(this.count$.pipe(
      filter((v:number) => v === 2)
    )),
  ).subscribe(
    (x: KeyboardEvent) => console.log(x)
  )
}

I made a working example on Stackblitz for you.

Solution 2:[2]

The stopPropagation() method is used to stop propagating the event from child to parent element, and in this case you are listening to the document's keyup event. (It's like listening events from the entire body of the document).

Maybe you should change the target from which you listen for the keyup event.

Here is a very simple example of stopPropagation() in action with the keyup event.

Solution 3:[3]

You don't need to prevent anything, just use the correct logic.

Try this one:

KeyUpEvent(event: KeyboardEvent) {
    if (event.keyCode == KeyCodes.LEFT) this.counter--;
    if (event.keyCode == KeyCodes.RIGHT) this.counter += this.counter < 2;
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Arthur PĂ©rez
Solution 3 opensorcio