从子组件向父组件传递Angular中的HostListener事件

3

我有两个组件 - 父组件和子组件。 我已经为这两个组件附加了hostlistener以检测按键事件。 我想在这两个组件中检测空格键事件。 如果用户在子组件文本字段中按下空格键,则我希望父组件什么也不做。 但是,如果用户不在子组件文本字段中并按下空格键,则我希望父组件触发一个函数。

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);
 }
}

这里的事件被按照特定顺序捕获 - 首先是PARENT,然后是CHILD。我希望这些事件首先被CHILD捕获,以便我可以决定在父组件中要做什么,或者停止事件传播。


不确定这是否相关 - https://github.com/angular/angular/issues/11200 - jaibatrik
为什么不能使用键盘弹起事件监听器? <input id="child" (keyup)="onChildClick()" /> <input id="parent" (keyup)="onParentClick()" />? - Woot
@Woot,我需要一个窗口监听器来处理键盘事件。 - Rj-s
1个回答

4
如果在父组件和子组件中都添加了相同的监听器事件,有两种可能性:
  1. 如果用户从父组件触发事件,只会执行父组件中的事件。
  2. 如果用户从子组件触发事件,则会同时执行子组件和父组件中的事件。将窗口从监听器事件中移除,这样子组件就会先于父组件执行。
如果不想从子组件执行父组件,则可以传递一些变量到父组件来控制事件。 工作演示,我使用了转义事件作为示例。
父组件:
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");
    }
  }
}

这帮助我想出了解决方案。谢谢。 - Rj-s

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接