Angular - HostListener 指令和传递值
Angular - HostListener directive and pass value
我正在尝试使用 'innerHTML' 通过单击事件传递 div。由于(单击)不起作用,我尝试使用 HostListener 来获取 ID。但是似乎连innerHTML里面的id都传不过去。
HTML代码
<div [innerHTML]="show" detectClick></div>
主机侦听器
@HostListener('click', ['$event.target.id']) onClick(id: any) {
alert(`You clicked on ${id}`);
this.test = id;
}
要动态附加的代码
this.show = this.sanitizer.bypassSecurityTrustHtml(`<div class="clickarea"><span id="123" (click)="showID('123');">x</span></div>`);
Link 到 StackBlitz
您不能在 innerHTML
中使用 Angular 特定属性,例如 (click)
或 [prop]
。
但是,您可以通过 @HostListener
装饰器使用事件委托来获得点击 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>
我正在尝试使用 'innerHTML' 通过单击事件传递 div。由于(单击)不起作用,我尝试使用 HostListener 来获取 ID。但是似乎连innerHTML里面的id都传不过去。
HTML代码
<div [innerHTML]="show" detectClick></div>
主机侦听器
@HostListener('click', ['$event.target.id']) onClick(id: any) {
alert(`You clicked on ${id}`);
this.test = id;
}
要动态附加的代码
this.show = this.sanitizer.bypassSecurityTrustHtml(`<div class="clickarea"><span id="123" (click)="showID('123');">x</span></div>`);
Link 到 StackBlitz
您不能在 innerHTML
中使用 Angular 特定属性,例如 (click)
或 [prop]
。
但是,您可以通过 @HostListener
装饰器使用事件委托来获得点击 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>