【问题标题】:Not able to bind click event in @Directive in angular4无法在 angular4 中的 @Directive 中绑定点击事件
【发布时间】:2017-09-12 09:20:54
【问题描述】:

我有一个像这样的简单指令

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

@Directive({
  selector: '[appAppClick]'
})
export class AppClickDirective {
  @Output() clickDirective: EventEmitter<any> = new EventEmitter();
  constructor() { }
  @HostListener('onClick') onclick() {
    debugger;
    this.clickDirective.emit();
  }
}

现在,我想触发像这样放置指令的组件的点击事件

<button type="button" class="btn btn-secondary" data-dismiss="modal" appAppClick (clickDirective)="parentClick()"> Proceed</button>

这是组件的ts代码

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  parentFunc() {
    alert('parent function called');
  }
}

当我将调试器放在 onclick() 事件的指令中时,我注意到该事件没有被调用 我引用了这个blog

【问题讨论】:

  • "onClick" 不是事件"click" 是。

标签: angular angular-directive eventemitter


【解决方案1】:
@HostListener('click',['$event']) onclick($event) {
    debugger;
    this.clickDirective.emit();
  }

【讨论】:

  • $event 不用为什么要传?
  • 谢谢,参考博客提到onClick,搞糊涂了
  • @Arg0n 供其他 Google 员工将来复制粘贴代码 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-23
  • 2013-06-21
  • 2013-02-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多