我在angular2中创建了一个简单的offClick指令,就像这样。
import { Directive, Host, Input, Output, EventEmitter, ElementRef } from '@angular/core';
@Directive({
selector: '[offClick]',
host: {
'(document:click)': 'onClick($event)',
}
})
export class OffClickDirective {
@Input('offClick') a;
@Output('off')
offClicked = new EventEmitter();
constructor(
private elementRef: ElementRef) {
}
onClick($event) {
$event.stopPropagation();
if (!this.elementRef.nativeElement.contains($event.target))
this.offClicked.emit({});
}
}
但是要将其添加到HTML元素中,我必须做这样的事情。
<div [offClick] (off)="onOffClick($event)"></div>
无论如何,我可以更改此指令,因此我可以在HTML元素上使用它
<div (offClick)="onOffClick($event)"></div>
OR
我基本上不想要为该指令声明一个标签,然后另一个来捕获该事件....
提前致谢
答案 0 :(得分:1)
这应该做你想要的事情
@Directive({
selector: '[offClick]',
host: {
'(document:click)': 'onClick($event)',
}
})
export class OffClickDirective {
@Output('offClick')
offClicked = new EventEmitter();
constructor(
private elementRef: ElementRef) {
}
onClick($event) {
$event.stopPropagation();
if (!this.elementRef.nativeElement.contains($event.target))
this.offClicked.emit({});
}
}
<div (offClick)="onOffClick($event)"></div>