首页 文章

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

提问于
浏览
2

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

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

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

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

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

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

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

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 回答

  • 3

    你应该调用方法

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

    Plunker

相关问题