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();
? }
}
添加回答
舉報