angular keyup事件不会在子组件上触发,而只会在父组件上触发

时间:2017-11-16 20:20:37

标签: angular

我创建了一个组件,我希望在我的应用程序中拥有它的多个版本,因为我想将所有逻辑保留在一个地方,我创建了一个ParentComponent,我所有的代码都驻留在那里。

但是角度不要继承组件注释,所以我还创建了一个" TemplateComponent",以防止代码重复。 TemplateComponent保存输入,但它是处理输入事件的ParentComponent。这样,每个ChildComponent都会为逻辑继承ParentComponent,而它的模板是TemplateComponent的一个实例。

最重要的是,当我尝试在TemplateComponent内部的输入上侦听keyup事件时,在没有任何输入或控件的ChildComponent上调用click事件。

我尝试将事件绑定传递给模板组件以连接keyup输入,但它永远不会触发。

ChildComponent上有一个HostListener,只是为了调试只在那里触发事件。并不是因为这导致事件停止。

有没有办法告诉angular必须在模板组件中调用keydown事件,或者将所有内容链接到其他方式?

我有一个工作的傻瓜,它几乎是不言自明的:

https://plnkr.co/edit/e4U6DB4d47ULpLppHd4H?p=preview

但代码:

为父级:

import {Component, NgModule, VERSION} from '@angular/core'

@Component({
  selector: 'app-parent',
  template: `
    <ng-content></ng-content>
  `,
})
export class ParentComponent {

  printText = 'Not yet';

  constructor() {
  }

  inputKeyDownEnter(event: any) {
    this.printText = 'KeyDown OK!';
  }

  clearButtonClick(event: any) {
    this.printText = "Clear button click!";
  }
}

ChildComponent:

import {Component, HostListener} from '@angular/core';
import {ParentComponent} from './parent.component';

@Component({
  selector: 'app-child',
  template: `
    <div>{{printText}}</div>
    <app-custom-template
      (inputKeyDownEnter)="inputKeyDownEnter"
      (clearButtonClick)="clearButtonClick"
    >
    </app-custom-template>
  `,
})
export class ChildComponent extends ParentComponent {

  constructor() {
    super();
  }

  @HostListener('keydown.enter', ['$event'])
  onKeyDownChild(event: any) {
    console.log('Only here :( !');
  }

}

TemplateComponent:

import {Component, Output, EventEmitter} from '@angular/core';

@Component({
  selector: 'app-custom-template',
  template: `
    <input 
      type="text"
      name="my_text"
      (keyup.Enter)="inputKeyDownEnter.emit($event)"
      />
    <button
      type="button"
      (click)="clearButtonClick.emit($event)">Clear</button>
  `,
})
export class CustomTemplateComponent {

  @Output()
  inputKeyDownEnter = new EventEmitter<any>();

  @Output()
  clearButtonClick = new EventEmitter<any>();

  constructor() {
  }

}

1 个答案:

答案 0 :(得分:3)

你应该调用方法

(inputKeyDownEnter)="inputKeyDownEnter($event)"
                                      ^^^^^^^^^

<强> Plunker

相关问题