本文介绍了HostListener文件:单击角度2相同的组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
今天我正在创建一个需要检测外部点击的组件。我正在做一个100%的div来举行点击事件。但是经过研究,我做了这个文件:点击绑定方式。
Today I was creating a component that needs to detect outside clicks. I was doing with a 100% div to held the click event. But after a research I did the document:click bind way.
('document:click', ['$event'])
clickout(event: MouseEvent) {
// ... some code
}
所以我正在为任何想要的人分享我的解决方案。
So I'm sharing my solution for anyone who wants!
推荐答案
strong> 2017/06/15 - 在配置中添加tslib
Updated 2017/06/15 - Added tslib in config
已更新 2016/10/18
Updated 2016/10/18
import { Component, ElementRef, HostListener, Input } from '@angular/core';
@Component({
selector: 'selector',
template: `
<div style="width: 200px; height: 200px; display: inline-block" [style.backgroundColor]="makeDifferent">
{{text}}
</div>
`
})
export class AnotherComponent {
public text: String;
@Input() makeDifferent;
@HostListener('document:click', ['$event'])
clickout(event) {
if(this.eRef.nativeElement.contains(event.target)) {
this.text = "clicked inside";
} else {
this.text = "clicked outside";
}
}
constructor(private eRef: ElementRef) { }
}
这篇关于HostListener文件:单击角度2相同的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!