[英]Clean way to close dropdown list when clicking outside
我有一個按鈕,單擊后會打開一個下拉列表。
我想在按鈕外部單擊時關閉此列表。 所以我使用了一個HostListener
像這樣:
@HostListener('click', ['$event.target'])
toggleDropdown(element) {
const clickOnDropdownButton = (): boolean => {
const buttonChildsClasses = ['button is-primary tog-button', 'dropdown-label', 'tog-icon tog-icon-arrow-down', 'icon is-small'];
return buttonChildsClasses.indexOf(element.className) !== -1;
};
if (this.dropDownActive) {
this.dropDownActive = false;
} else if (!this.dropDownActive && clickOnDropdownButton()) {
this.dropDownActive = true;
}
}
這可行,但是我認為使用可能的childs數組根本不干凈。
確實,我按鈕的問題在於它由幾個HTML元素組成,我的按鈕不僅僅是button
標簽。
我想到了使用position: absolute
在其他元素之上放置HTML元素,但是我不確定它是否更干凈。
對這個問題有什么想法嗎?
//this is your dropdown list in html
<div #dropdown> </div>
//this is your ts
@Component({
host: {'(document:click)': 'handleClick($event)',}
})
@ViewChild('dropdown', {read: ElementRef}) dropdown: ElementRef;
handleClick(event) {
var clickedComponent = event.target;
do {
if (clickedComponent !== this.dropdown.nativeElement) {
it's call when we click outside the dropdown list
}
while (clickedComponent);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.