Emit event from Directive to Parent element

笑着哭i 提交于 2019-11-30 14:44:53

问题


I have an element in HTML template. 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.

I don't know how to emit event from a Directive and capture inside a parent element.

Any help is appreciated. This is angular2 project.


回答1:


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

<div myCustomDirective (someEvent)="callSomethingOnParent($event)">HELLO</div>



回答2:


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>


来源:https://stackoverflow.com/questions/37962701/emit-event-from-directive-to-parent-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!