Reputation: 121
How to implement event delegation for specific target in angular 2
Consider having the below html
<ul>
<li><span>hello</span><button>button</button></li>
</ul>
And i want to implement event delegation to target the li even if the user clicked on the span or the button inside the li, the li event will run.
for example we can achieve this in jquery using :
$('ul').on('click', 'li', function() {
console.log($(this)) // always log the li whenever you clicked inside it
})
my actual scenario in angular :
<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>
Upvotes: 1
Views: 678
Reputation: 41407
you can achive this by creating a directive with @HostListner
@Directive({selector: '[dele]')
export class delegator{
@HostListener('click') clicked($event) {
console.log($event.target); // this will be a child button
}
}
Now call it like this
<ul dele>
<li><span>hello</span><button>button</button></li>
</ul>
EDIT
if you want to add hostlistner
to a specific element then use an event
@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);
}
}
In the html add the directive as well as the
<ul>
<li dele (onFocusOut)='clickFunction($event)'><span>hello</span><button>button</button></li>
</ul>
Upvotes: 2