Angular: stopImmediatePropagation() 无法在 keydown 上工作
Angular: stopImmediatePropagation() not working on keydown
我有一个 directive
附加到 input
字段,两者都在监听 keydown
事件,在某些情况下我想阻止事件在 directive
。调用 event.stopImmediatePropagation();
并没有真正停止传播。
示例:
指令
import { Directive, HostListener } from '@angular/core';
@Directive({ selector: '[myDirective]' })
export class MyDirective {
constructor() { }
@HostListener('keydown', ['$event'])
keydownHandler(event) {
event.stopImmediatePropagation(); // seems to be not working!!
console.log('[my-directive.ts]: keydownHandler', event)
}
}
带输入字段的组件
import { Component, Input } from '@angular/core';
@Component({
selector: 'hello',
template: `
<input type="text" myDirective (keydown)="keydownHandler($event)">
`
})
export class HelloComponent {
@Input() name: string;
keydownHandler(event) {
console.log('[hello.component.ts]: keydownHandler', event)
}
}
我不明白为什么 event.stopImmediatePropagation();
不起作用,有什么想法吗?是否有另一种方法可以避免 keydown
在带有 input
字段的 component
上被触发?
Angular 优化事件处理程序,如果您有两个或多个处理程序处理同一个事件,它将只添加一个侦听器并将结果分派给所有组件。这意味着 stopImmediatePropagation
现在取决于 angular 调度顺序。您可以添加日志记录或调试执行顺序。
看看这个问题https://github.com/angular/angular/issues/9587
作为解决方法,您可以直接在元素上添加事件侦听器
constructor(private elementRef: ElementRef) {
// add listener as first to allow to stop next event listener execution
elementRef.nativeElement.addEventListener('click', (event: Event) => {
if (this.disabled) {
event.stopImmediatePropagation();
}
});
}
我有一个 directive
附加到 input
字段,两者都在监听 keydown
事件,在某些情况下我想阻止事件在 directive
。调用 event.stopImmediatePropagation();
并没有真正停止传播。
示例:
指令
import { Directive, HostListener } from '@angular/core';
@Directive({ selector: '[myDirective]' })
export class MyDirective {
constructor() { }
@HostListener('keydown', ['$event'])
keydownHandler(event) {
event.stopImmediatePropagation(); // seems to be not working!!
console.log('[my-directive.ts]: keydownHandler', event)
}
}
带输入字段的组件
import { Component, Input } from '@angular/core';
@Component({
selector: 'hello',
template: `
<input type="text" myDirective (keydown)="keydownHandler($event)">
`
})
export class HelloComponent {
@Input() name: string;
keydownHandler(event) {
console.log('[hello.component.ts]: keydownHandler', event)
}
}
我不明白为什么 event.stopImmediatePropagation();
不起作用,有什么想法吗?是否有另一种方法可以避免 keydown
在带有 input
字段的 component
上被触发?
Angular 优化事件处理程序,如果您有两个或多个处理程序处理同一个事件,它将只添加一个侦听器并将结果分派给所有组件。这意味着 stopImmediatePropagation
现在取决于 angular 调度顺序。您可以添加日志记录或调试执行顺序。
看看这个问题https://github.com/angular/angular/issues/9587
作为解决方法,您可以直接在元素上添加事件侦听器
constructor(private elementRef: ElementRef) {
// add listener as first to allow to stop next event listener execution
elementRef.nativeElement.addEventListener('click', (event: Event) => {
if (this.disabled) {
event.stopImmediatePropagation();
}
});
}