ngx-markdown

jfcereMIT活跃维护

Angular 生态里的 Markdown 渲染组件,能把静态、动态或远程内容解析成带语法高亮、Emoji、KaTeX 公式和 Mermaid 图表的 HTML。

Angular markdown component/directive/pipe/service to parse static, dynamic or remote content to HTML with syntax highlight and more...

v22.1.1发布于 2026-10-16 00:43 UTC1,197star184fork同步于 2026-11-10 17:52 UTC

怎么上手

由 README 提炼,执行前请确认
npm install ngx-markdown marked@^18.0.0 --save
硬件要求按 README 说明

README 未说明

下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

Angular 的 Markdown 渲染库,把静态、动态或远程内容转成带高亮的 HTML

Angular 生态里的 Markdown 渲染组件,能把静态、动态或远程内容解析成带语法高亮、Emoji、KaTeX 公式和 Mermaid 图表的 HTML。

核心能力

  • 用 Marked 把 Markdown 解析为 HTML
  • 集成 Prism.js 做代码语法高亮
  • 支持 KaTeX 数学公式与 Mermaid 图表
  • 提供组件、指令、管道、服务四种用法
  • 可绑定 data 变量或通过 src 加载远程内容

容易踩的坑

语法高亮需额外安装 prismjs@^1.30.0 并在 angular.json 中手动引入核心库、主题和语言文件;Angular 6 起模板编译器默认去空白,需加 ngPreserveWhitespaces 否则 Markdown 换行渲染异常;markdown 管道返回 Promise,模板中必须配合 async 管道使用

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本v22.1.1
  1. v22.1.1最新正式版2026-10-16 · 2026-10-16 00:43 UTC

    Security fixes

    Full Changelog: https://github.com/jfcere/ngx-markdown/compare/v22.1.0...v22.1.1

  2. v22.1.02026-09-26 · 2026-09-26 02:12 UTC
    查看更新说明

    New features and enhancements

    Special Thanks

    🥇 Thanks to @Kirskov for his first contribution in https://github.com/jfcere/ngx-markdown/pull/692

    Full Changelog: https://github.com/jfcere/ngx-markdown/compare/v22.0.2...v22.1.0

  3. v22.0.22026-08-29 · 2026-08-29 21:39 UTC
    查看更新说明

    Fix a regression introduced in v22.0.1 that prevented KaTeX from rendering when marked-katex-extension and katex were installed and the katex attribute was enabled. This restores the previous KaTeX behaviour.

    Bug fixes

    Known limitation

    Due to a limitation in Vite's handling of optional peer dependencies, applications that do not use KaTeX may still encounter a dev-server error when marked-katex-extension is not installed.

    As a workaround, add the following to the build.options section of angular.json:

    {
      "externalDependencies": [
        "marked-katex-extension"
      ]
    }
    

    Applications using the katex attribute still need to install both marked-katex-extension and katex.

    A cleaner solution that allows KaTeX to be explicitly included or excluded will be provided in the next major version. The related issue #681 has been reopened to track this follow-up work.

    Full Changelog: https://github.com/jfcere/ngx-markdown/compare/v22.0.1...v22.0.2

  4. v22.0.12026-08-29 · 2026-08-29 21:11 UTC
    查看更新说明

    New features and enhancements

    Bug fixes

    Security fixes

    Full Changelog: https://github.com/jfcere/ngx-markdown/compare/v22.0.0...v22.0.1

  5. v22.0.02026-06-10 · 2026-06-10 05:00 UTC
    查看更新说明

    Update Angular 22

    It is recommended to stick with ngx-markdown v21.x.x if you are using Angular 21.

    New features and enhancements

    • Add support for Angular 22
    • Migrate math rendering with KaTeX from katex/auto-render to marked-katex-extension fixing important rendering problems
    • Deprecate MarkdownModule, which will be removed in the next major release in favour of provideMarkdown

    ⚠ Breaking changes

    Fix for KaTeX math rendering
    • KaTeX support now requires the optional marked-katex-extension package in addition to katex.
    • Global KaTeX options can now be provided through the new katexOptions provider config in MarkdownModule.forRoot() or provideMarkdown() using the KATEX_OPTIONS injection token.
    • Updated KaTeX installation instructions: include katex.min.css and do not rely on the old KaTeX auto-render script configuration.
    Migration guidance

    Remove the old KaTeX script entries and keep styles entry from angular.json:

    "styles": [
    + "node_modules/katex/dist/katex.min.css"
    ],
    "scripts": [
    - "node_modules/katex/dist/katex.min.js",
    - "node_modules/katex/dist/contrib/auto-render.min.js",
    ]
    

    Install new extension:

    npm install katex@^0.16.0 marked-katex-extension@^5.0.0 --save
    

    If you previously used MarkdownService.render() with katex or katexOptions, move KaTeX configuration to the new provider-style setup and enable KaTeX at parse time instead.

    📘 See the Math Rendering section in the README.md for more information.

    Commits

    Security fixes

    Full Changelog: https://github.com/jfcere/ngx-markdown/compare/v21.3.0...v22.0.0

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    ngx-markdown

    ngx-markdown is an Angular library that combines...

    Demo available @ https://jfcere.github.io/ngx-markdown
    StackBlitz available @ https://stackblitz.com/edit/ngx-markdown

    Table of contents

    Installation

    ngx-markdown

    To add ngx-markdown along with the required marked library to your package.json use the following commands.

    npm install ngx-markdown marked@^18.0.0 --save
    

    Syntax highlight

    :bell: Syntax highlight is optional, skip this step if you are not planning to use it

    To add Prism.js library to your package.json use the following command.

    npm install prismjs@^1.30.0 --save
    

    To activate Prism.js syntax highlight you will need to include...

    • prism.js core library - node_modules/prismjs/prism.js file
    • a highlight css theme - from node_modules/prismjs/themes directory
    • desired code language syntax files - from node_modules/prismjs/components directory

    Additional themes can be found by browsing the web such as Prism-Themes or Mokokai for example.

    If you are using Angular CLI you can follow the angular.json example below...

    "styles": [
      "styles.css",
    + "node_modules/prismjs/themes/prism-okaidia.css"
    ],
    "scripts": [
    + "node_modules/prismjs/prism.js",
    + "node_modules/prismjs/components/prism-csharp.min.js", # c-sharp language syntax
    + "node_modules/prismjs/components/prism-css.min.js" # css language syntax
    ]
    
    Line Numbers plugin

    To use the line numbers plugin that shows line numbers in code blocks, in addition to Prism.js configuration files, you will need to include the following files from prismjs/plugins/line-numbers directory to your application:

    • CSS styling for line numbers - prism-line-numbers.css
    • line numbers plugin script - prism-line-numbers.js

    If you are using Angular CLI you can follow the angular.json example below...

    "styles": [
      "src/styles.css",
      "node_modules/prismjs/themes/prism-okaidia.css",
    + "node_modules/prismjs/plugins/line-numbers/prism-line-numbers.css"
    ],
    "scripts": [
      "node_modules/prismjs/prism.js",
      "node_modules/prismjs/components/prism-csharp.min.js",
      "node_modules/prismjs/components/prism-css.min.js",
    + "node_modules/prismjs/plugins/line-numbers/prism-line-numbers.js"
    ]
    

    Using markdown component and/or directive, you will be able to use the lineNumbers property to activate the plugin. The property can be used in combination with either data for variable binding, src for remote content or using transclusion for static markdown.

    Additionally, you can use start input property to specify the offset number for the first display line.

    <markdown
      lineNumbers
      [start]="5"
      [src]="path/to/file.js">
    </markdown>
    
    Line Highlight plugin

    To use the line highlight plugin that highlights specific lines and/or line ranges in code blocks, in addition to Prism.js configuration files, you will need to include the following files from prismjs/plugins/line-highlight directory to your application:

    • CSS styling for line highlight - prism-line-highlight.css
    • line highlight plugin script - prism-line-highlight.js

    If you are using Angular CLI you can follow the angular.json example below...

    "styles": [
      "src/styles.css",
      "node_modules/prismjs/themes/prism-okaidia.css",
    + "node_modules/prismjs/plugins/line-highlight/prism-line-highlight.css"
    ],
    "scripts": [
      "node_modules/prismjs/prism.js",
      "node_modules/prismjs/components/prism-csharp.min.js",
      "node_modules/prismjs/components/prism-css.min.js",
    + "node_modules/prismjs/plugins/line-highlight/prism-line-highlight.js"
    ]
    

    Using markdown component and/or directive, you will be able to use the lineHighlight property to activate the plugin. The property can be used in combination with either data for variable binding, src for remote content or using transclusion for static markdown.

    Use line input property to specify the line(s) to highlight and optionally there is a lineOffset property to specify the starting line of code your snippet represents.

    <markdown
      lineHighlight
      [line]="'6, 10-16'"
      [lineOffset]="5"
      [src]="path/to/file.js">
    </markdown>
    
    Command Line Plugin

    To use the command line plugin that displays a command line with a prompt and, optionally, the output/response from the commands, you will need to include the following files from prismjs/plugins/command-line directory to your application:

    • CSS styling for command line - prism-command-line.css
    • command line plugin script - prism-command-line.js

    If you are using Angular CLI you can follow the angular.json example below...

    "styles": [
      "src/styles.css",
      "node_modules/prismjs/themes/prism-okaidia.css",
    + "node_modules/prismjs/plugins/command-line/prism-command-line.css"
    ],
    "scripts": [
      "node_modules/prismjs/prism.js",
      "node_modules/prismjs/components/prism-csharp.min.js",
      "node_modules/prismjs/components/prism-css.min.js",
    + "node_modules/prismjs/plugins/command-line/prism-command-line.js"
    ]
    

    Using markdown component and/or directive, you will be able to use the commandLine property to activate the plugin. The property can be used in combination with either data for variable binding, src for remote content or using transclusion for static markdown.

    For a server command line, specify the user and host names using the user and host input properties. The resulting prompt displays a # for the root user and $ for all other users. For any other command line, such as a Windows prompt, you may specify the entire prompt using the prompt input property.

    You may also specify the lines to be presented as output (no prompt and no highlighting) through the output property in the following simple format:

    • A single number refers to the line with that number
    • Ranges are denoted by two numbers, separated with a hyphen (-)
    • Multiple line numbers or ranges are separated by commas
    • Whitespace is allowed anywhere and will be stripped off
    <markdown
      commandLine
      [user]="'chris'"
      [host]="'remotehost'"
      [output]="'2, 4-8'"
      [src]="'path/to/file.bash'">
    </markdown>
    

    Optionally, to automatically present some lines as output without providing the line numbers, you can prefix those lines with any string and specify the prefix using the filterOutput input property. For example, [filterOutput]="'(out)'" will treat lines beginning with (out) as output and remove the prefix.

    <markdown
      commandLine
      [prompt]="'PS C:\Users\Chris>'"
      [filterOutput]="'(out)'">
      ```powershell
      Get-Date
      (out)
      (out)Sunday, November 7, 2021 8:19:21 PM
      (out)
      `​``
    </markdown>
    

    Emoji support

    :bell: Emoji support is optional, skip this step if you are not planning to use it

    To add Emoji-Toolkit library to your package.json use the following command.

    npm install emoji-toolkit@^11.0.0 --save
    

    To activate Emoji-Toolkit for emoji suppport you will need to include...

    • Emoji-Toolkit library - node_modules/emoji-toolkit/lib/js/joypixels.min.js

    If you are using Angular CLI you can follow the angular.json example below...

    "scripts": [
    + "node_modules/emoji-toolkit/lib/js/joypixels.min.js",
    ]
    

    Emoji plugin

    Using markdown component and/or directive, you will be able to use the emoji property to activate Emoji-Toolkit plugin that converts emoji shortnames such as :heart: to native unicode emojis.

    <markdown emoji>
      I :heart: ngx-markdown
    </markdown>
    

    :blue_book: You can refer to this Emoji Cheat Sheet for a complete list of shortnames.

    Math rendering

    :warning: Math rendering is optional, and no KaTeX packages are required if you are not planning to use it. However, Angular applications using the Vite-based application builder may need to add marked-katex-extension to externalDependencies in the build.options section of angular.json:

    {
      "externalDependencies": ["marked-katex-extension"]
    }
    

    To add KaTeX math rendering support to your application install the KaTeX runtime and the parser extension:

    npm install katex@^0.16.0 marked-katex-extension@^5.0.0 --save
    

    Applications using the katex property must install both katex and marked-katex-extension.

    To activate KaTeX math rendering you need to include the KaTeX stylesheet:

    "styles": [
      "styles.css",
    + "node_modules/katex/dist/katex.min.css"
    ],
    

    KaTeX plugin

    Using the markdown component and/or directive, you can enable KaTeX rendering with the katex property:

    <markdown
      katex
      [src]="path/to/file.md">
    </markdown>
    

    Global configuration

    Global KaTeX options can be provided with the KATEX_OPTIONS injection token when configuring provideMarkdown().

    provideMarkdown({
      katexOptions: {
        provide: KATEX_OPTIONS,
        useValue: {
          displayMode: false,
          throwOnError: false,
        },
      },
    }),
    

    Component configuration

    Optionally, you can specify the KaTeX options at the component-level through katexOptions property:

    import { KatexOptions } from 'ngx-markdown';
    
    public options: KatexOptions = {
      displayMode: true,
      throwOnError: false,
      errorColor: '#cc0000',
      delimiters: [...],
    };
    
    <markdown
      katex
      [katexOptions]="options"
      [src]="path/to/file.md">
    </markdown>
    

    :blue_book: Follow official KaTeX options documentation for more details on available options.

    Diagrams tool

    :bell: Diagram support is optional, skip this step if you are not planning to use it

    To add Mermaid library to your package.json use the following command.

    npm install mermaid@^11.0.0 --save
    

    To activate Mermaid diagramming and charting tool you will need to include...

    • Mermaid JavaScript library - node_modules/mermaid/dist/mermaid.min.js file

    If you are using Angular CLI you can follow the angular.json example below...

    "scripts": [
    + "node_modules/mermaid/dist/mermaid.min.js",
    ]
    

    Mermaid plugin

    Using markdown component and/or directive, you will be able to use the mermaid property to activate Mermaid plugin that renders Markdown-inspired text definitions to create and modify diagrams dynamically.

    <markdown
      mermaid
      [src]="path/to/file.md">
    </markdown>
    

    Global configuration

    You can provide a global configuration for mermaid configuration options to use across your application with the mermaidOptions when configuring provideMarkdown.

    provideMarkdown({
      mermaidOptions: {
        provide: MERMAID_OPTIONS,
        useValue: {
          darkMode: true,
          look: 'handDrawn',
          ...
        },
      },
    }),
    

    Component configuration

    Additionally, you can specify mermaid configuration options on component directly using mermaidOptions property.

    import { MermaidAPI } from 'ngx-markdown';
    
    public options: MermaidAPI.MermaidConfig = {
      darkMode: true,
      look: 'handDrawn',
      ...
    };
    
    <markdown
      mermaid
      [mermaidOptions]="options"
      [src]="'path/to/file.md'">
    </markdown>
    

    :blue_book: Follow official Mermaid documentation for more details on diagrams and charts syntax.

    Copy-to-clipboard

    :bell: Copy-to-clipboard support is optional, skip this step if you are not planning to use it

    To add Clipboard library to your package.json use the following command.

    npm install clipboard@^2.0.11 --save
    

    To activate Clipboard allowing copy-to-clipboard you will need to include...

    • Clipboard JavaScript library - node_modules/clipboard/dist/clipboard.min.js file

    If you are using Angular CLI you can follow the angular.json example below...

    "scripts": [
    + "node_modules/clipboard/dist/clipboard.min.js",
    ]
    

    Clipboard plugin

    Using markdown component and/or directive, you will be able to use the clipboard property to activate Clipboard plugin that enable copy-to-clipboard for code block from a single click.

    <markdown
      clipboard
      [src]="path/to/file.md">
    </markdown>
    

    Default button

    The clipboard plugin provide an unstyled default button with a default behavior out of the box if no alternative is used.

    Customize button toolbar

    The clipboard button is placed inside a wrapper element that can be customize using the .markdown-clipboard-toolbar CSS selector in your global styles.css/scss file.

    This allows to override the default positionning of the clipboard button and play with the visibility of the button using the .hover CSS selector that is applied on the toolbar when the mouse cursor enters and leaves the code block element.

    Customize default button

    To customize the default button styling, use the .markdown-clipboard-button CSS selector in your global styles.css/scss file. You can also customized the "copied" state happening after the button is clicked using the .copied CSS selector.

    Using global configuration

    You can provide a custom component to use globaly across your application with the clipboardOptions when configuring provideMarkdown.

    provideMarkdown({
      clipboardOptions: {
        provide: CLIPBOARD_OPTIONS,
        useValue: {
          buttonComponent: ClipboardButtonComponent,
        },
      },
    })
    

    Using a component

    You can also provide your custom component using the clipboardButtonComponent input property when using the clipboard directive.

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'app-clipboard-button',
      template: `<button (click)="onClick()">Copy</button>`,
    })
    export class ClipboardButtonComponent {
      onClick() {
        alert('Copied to clipboard!');
      }
    }
    
    import { ClipboardButtonComponent } from './clipboard-button-component';
    
    @Component({ ... })
    export class ExampleComponent {
      readonly clipboardButton = ClipboardButtonComponent;
    }
    
    <markdown 
      clipboard 
      [clipboardButtonComponent]="clipboardButton">
    </markdown>
    

    Using ng-template

    Alternatively, the clipboard directive can be used in conjonction with ng-template to provide a custom button implementation via the clipboardButtonTemplate input property on the markdown component.

    <ng-template #buttonTemplate>
      <button (click)="onCopyToClipboard()">...</button>
    </ng-template>
    
    <markdown 
      clipboard 
      [clipboardButtonTemplate]="buttonTemplate">
    </markdown>
    

    :blue_book: Refer to the ngx-markdown clipboard plugin demo for live examples.

    Configuration

    The ngx-markdown library can be used with standalone components. Use the provideMarkdown provide-function in your application configuration ApplicationConfig to be able to provide the MarkdownComponent and MarkdownPipe to your standalone components and/or inject the MarkdownService.

    import { NgModule } from '@angular/core';
    + import { provideMarkdown } from 'ngx-markdown';
    
    export const appConfig: ApplicationConfig = {
      providers: [
    +   provideMarkdown(),
      ],
    };
    

    Remote file configuration

    If you want to use the [src] attribute to directly load a remote file, in order to keep only one instance of HttpClient and avoid issues with interceptors, you also have to provide HttpClient:

    providers: [
    +  provideHttpClient(),
    +  provideMarkdown({ loader: HttpClient }),
    ],
    

    Sanitization

    Sanitization is enabled by default and uses Angular’s DomSanitizer with SecurityContext.HTML to prevent XSS vulnerabilities. It can be disabled by changing the SecurityContext level using the sanitize property when configuring provideMarkdown.

    import { SecurityContext } from '@angular/core';
    import { SANITIZE } from 'ngx-markdown';
    
    // enable default sanitization
    provideMarkdown()
    
    // disable sanitization
    provideMarkdown({
      sanitize: {
        provide: SANITIZE,
        useValue: SecurityContext.NONE
      },
    })
    

    Because Angular's sanitizer offers limited flexibility, you can use any external library for sanitization such as DOMPurify by providing a custom sanitizer function using the SANITIZE provider token.

    import DOMPurify from 'dompurify';
    import { SANITIZE } from 'ngx-markdown';
    
    // sanitize function using an external library
    function sanitizeHtml(html: string): string {
      DOMPurify.setConfig({ ... });
      return DOMPurify.sanitize(html);
    }
    
    // provide a sanitize function
    provideMarkdown({
      sanitize: {
        provide: SANITIZE,
        useValue: sanitizeHtml,
      },
    })
    

    :blue_book: Follow Angular DomSanitizer documentation for more information on sanitization and security contexts.

    You can bypass sanitization using the markdown component, directive or pipe using the disableSanitizer option as follow:

    <!-- disable sanitizer using markdown component -->
    <markdown
      [data]="markdown"
      [disableSanitizer]="true">
    </markdown>
    
    <!-- disable sanitizer using markdown directive -->
    <div markdown
      [data]="markdown"
      [disableSanitizer]="true">
    </div>
    
    <!-- disable sanitizer using markdown pipe -->
    <div [innerHTML]="markdown | markdown : { disableSanitizer: true } | async"></div>
    

    MarkedOptions

    Optionally, markdown parsing can be configured using MarkedOptions that can be provided with the MARKED_OPTIONS injection token via the markedOptions property when configuring provideMarkdown.

    // imports
    import { MARKED_OPTIONS, provideMarkdown } from 'ngx-markdown';
    
    // using default options
    provideMarkdown(),
    
    // using specific options with ValueProvider and passing HttpClient
    provideMarkdown({
      markedOptions: {
        provide: MARKED_OPTIONS,
        useValue: {
          gfm: true,
          breaks: false,
          pedantic: false,
        },
      },
    }),
    

    MarkedOptions.renderer

    MarkedOptions also exposes the renderer property which allows you to override token rendering for your whole application.

    The example uses a factory function and override the default blockquote token rendering by adding a CSS class for custom styling when using Bootstrap CSS:

    import { Parser } from 'marked';
    import { MARKED_OPTIONS, MarkedOptions, MarkedRenderer } from 'ngx-markdown';
    
    // function that returns `MarkedOptions` with renderer override
    export function markedOptionsFactory(): MarkedOptions {
      const renderer = new MarkedRenderer();
    
      renderer.blockquote = ({ tokens }) => {
        return '<blockquote class="blockquote"><p>' + Parser.parse(tokens) + '</p></blockquote>';
      };
    
      return {
        renderer: renderer,
        gfm: true,
        breaks: false,
        pedantic: false,
      };
    }
    
    // using specific option with FactoryProvider
    provideMarkdown({
      markedOptions: {
        provide: MARKED_OPTIONS,
        useFactory: markedOptionsFactory,
      },
    }),
    

    Marked extensions

    When configuring provideMarkdown, you can provide marked extensions using the MARKED_EXTENSION injection token via the markedExtensions property, which accepts an array of providers and supports Angular dependency injection.

    import { gfmHeadingId } from 'marked-gfm-heading-id';
    
    providemarkdown({
      markedExtensions: [
        {
          provide: MARKED_EXTENSIONS,
          useFactory: gfmHeadingId,
          multi: true,
        },
        {
          provide: MARKED_EXTENSIONS,
          useFactory: myExtensionFactory,
          deps: [SomeService],
          multi: true,
        },
      ],
    }),
    

    Usage

    ngx-markdown provides different approaches to help you parse markdown to your application depending on your needs.

    :bulb: As of Angular 6, the template compiler strips whitespace by default. Use ngPreserveWhitespaces directive to preserve whitespaces such as newlines in order for the markdown-formatted content to render as intended.
    https://angular.io/api/core/Component#preserveWhitespaces

    Component

    You can use markdown component to either parse static markdown directly from your HTML markup, load the content from a remote URL using src property or bind a variable to your component using data property. You can get a hook on load complete using load output event property, on loading error using error output event property or when parsing is completed using ready output event property.

    <!-- static markdown -->
    <markdown ngPreserveWhitespaces>
      # Markdown
    </markdown>
    
    <!-- loaded from remote url -->
    <markdown
      [src]="'path/to/file.md'"
      (load)="onLoad($event)"
      (error)="onError($event)">
    </markdown>
    
    <!-- variable binding -->
    <markdown
      [data]="markdown"
      (ready)="onReady()">
    </markdown>
    
    <!-- inline parser, omitting rendering top-level paragraph -->
    <markdown
      [data]="markdown"
      [inline]="true">
    </markdown>
    

    Directive

    The same way the component works, you can use markdown directive to accomplish the same thing.

    <!-- static markdown -->
    <div markdown ngPreserveWhitespaces>
      # Markdown
    </div>
    
    <!-- loaded from remote url -->
    <div markdown
      [src]="'path/to/file.md'"
      (load)="onLoad($event)"
      (error)="onError($event)">
    </div>
    
    <!-- variable binding -->
    <div markdown
      [data]="markdown"
      (ready)="onReady()">
    </div>
    
    <!-- inline parser, omitting rendering top-level paragraph -->
    <div markdown
      [data]="markdown"
      [inline]="true">
    </div>
    

    Pipe

    Using markdown pipe to transform markdown to HTML allow you to chain pipe transformations and will update the DOM when value changes. It is important to note that, because the marked parsing method returns a Promise, it requires the use of the async pipe.

    <!-- chain `language` pipe with `markdown` pipe to convert typescriptMarkdown variable content -->
    <div [innerHTML]="typescriptMarkdown | language : 'typescript' | markdown | async"></div>
    

    The markdown pipe allow you to use all the same plugins as the component by providing the options parameters.

    <!-- provide options parameters to activate plugins or for configuration -->
    <div [innerHTML]="typescriptMarkdown | language : 'typescript' | markdown : { emoji: true, inline: true } | async"></div>
    

    This is the MarkdownPipeOptions parameters interface, those options are the same as the ones available for the markdown component:

    export interface MarkdownPipeOptions {
      decodeHtml?: boolean;
      inline?: boolean;
      emoji?: boolean;
      katex?: boolean;
      katexOptions?: KatexOptions;
      mermaid?: boolean;
      mermaidOptions?: MermaidAPI.MermaidConfig;
      markedOptions?: MarkedOptions;
      disableSanitizer?: boolean;
    }
    

    Service

    You can use MarkdownService to have access to markdown parsing, rendering and syntax highlight methods.

    import { Component, OnInit } from '@angular/core';
    import { MarkdownService } from 'ngx-markdown';
    
    @Component({ ... })
    export class ExampleComponent implements OnInit {
      constructor(private markdownService: MarkdownService) { }
    
      ngOnInit() {
        // outputs: <p>I am using <strong>markdown</strong>.</p>
        console.log(this.markdownService.parse('I am using __markdown__.'));
      }
    }
    

    Renderer

    Tokens can be rendered in a custom manner by either...

    • providing the renderer property with the MarkedOptions when configuring provideMarkdown() (see Configuration section)
    • using MarkdownService exposed renderer

    Here is an example of overriding the default heading token rendering through MarkdownService by adding an embedded anchor tag like on GitHub:

    import { Component, OnInit } from '@angular/core';
    import { Parser } from 'marked';
    import { MarkdownService } from 'ngx-markdown';
    
    @Component({
      selector: 'app-example',
      template: '<markdown># Heading</markdown>',
    })
    export class ExampleComponent implements OnInit {
      constructor(private markdownService: MarkdownService) { }
    
      ngOnInit() {
        this.markdownService.renderer.heading = ({ tokens, depth }) => {
          const text = Parser.parseInline(tokens);
          const escapedText = text.toLowerCase().replace(/[^\w]+/g, '-');
          return '<h' + depth + '>' +
                   '<a name="' + escapedText + '" class="anchor" href="#' + escapedText + '">' +
                     '<span class="header-link"></span>' +
                   '</a>' + text +
                 '</h' + depth + '>';
        };
      }
    }
    

    This code will output the following HTML:

    <h1>
      <a name="heading" class="anchor" href="#heading">
        <span class="header-link"></span>
      </a>
      Heading
    </h1>
    

    :blue_book: Follow official marked.renderer documentation for the list of tokens that can be overriden.

    Re-render Markdown

    In some situations, you might need to re-render markdown after making changes. If you've updated the text this would be done automatically, however if the changes are internal to the library such as rendering options, you will need to inform the MarkdownService that it needs to update.

    To do so, inject the MarkdownService and call the reload() function as shown below.

    import { MarkdownService } from 'ngx-markdown';
    
    constructor(
      private markdownService: MarkdownService,
    ) { }
    
    update() {
      this.markdownService.reload();
    }
    

    :blue_book: Refer to the ngx-markdown re-render demo for a live example.

    Syntax highlight

    When using static markdown you are responsible to provide the code block with related language.

    <markdown ngPreserveWhitespaces>
    +  ```typescript
        const myProp: string = 'value';
    +  ```
    </markdown>
    

    When using remote URL ngx-markdown will use the file extension to automatically resolve the code language.

    <!-- will use html highlights -->
    <markdown [src]="'path/to/file.html'"></markdown>
    
    <!-- will use php highlights -->
    <markdown [src]="'path/to/file.php'"></markdown>
    

    When using variable binding you can optionally use language pipe to specify the language of the variable content (default value is markdown when pipe is not used).

    <markdown [data]="markdown | language : 'typescript'"></markdown>
    

    Demo application

    A demo is available @ https://jfcere.github.io/ngx-markdown and its source code can be found inside the demo directory.

    The following commands will clone the repository, install npm dependencies and serve the application @ http://localhost:4200

    git clone https://github.com/jfcere/ngx-markdown.git
    npm install
    npm start
    

    AoT compilation

    Building with AoT is part of the CI and is tested every time a commit occurs so you don't have to worry at all.

    Road map

    Here is the list of tasks that will be done on this library in the near future ...

    • Add a FAQ section to the README.md
    • Improve flexibily for some options

    Contribution

    Contributions are always welcome, just make sure that ...

    • Your code style matches with the rest of the project
    • Unit tests pass
    • Linter passes

    Support Development

    The use of this library is totally free and no donation is required.

    As the owner and primary maintainer of this project, I am putting a lot of time and effort beside my job, my family and my private time to bring the best support I can by answering questions, addressing issues and improving the library to provide more and more features over time.

    If this project has been useful, that it helped you or your business to save precious time, don't hesitate to give it a star and to consider a donation to support its maintenance and future development.

    License

    Licensed under MIT.