[英]Angular: how to get <li> rather than <ul> from click event
I have an Angular component that has a <ul>
element contains <li>
elements.我有一个包含
<li>
元素的<ul>
元素的 Angular 组件。 I have the following code:我有以下代码:
@HostListener('document:mousedown', ['$event'])
onMouseDown(event: MouseEvent): void {
func();
}
I want func()
to be executed whenever I click anywhere on the screen except for on certain <li>
elements that have a disabled
class applied to them.我希望
func()
每当我点击屏幕上的任何地方时都会执行,除了某些应用了disabled
类的<li>
元素。 What I was hoping is that event.target
would return the <li>
I clicked on, so that I could do something like我希望
event.target
会返回我点击的<li>
,这样我就可以做类似的事情
if (!event.target.disabled) {
func()
}
The problem is that event.target
returns the <ul>
rather than the <li>
.问题是
event.target
返回<ul>
而不是<li>
。 Here's my template:这是我的模板:
<div>
<ul>
<ng-container>
<ng-template>
<li>
<li class="disabled">
<li>
</ng-template>
</ng-container>
</ul>
</div>
This template can't change, because it's part of someone else's code.此模板无法更改,因为它是其他人代码的一部分。
Does anyone know how to approach this?有谁知道如何解决这个问题?
can you try this approach:你能试试这个方法吗:
https://stackblitz.com/edit/angular-kfonyy https://stackblitz.com/edit/angular-kfonyy
@HostListener('document:click', ['$event'])
onMouseDown(event): void {
this.func(event.target)
}
func(element) {
if (element.tagName == ‘LI’ && element.classList.contains('disabled')) {
console.log("clicked disabled li")
} else {
console.log("clicked elsewhere")
}
}
a simple solution is bind these disabled elemnt to mousedown event and call event.stopPropagation()
method.一个简单的解决方案是将这些禁用的元素绑定到 mousedown 事件并调用
event.stopPropagation()
方法。
template模板
<li class="disabled" (mousedown)="handler($event)">click</li>
component成分
handler(e:MouseEvent){
e.stopPropagation();
}
Update !!更新 !!
you can still do the samething by using directive like this and target nore event你仍然可以通过使用这样的指令和目标 nore 事件来做同样的事情
@Directive({
selector: '[prevEvents]'
})
export class PrevEventsDirective {
@HostListener("mousedown", ["$event"])
@HostListener("mouseup", ["$event"])
@HostListener("click", ["$event"])
public handler(e:MouseEvent) {
e.stopPropagation();
}
}
template模板
<li class="disabled" prevEvents>click</li>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.