Product
Introducing License Enforcement in Socket
Ensure open-source compliance with Socket’s License Enforcement Beta. Set up your License Policy and secure your software!
ngx-markdown
Advanced tools
Angular 2+ library that uses marked to parse markdown to html combined with Prism.js for synthax highlights
ngx-markdown is an Angular library that allows you to use Markdown in your Angular applications. It provides a set of directives and services to easily render Markdown content.
Render Markdown from a string
This feature allows you to render Markdown content directly from a string within your Angular templates.
<markdown># Hello World</markdown>
Render Markdown from a URL
This feature allows you to render Markdown content from an external file by specifying the URL.
<markdown src="path/to/markdown/file.md"></markdown>
Render Markdown from a variable
This feature allows you to bind a variable containing Markdown content to the markdown component.
<markdown [data]="markdownContent"></markdown>
Syntax highlighting
This feature allows you to enable syntax highlighting for code blocks within your Markdown content.
<markdown [data]="markdownContent" [lineNumbers]="true"></markdown>
Marked is a low-level Markdown compiler for parsing Markdown without caching or blocking for long periods of time. It is more lightweight compared to ngx-markdown and can be used in various JavaScript environments, not just Angular.
Showdown is a bidirectional Markdown to HTML to Markdown converter written in JavaScript. It is highly customizable and can be used in both client-side and server-side applications. Unlike ngx-markdown, it is not specifically designed for Angular.
React-markdown is a Markdown component for React. It allows you to render Markdown content in React applications. While ngx-markdown is tailored for Angular, react-markdown is specifically designed for React.
v1.6.0 Repository has been updated to Angular 6 and now uses
HttpClient
instead ofHttp
service.
Please use a previous version of the package if you are using an older version of Angular.
ngx-markdown is an Angular 2+ library that uses marked to parse markdown to html combined with Prism.js for syntax highlight.
To add ngx-markdown library to your package.json
use the following command.
npm install ngx-markdown --save
As the library is using marked parser you will need to add node_modules/marked/lib/marked.js
to your application.
If you are using Angular CLI you can follow the angular.json
example below...
"scripts": [
+ "node_modules/marked/lib/marked.js"
]
Syntax highlight is optional, skip this step if you are not planning to use it
To add Prism.js syntax highlight to your package.json
use the following command.
npm install prismjs --save
To activate Prism.js syntax highlight you will need to include...
node_modules/prismjs/prism.js
filenode_modules/prismjs/themes
directorynode_modules/prismjs/components
directoryAdditional 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
]
You must import MarkdownModule
inside your main application module (usually named AppModule) with forRoot
to be able to use markdown
component and/or directive.
import { NgModule } from '@angular/core';
+ import { MarkdownModule } from 'ngx-markdown';
import { AppComponent } from './app.component';
@NgModule({
imports: [
+ MarkdownModule.forRoot(),
],
declarations: [AppComponent],
bootstrap: [AppComponent],
})
export class AppModule { }
Optionaly, markdown parsing can be configured by passing MarkedOptions to the forRoot
method of MarkdownModule
.
import { MarkdownModule, MarkedOptions } from 'ngx-markdown';
// using default options
MarkdownModule.forRoot(),
// using specific options with ValueProvider
MarkdownModule.forRoot({
provide: MarkedOptions,
useValue: {
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: false,
smartLists: true,
smartypants: false,
},
}),
MarkedOptions
also exposes the renderer
property which allows you to override token rendering for your whole application.
The example below overrides the default blockquote token rendering by adding a CSS class for custom styling when using Bootstrap CSS:
import { MarkedOptions, MarkedRenderer } from 'ngx-markdown';
// function that returns `MarkedOptions` with renderer override
export function markedOptionsFactory(): MarkedOptions {
const renderer = new MarkedRenderer();
renderer.blockquote = (text: string) => {
return '<blockquote class="blockquote"><p>' + text + '</p></blockquote>';
};
return {
renderer: renderer,
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: false,
smartLists: true,
smartypants: false,
};
}
// using specific option with FactoryProvider
MarkdownModule.forRoot({
provide: MarkedOptions,
useFactory: markedOptionsFactory,
}),
Use forChild
when importing MarkdownModule
into other application modules to allow you to use the same parser configuration accross your application.
import { NgModule } from '@angular/core';
+ import { MarkdownModule } from 'ngx-markdown';
import { HomeComponent } from './home.component';
@NgModule({
imports: [
+ MarkdownModule.forChild(),
],
declarations: [HomeComponent],
})
export class HomeModule { }
ngx-markdown
provides different approaches to help you parse markdown to your application depending of your needs.
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
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 loading error using error
output event property.
<!-- static markdown -->
<markdown ngPreserveWhitespaces>
# Markdown
</markdown>
<!-- loaded from remote url -->
<markdown [src]="'path/to/file.md'" (error)="onError($event)"></markdown>
<!-- variable binding -->
<markdown [data]="markdown"></markdown>
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'" (error)="onError($event)"></div>
<!-- variable binding -->
<div markdown [data]="markdown"></div>
Using markdown
pipe to transform markdown to HTML allow you to chain pipe transformations and will update the DOM when value changes.
<!-- chain `language` pipe with `markdown` pipe to convert typescriptMarkdown variable content -->
<div [innerHTML]="typescriptMarkdown | language : 'typescript' | markdown"></div>
You can use MarkdownService
to have access to markdown parser 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.compile('I am using __markdown__.'));
}
}
Tokens can be render in a custom manner by either...
renderer
property with the MarkedOptions
when importing MarkdownModule.forRoot()
into your main application module (see Configuration section)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 { 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 = (text: string, level: number) => {
const escapedText = text.toLowerCase().replace(/[^\w]+/g, '-');
return '<h' + level + '>' +
'<a name="' + escapedText + '" class="anchor" href="#' + escapedText + '">' +
'<span class="header-link"></span>' +
'</a>' + text +
'</h' + level + '>';
};
}
}
This code will output the following HTML:
<h1>
<a name="heading" class="anchor" href="#heading">
<span class="header-link"></span>
</a>
Heading
</h1>
Follow official marked.renderer documentation for the list of tokens that can be overriden.
When using static markdown you are responsible to provide the code block with related language.
<markdown>
+ ```typescript
const myProp: string = 'value';
+ ```
</markdown>
When using remote url ngx-markdown will use 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>
A demo is available @ https://jfcere.github.io/ngx-markdown and it source code can be found inside the src/app/markdown-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
ng serve
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.
Here is the list of tasks that will be done on this library in a near future ...
Contributions are always welcome, just make sure that ...
Licensed under MIT.
FAQs
Angular library that uses marked to parse markdown to html combined with Prism.js for synthax highlights
The npm package ngx-markdown receives a total of 121,128 weekly downloads. As such, ngx-markdown popularity was classified as popular.
We found that ngx-markdown demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Ensure open-source compliance with Socket’s License Enforcement Beta. Set up your License Policy and secure your software!
Product
We're launching a new set of license analysis and compliance features for analyzing, managing, and complying with licenses across a range of supported languages and ecosystems.
Product
We're excited to introduce Socket Optimize, a powerful CLI command to secure open source dependencies with tested, optimized package overrides.