Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emit event from Directive to parent element

I have an element in HTML template of an Angular 2 app. I add a directive to it:

<div myCustomDirective>HELLO</div> 

I want that whenever I hover over the div the text inside the div should be changed, but it needs to be done from Directive (mouseover) event.

How to emit an event from a Directive and capture it inside a parent element?

like image 630
raju Avatar asked Jun 22 '16 08:06

raju


People also ask

How@ Output works in Angular?

The @Output() 's type. Tells Angular to create a new event emitter and that the data it emits is of type string. For more information on EventEmitter , see the EventEmitter API documentation. The addNewItem() function uses the @Output() , newItemEvent , to raise an event with the value the user types into the <input> .

How do you emit an event from parent to child?

In a parent component you can use @ViewChild() to access child component's method/variable. Use the @Input() decorator in your child component to allow the parent to bind to this input. To bind a property from parent to a child you must add in you template the binding brackets and the name of your input between them.

What is the difference between@ Input and@ Output in Angular?

Input is used to receive data in whereas Output is used to send data out. Output sends data out by exposing event producers, usually EventEmitter objects. by the way, I will produce and send data out via the onChange property.


2 Answers

If myCustomDirective has an output @Output() someEvent:EventEmitter = new EventEmitter(); then you can use

<div myCustomDirective (someEvent)="callSomethingOnParent($event)">HELLO</div> 
like image 132
Günter Zöchbauer Avatar answered Sep 20 '22 15:09

Günter Zöchbauer


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> 
like image 31
Alexander Abakumov Avatar answered Sep 16 '22 15:09

Alexander Abakumov