Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

408
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda