无法在angular4中绑定@Directive中的click事件

时间:2017-09-12 09:20:55

标签: angular angular-directive eventemitter

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

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

现在,我想触发我放置了这个指令的组件的click事件

<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

1 个答案:

答案 0 :(得分:3)

@HostListener('click',['$event']) onclick($event) {
    debugger;
    this.clickDirective.emit();
  }