
在现代 Web 应用中,展示代码片段并进行语法高亮是一个常见需求。Prism.js 是一个轻量级、可扩展的语法高亮库,因其简洁高效而广受欢迎。然而,当代码内容不是静态存在于 HTML 中,而是从数据库或其他异步源动态加载到 Angular 组件时,Prism.js 往往不会自动对新内容进行高亮。这通常会导致新加载的代码显示为纯文本,而非预期的带颜色高亮效果。
本教程将详细阐述如何在 Angular 应用中解决这一问题,确保动态加载的代码内容能够被 Prism.js 正确识别并高亮显示。
Prism.js 在页面加载时会扫描 DOM,查找带有特定 language-xxx 类的 <pre><code> 结构,并对其内容进行语法高亮。当通过 JavaScript 或 Angular 的数据绑定动态更改这些 <pre><code> 标签内的文本内容时,Prism.js 不会默认重新扫描并高亮这些更新。为了使新内容生效,我们需要手动触发 Prism.js 的高亮机制。
Prism.js 提供了两种主要的刷新方法:
为了在 Angular 应用中动态刷新 Prism.js 高亮,我们需要在代码内容更新后,且 DOM 已经渲染了新内容时,调用 Prism.highlightElement() 方法。Angular 的数据绑定和生命周期钩子提供了完美的集成点。
首先,确保您的 HTML 模板遵循 Prism.js 的推荐结构,通常是 <pre><code> 组合,并绑定动态内容和语言类型。textarea 用于用户输入或显示原始文本,而 pre/code 组合用于高亮显示。
<form [formGroup]="form">
<div class="code-container line-numbers">
<!-- textarea 用于显示或编辑原始代码,通常与 formControlName 绑定 -->
<textarea
#textArea
class="text-area-code-editor"
formControlName="content"
spellcheck="false"
></textarea>
<!-- pre 标签通常用于行号和滚动同步,code 标签用于 Prism.js 高亮 -->
<pre #pre>
<code [ngClass]="['code', 'language-' + codeType]" #codeContent>{{currentCode}}</code>
</pre>
</div>
</form>关键点:
在 Angular 组件中,我们需要管理代码内容、触发更新,并在 DOM 更新后通知 Prism.js 进行高亮。
import { Component, OnInit, AfterViewInit, AfterViewChecked, OnDestroy, ViewChild, ElementRef, Renderer2 } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Subscription, fromEvent } from 'rxjs';
import * as Prism from 'prismjs'; // 确保正确导入 Prism.js
// 假设 DataService, ApiService, PrismService 已经定义
// PrismService 可能是一个封装了 Prism.js 方法的自定义服务,
// 但为了直接演示,我们此处直接使用 Prism 模块。
@Component({
selector: 'app-display-sourcecode',
templateUrl: './display-sourcecode.component.html',
styleUrls: ['./display-sourcecode.component.css']
})
export class DisplaySourcecodeComponent implements OnInit, AfterViewInit, AfterViewChecked, OnDestroy {
codeList: any[] = [];
currentCode = ''; // 绑定到 <code> 标签的内容
codeType = 'java'; // 初始代码语言
form: FormGroup; // 表单组,用于管理 textarea 内容
// 获取模板中的元素引用
@ViewChild('textArea', { static: true }) textArea!: ElementRef;
@ViewChild('codeContent', { static: true }) codeContent!: ElementRef;
@ViewChild('pre', { static: true }) pre!: ElementRef; // 确保 pre 标签存在于模板中
private sub!: Subscription; // 用于管理订阅
// 标志位,用于控制 ngAfterViewChecked 中的高亮逻辑
highlighted = false;
constructor(
private data_service: any, // 替换为实际的服务类型
private api_service: any, // 替换为实际的服务类型
private prismService: any, // 替换为实际的服务类型,如果存在
private fb: FormBuilder,
private renderer: Renderer2
) {
this.form = this.fb.group({
content: [''] // 初始化表单控件
});
}
ngOnInit(): void {
this.listenForm(); // 监听表单变化
this.synchronizeScroll(); // 同步滚动
this.loadSourceCodes(); // 页面初始化时加载代码
}
ngAfterViewInit() {
// 视图初始化后,对初始内容进行高亮
// 确保 Prism.js 脚本已加载且 codeContent 元素存在
if (this.codeContent && this.codeContent.nativeElement.textContent && typeof Prism !== 'undefined' && Prism.highlightElement) {
Prism.highlightElement(this.codeContent.nativeElement);
}
}
ngAfterViewChecked() {
// ngAfterViewChecked 在每次 Angular 检查完组件视图及其子视图后调用。
// 我们利用 'highlighted' 标志来精确控制何时重新高亮。
if (this.highlighted && this.codeContent && this.codeContent.nativeElement) {
if (typeof Prism !== 'undefined' && Prism.highlightElement) {
Prism.highlightElement(this.codeContent.nativeElement);
} else {
console.warn('Prism.highlightElement is not available. Ensure Prism.js is loaded correctly.');
}
this.highlighted = false; // 重置标志,避免不必要的重复高亮
}
}
ngOnDestroy() {
this.sub?.unsubscribe(); // 取消所有订阅,防止内存泄漏
}
// 监听 textarea 内容变化,并更新 code 块
private listenForm() {
this.sub = this.form.valueChanges.subscribe((val) => {
// 假设 prismService.convertHtmlIntoString 负责将 textarea 内容转换为纯文本
const modifiedContent = this.prismService.convertHtmlIntoString(val.content);
this.renderer.setProperty(this.codeContent.nativeElement, 'innerHTML', modifiedContent);
this.highlighted = true; // 设置标志,在 ngAfterViewChecked 中触发高亮
});
}
// 同步 textarea 和 pre 标签的滚动
private synchronizeScroll() {
const localSub = fromEvent(this.textArea.nativeElement, 'scroll').subscribe(() => {
const toTop = this.textArea.nativeElement.scrollTop;
const toLeft = this.textArea.nativeElement.scrollLeft;
if (this.pre) { // 确保 pre 元素存在
this.renderer.setProperty(this.pre.nativeElement, 'scrollTop', toTop);
this.renderer.setProperty(this.pre.nativeElement, 'scrollLeft', toLeft + 0.2);
}
});
this.sub.add(localSub);
}
// 从数据库加载代码后,显示特定代码片段的方法
displaySourceCode(item: any): void {
// 1. 更新绑定到 `<code>` 标签的 `currentCode` 属性
this.currentCode = item.code;
this.codeType = item.language || 'java'; // 假设 item 中包含语言信息
// 2. 如果 `textarea` 也需要显示此内容,则更新表单控件
// 使用 { emitEvent: false } 避免触发 `valueChanges` 订阅,从而防止无限循环。
this.form.get('content')?.setValue(item.code, { emitEvent: false });
// 3. 设置 `highlighted` 标志,通知 `ngAfterViewChecked` 进行高亮刷新
this.highlighted = true;
}
// 从 API 加载所有代码列表
loadSourceCodes(): void {
this.codeList = [];
this.api_service.getSourceCodes().subscribe((data: any[]) => {
this.codeList = data;
// 示例:加载后显示第一段代码
if (this.codeList.length > 0) {
this.displaySourceCode(this.codeList[0]);
}
});
}
}以上就是在 Angular 应用中动态刷新 Prism.js 语法高亮的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号