Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

397
Vistas
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();
    }
  }
}
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar

0

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;
  }
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda