我正在构建一个 CMS,并且当文章正文更改以在预览中显示语法高亮显示时,我正在尝试重新渲染 Prism.js。
模板:
<textarea
[(ngModel)]="article.body"
(ngModelChange)="onBodyChange($event)"
formControlName="body" type="text" name="body">
</textarea>
组件( ngAfterViewChecked() 有效,但 onBodyChange() 无效):
onBodyChange() {
this.highlightService.highlightAll();
this.highlighted = true;
}
ngAfterViewChecked() {
if (this.article && !this.highlighted) {
this.highlightService.highlightAll();
this.highlighted = true;
}
}
有些人建议使用以下方法重新渲染 Prism.js,但我对如何实现它有点困惑:
Prism.highlightElement(precode);
这是服务:
import { Injectable, Inject } from '@angular/core';
import { PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import 'clipboard';
import 'prismjs';
import 'prismjs/plugins/toolbar/prism-toolbar';
import 'prismjs/plugins/copy-to-clipboard/prism-copy-to-clipboard';
import 'prismjs/components/prism-css';
import 'prismjs/components/prism-javascript';
import 'prismjs/components/prism-markup';
import 'prismjs/components/prism-typescript';
import 'prismjs/components/prism-scss';
declare var Prism: any;
@Injectable()
export class HighlightService {
constructor(@Inject(PLATFORM_ID) private platformId: Object) { }
highlightAll() {
if (isPlatformBrowser(this.platformId)) {
Prism.highlightAll();
}
}
}