【问题标题】:Angular HostListener event from Child Component to Parent Component从子组件到父组件的 Angular HostListener 事件
【发布时间】:2017-12-05 13:18:22
【问题描述】:

我有两个组件 - 父组件和子组件。 我已将主机侦听器附加到两个组件以检测关键事件。 我想检测两个组件中的空格键事件。如果用户在子组件文本字段中按下空格键,那么我希望父组件什么都不做。但是,如果用户不在子组件文本字段中并按空格键,那么我希望父组件触发一个功能。

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 捕获,以便我可以决定在父组件中做什么或可以停止事件传播。

【问题讨论】:

标签: angular


【解决方案1】:

如果我们在父组件和子组件中添加相同的侦听器事件,则有两种可能性。

  1. 如果用户从父组件触发,则只执行父组件中的事件
  2. 如果用户从子组件触发,子组件和父组件中的事件都会被执行。从侦听器事件中删除窗口,以便子组件将在父组件之前首先执行。

如果您不想从子执行父,请将一些变量传递给父以控制事件。

Working demo,我使用了逃逸事件作为示例

父组件

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

【讨论】:

  • 这帮助我想出了解决方案。谢谢
猜你喜欢
  • 2019-05-13
  • 2018-04-16
  • 2020-01-11
  • 1970-01-01
  • 2018-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多