raj*_*aju 14 html dom-events angular-directive angular
我在HTML模板中有一个元素.我给它添加了一个指令:
<div myCustomDirective>HELLO</div>
Run Code Online (Sandbox Code Playgroud)
我希望每当我将鼠标悬停在div
文本里面时都div
应该更改,但是需要从Directive
(mouseover)
事件中完成.
我不知道如何从a发出事件Directive
并捕获父元素内部.
任何帮助表示赞赏.这是angular2项目.
Gün*_*uer 45
如果myCustomDirective
有输出 @Output() someEvent:EventEmitter = new EventEmitter();
则可以使用
<div myCustomDirective (someEvent)="callSomethingOnParent($event)">HELLO</div>
Run Code Online (Sandbox Code Playgroud)
Ale*_*mov 12
我想添加@GünterZöchbauer的答案,如果你试图从结构指令发出一个事件并*
在应用指令时使用asterisk()语法,它将无法工作.@Output
如果与*
语法一起使用,Angular 5.2.6仍然不支持结构指令的绑定(请参阅GitHub问题).
你必须将它转换为脱糖形式(见这里),即:
<ng-template [customDirective]="foo" (customDirectiveEvent)="handler($event)">
<div class="name">{{hero.name}}</div>
</ng-template>
Run Code Online (Sandbox Code Playgroud)
代替:
<div *customDirective="foo" (customDirectiveEvent)="handler($event)" class="name">{{hero.name}}</div>
Run Code Online (Sandbox Code Playgroud)
您还可以对指令使用相同的名称@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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以在任何元素中使用,如下所示:
<div (myCustomMouseover)="handler()">
...
</div>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
25352 次 |
最近记录: |