我有两个组件 - 父和子组件。我已将hostlistener附加到两个组件上,以检测关键事件。我想检测两个组件中的太空密钥事件。如果用户按下儿童组件文本字段中的空格键,那么我希望父级零件什么都不做。但是,如果用户不在儿童组件文本字段中并按Space键,则我希望父派启用函数。
export class ParentComponent {
constructor() { }
@HostListener('window:keyup', ['$event'])
keyEvent(event: KeyboardEvent) {
console.log("PARENT", event.keyCode);
}
}
export class ChildComponent {
constructor() { }
@HostListener('window:keyup', ['$event'])
keyEvent(event: KeyboardEvent) {
console.log("CHILD", event.keyCode);
}
}
这里的事件被捕获,但按照特定的顺序 - 第一父母,然后是孩子。我希望这些事件是 - 首先是由孩子捕获的,以便我可以决定在父级组件中做什么或可以停止事件传播。
如果我们在父和子组件中添加相同的侦听器事件,则有两种可能性。
- 如果用户触发了父部件,则只能执行父部件中的事件
- 如果用户触发儿童组件,则将执行子女组件中的事件。从侦听器事件中删除窗口,以便在父部件之前先执行子组件。
如果您不想从子女执行父母,请传递一些变量来控制事件。
工作演示,我已将逃生事件用作样本
父部件
import { Component } from '@angular/core';
import { HostListener } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
color : String='green';
child : Boolean=true;
@HostListener('keydown', ['$event']) triggerEsc(e: KeyboardEvent) {
if(e.keyCode===27 && this.child===true){
console.log("global esc");
alert("parent esc");
}else{
this.child=true;
}
}
public doSomething(child: any):void {
this.child=child;
}
name = 'Angular 5';
}
父模板
<input placeholder="Parent Can't copy/paste" type="text" appBlockCopyPaste/>
<hello (child)="doSomething($event)"></hello>
带模板的儿童组件
import { Component, Input,Output , EventEmitter} from '@angular/core';
import { HostListener } from '@angular/core';
@Component({
selector: 'hello',
template: `<input placeholder="Child" type="text" appBlockCopyPaste/>`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
@Output() child: EventEmitter<any> = new EventEmitter<any>();
@HostListener('keydown', ['$event']) triggerEsc(e: KeyboardEvent) {
if(e.keyCode===27){
this.child.emit(false);
console.log("global esc");
alert("child esc");
}
}
}