简体   繁体   English

角度:如何获得<li>而不是<ul>来自点击事件

[英]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();   
}

demo 🚀🚀演示🚀🚀

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>

demo 🌟演示🌟

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM