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();
}
}
}
CodePudding user response:
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.
CodePudding user response:
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.
CodePudding user response:
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;
}