【问题标题】:angular keyup event does not trigger on child component, but only on parent insteadangular keyup 事件不会在子组件上触发,而只会在父组件上触发
【发布时间】:2018-04-30 12:11:59
【问题描述】:

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

但是 angular 不继承组件注释,所以我还创建了一个“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!";
  }
}

子组件:

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 :( !');
  }

}

模板组件:

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() {
  }

}

【问题讨论】:

    标签: angular


    【解决方案1】:

    你应该调用方法

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

    Plunker

    【讨论】:

    • 耶稣......这些小注意错误是最糟糕的。谢谢!
    • 这是一个工作的笨蛋吗?我没有看到 printText 更改或任何控制台日志。
    • @yurzui 哎呀!我只尝试了一些键盘和clear button。对不起!
    猜你喜欢
    • 1970-01-01
    • 2010-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-07
    • 1970-01-01
    相关资源
    最近更新 更多