Search code examples
angularangular-directiveeventemitter

Not able to bind click event in @Directive in angular4


I have a simple Directive like this

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

now, i want to trigger the click event of the component where i have placed the directive like this

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

this is the component ts code

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

when i placed the debugger inside the directives onclick() event, i noticed that the event is not getting called i refrenced this blog


Solution

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