Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

403
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!