1 回答
TA贡献1785条经验 获得超8个赞
我可以使用 RxJS而不是hook来捕获标签click中的事件。我还使用 Angular 清理了 HTML 。markfromEventaddEventListenerAfterViewInitAfterContentCheckedDomSanitizer
尝试以下操作
应用程序组件.ts
import { fromEvent, Subject } from "rxjs";
import { takeUntil } from "rxjs/operators";
...
export class AppComponent implements AfterViewInit, OnDestroy {
@ViewChild("showcaseContentText") showcaseContentText: ElementRef<any>;
html =
"Lorem ipsum dolor sit amet, <mark (click)='hello('my name is what')'>consectetur adipiscing elit</mark>";
closed$ = new Subject<any>();
constructor(private cdr: ChangeDetectorRef) {}
ngAfterViewInit() {
this.cdr.detectChanges();
fromEvent(
this.showcaseContentText.nativeElement.querySelector("mark"),
"click"
)
.pipe(takeUntil(this.closed$))
.subscribe(e => console.log(e));
}
ngOnDestroy() {
this.closed$.next();
}
}
应用程序组件.html
<div #showcaseContentText class="text-md-left text-muted mb-lg-6" [innerHTML]="html | safe" style="font-size: 15px">
</div>
安全管道.ts
import { Pipe, PipeTransform } from "@angular/core";
import { DomSanitizer, SafeHtml } from "@angular/platform-browser";
@Pipe({
name: "safe",
pure: true
})
export class SafePipe implements PipeTransform {
constructor(protected sanitizer: DomSanitizer) {}
public transform(value: any): SafeHtml {
return this.sanitizer.bypassSecurityTrustHtml(value);
}
}
更新:<mark>
单个标签中有多个标签innerHTML
在这种情况下,您可以使用querySelectorAll()
该函数来代替querySelector()
。此外,由于会有多个元素,您可以使用Array#map
withfromEvent
和 RxJSmap
运算符来获取各自的id
s。
请注意,我们创建了多个订阅流。因此标签的数量越多mark
,流的数量就越多。当组件关闭时(例如takeUntil
使用),您需要关闭它。有更好的方法来处理多个订阅(例如使用combineLatest
),但它们都有自己的优点和缺点。我将把它们留给你来解决。
控制器
export class AppComponent implements AfterViewInit, OnDestroy {
@ViewChild("showcaseContentText") showcaseContentText: ElementRef<any>;
html =
"Lorem ipsum dolor sit amet, <mark id='mark1' (click)='hello('my name is what')'>consectetur adipiscing elit</mark>. Lorem ipsum <mark id='mark2' (click)='hello('my name is two')'>dolor sit amet</mark>, consectetur adipiscing elit";
closed$ = new Subject<any>();
constructor(private cdr: ChangeDetectorRef) {}
ngAfterViewInit() {
this.cdr.detectChanges();
const obs$ = Array.from(
this.showcaseContentText.nativeElement.querySelectorAll("mark")
).map((el: HTMLElement) => fromEvent(el, "click").pipe(map(_ => el["id"])));
obs$.forEach(obs =>
obs.pipe(takeUntil(this.closed$)).subscribe({
next: id => {
console.log(id);
}
})
);
}
ngOnDestroy() {
this.closed$.next();
}
}
添加回答
举报