当用户单击外部时,关闭以下下拉菜单 [英] Close the following dropdown when user click outside
问题描述
我有一个下拉列表,如下所示,当用户在下拉列表外部单击时,我想关闭它.
I have a dropdown as follows, i want to close it when user click outside the dropdown.
<div [class.open]="qtydropdownOpened">
<button (click)="qtydropdownOpened = !qtydropdownOpened" type="button"
data-toggle="dropdown" aria-haspopup="true" [attr.aria-expanded]="qtydropdownOpened ? 'true': 'false' ">
{{selectedqty}}<span class="caret margin-left-1x "></span>
</button>
<div class="dropdown-wrp dropdown-menu">
<ul class="default-dropdown">
<li *ngFor="let quantity of quantities">
<a (click)="qtydropdownOpened = !qtydropdownOpened;setQuantity(quantity)">{{quantity }}</a>
</li>
</ul>
</div>
</div>
我尝试使用 Angular2关闭下拉菜单单击外部,是否有最简单的方法?方法,但似乎不起作用.
i have tried with Angular2 Close dropdown on click outside, is there an easiest way? method but it does not seem to work.
预期的行为:下拉列表应关闭.
实际行为:它保持打开状态.
推荐答案
我认为您有两个选择.第一个是使div内容可编辑(或使用另一个具有Blur事件的元素),并添加一个侦听器以模糊事件以隐藏drowdown.当元素失去焦点(例如单击外部等)时,将触发模糊.
I think you have two options. First one is to make the div content editable(Or use another element that has blur event) and add a listener to blur event to hide the drowdown. Blur will be triggered when the element loses focus like clicking outside etc.
或者您可以在组件中添加一个窗口侦听器,并在下拉菜单之外单击时将其隐藏:
Or you can add a window listener to your component and hide it when there's a click outside of the dropdown like:
@Component({
selector: 'mySelector',
template : 'YourTemplatehere',
host: {'(window:mouseup)': 'handleMouseUp($event)'},
})
export class MyClass {
handleMouseUp(e: MouseEvent) {
// Your code to handle the hiding logic. I think in your case its;
this.qtydropdownOpened = !this.qtydropdownOpened;
}
}
这篇关于当用户单击外部时,关闭以下下拉菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!