Saad Bashir
Saad Bashir

Reputation: 4519

Angular - HostListener directive and pass value

I am trying to pass a div with click event using 'innerHTML'.Since (click) wasn't working, I tried to use HostListener to get id. But it seems can't even pass id in the innerHTML.

HTML Code

<div [innerHTML]="show" detectClick></div>

Host Listener

@HostListener('click', ['$event.target.id']) onClick(id: any) {
    alert(`You clicked on ${id}`);
    this.test = id;
} 

Code to be appended dynamically

this.show = this.sanitizer.bypassSecurityTrustHtml(`<div class="clickarea"><span id="123" (click)="showID('123');">x</span></div>`);

Link to StackBlitz

Upvotes: 2

Views: 2653

Answers (1)

yurzui
yurzui

Reputation: 214175

You can't use Angular specific attributes like (click) or [prop] inside innerHTML.

But yes, you can use event delegation through @HostListener decorator to get clicked id:

detectclick.directive.ts

import { Directive, Output, HostListener, EventEmitter } from '@angular/core';

@Directive({selector: '[detectClick]'})
export class DetectClick {

  @Output() detectClick = new EventEmitter();

  @HostListener('click', ['$event.target.id']) onClick(id: any) {
    this.detectClick.emit(id);
  } 
}

parent.html

<div [innerHTML]="show" (detectClick)="showID($event)"></div>

Forked Stackblitz

Upvotes: 3

Related Questions