Emit event from Directive to parent element
You can also use the use the same name for the directive and the @Output
:
@Directive({
selector: '[myCustomMouseover]'
})
export class MyCustomMouseoverDirective {
@Output()
public myCustomMouseover = new EventEmitter<void>();
@HostListener('mouseover', ['$event'])
public onMouseover(event: MouseEvent): void {
if (/* only trigger in certain conditions */) {
this.myCustomMouseover.emit();
}
}
}
And you can use in any element just like:
<div (myCustomMouseover)="handler()">
...
</div>
I'd like to add to @GünterZöchbauer's answer that if you're trying to emit an event from a structural directive and using an asterisk (*
) syntax when applying the directive, it won't work. Angular 5.2.6 still doesn't support @Output
binding for structural directives if used with the *
syntax (see GitHub issue).
You have to transform it to de-sugarized form (see here), i.e.:
<ng-template [customDirective]="foo" (customDirectiveEvent)="handler($event)">
<div class="name">{{hero.name}}</div>
</ng-template>
instead of:
<div *customDirective="foo" (customDirectiveEvent)="handler($event)" class="name">{{hero.name}}</div>
If myCustomDirective
has an output @Output() someEvent:EventEmitter = new EventEmitter();
then you can use
<div myCustomDirective (someEvent)="callSomethingOnParent($event)">HELLO</div>