针对特定目标Angular 2的事件委派

问题描述 投票:1回答:1

如何在角度2中实现特定目标的事件委托

考虑使用以下html

<ul>
   <li><span>hello</span><button>button</button></li>
</ul>

我想实现事件委托以定位li,即使用户点击了li内的跨度或按钮,li事件也会运行。

例如,我们可以在jquery中使用以下方法实现:

$('ul').on('click', 'li', function() {
  console.log($(this)) // always log the li whenever you clicked inside it
})

我在角度的实际场景:

<div class="list-group" (click)="selectOption($event)">

<button type="button" class="list-group-item" *ngFor="let option of options; let i = index"
 [attr.data-value]="option.key" [attr.data-label]="option.displayColumnValue">
  <span [title]="option.displayColumnValue ">
   {{ option.displayColumnValue }} 
  <small *ngIf="option.email">({{ option.email }})</small>
  </span>

  <a *ngIf="option.group" class="drilldown" [attr.data-key]="option.key"><i class="fa fa-chevron-right" aria-hidden="true"></i></a>
</button>

angular angular2-template
1个回答
2
投票

您可以通过使用qazxsw poi创建指令来实现此目的

@HostListner

现在这样称呼它

@Directive({selector: '[dele]')
export class delegator{
   @HostListener('click') clicked($event) {
      console.log($event.target); // this will be a child button
   }
}

编辑

如果要将<ul dele> <li><span>hello</span><button>button</button></li> </ul> 添加到特定元素,请使用事件

hostlistner

在html中添加指令以及

@Directive({
   selector: "[dele]"
})
export class deleDirective {
   @Output() onFocusOut: EventEmitter<boolean> = new EventEmitter<false>();

   @HostListener("focusout", ["$event"])
   public onListenerTriggered(event: any): void {
       this.onFocusOut.emit(true);
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.