Ron*_*men 20 angular-directive angular2-directives angular angular-observable
我已经使用自定义指令来检测角度2中元素外部的单击,但角度4中不可能相同.
[plunkr] https://plnkr.co/edit/aKcZVQ?p=info
当我尝试在angular-4中使用相同的代码时,我收到以下错误:
1. Argument of type '{ template: string; directives: typeof ClickOutside[]; }' is not assignable to parameter of type 'Component'. ==>
@Component({
templateUrl: "",
directives: [ClickOutside]
})
2. Type 'Subscription' is not assignable to type 'Observable<MouseEvent>'. in the directive inside ngOnInit() and ngOnDestroy()
ngOnInit() {
this.globalClick = Observable
.fromEvent(document, 'click')
.delay(1)
.do(() => {
this.listening = true;
}).subscribe((event:MouseEvent) => {
this.onGlobalClick(event);
});
}
ngOnDestroy() {
this.globalClick.unsubscribe();
}
Run Code Online (Sandbox Code Playgroud)
如果角度4中的指令声明有任何变化请告诉我,官方文档对此事没有任何帮助.
Kub*_*uba 50
与您的plnkr相关的变化很少.
该指令本身对我来说很好.我将你的指令与我的指令进行了比较,它在Angular 4.3.5中运行良好.
实际上,在这种情况下你不需要任何指令,除非它不会重复使用.如果您只需要将clickOutside应用于菜单,那么最好这样做:
将点击事件绑定到您的"内部"选择器.让我们说这是你的菜单:
<ul id="menu" (click)="clickedInside($event)"> <li> .. </li> </ul>
Run Code Online (Sandbox Code Playgroud)
然后在你的组件内添加如下clickedInside()函数:
clickedInside($event: Event){
$event.preventDefault();
$event.stopPropagation(); // <- that will stop propagation on lower layers
console.log("CLICKED INSIDE, MENU WON'T HIDE");
}
Run Code Online (Sandbox Code Playgroud)
最后,您可以在组件中使用Host Listener将click也绑定到文档的其余部分
@HostListener('document:click', ['$event']) clickedOutside($event){
// here you can hide your menu
console.log("CLICKED OUTSIDE");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25753 次 |
| 最近记录: |