gpt4 book ai didi

javascript - 清理代码片段的 ng-content

转载 作者:行者123 更新时间:2023-11-29 20:55:57 24 4
gpt4 key购买 nike

我有一个使用 PrismJS 的 Angular 组件用于语法高亮代码块。组件如下:

import { Component, AfterViewInit, Input, 
ElementRef, ViewChild, ChangeDetectorRef } from '@angular/core';

declare var Prism: any;

@Component({
selector: 'prism',
template: `
<div hidden="true" #rawContent>
<ng-content></ng-content>
</div>
<section class="code-container">
<pre><code [innerHtml]="content" class="block language-{{language}}"></code></pre>
</section>
`
})
export class PrismComponent implements AfterViewInit {
@Input() language: string;
@ViewChild('rawContent') rawContent: ElementRef;
content: string;

constructor(public cdr: ChangeDetectorRef) {}

ngAfterViewInit() {
this.content = Prism.highlight(this.rawContent.nativeElement.textContent.trim(),
Prism.languages[this.language]);
this.cdr.detectChanges();
}
}

问题是当我使用它时,我必须手动转义任何无效的 HTML 字符。

我试过使用 DomSanitizer .sanitize() 在以下位置的组件元素引用值和 rawContent 引用值上,以尝试规避此问题:

  • 构造器
  • ngOnChanges()
  • ngOnInit()
  • ngAfterViewInit()

当代码块包含无效的 HTML 字符时,Angular 会在任何这些事件发生之前抛出无效字符错误。

我将如何清理 rawContent 中指定的代码块以防止手动转义无效的 HTML 字符?

示例 StackBlitz Solution

最佳答案

使用 CDATA(Character Data):

<prism language="typescript">
<![CDATA[ export class Demo { id: number; name: string; } ]]>
</prism>

关于javascript - 清理代码片段的 ng-content,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49366449/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com