/ angular

Angular Markdown Pipe

While working on a small Angular side-project (more on that later), I found myself in need of a way to render markdown as HTML. I'm sure there are a lot of ways to go about this, but I decided to go with a Pipe. I like pipes. Anyway, here's how to do it.

Create a new Angular app

(skip this step to add to an existing app):

ng new my-markdown-app && cd my-markdown-app

Add marked to use as the markdown parser

npm install marked

Generate a new Pipe using angular-cli

ng generate pipe marked
# or, if you prefer:
ng g p marked

This will create a new Pipe called 'marked' and import it into your app.module.ts file.

Edit marked.pipe.ts

The file generated above looks like this:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'marked'
})
export class MarkedPipe implements PipeTransform {

  transform(value: any, args?: any): any {
    return null;
  }

}

Edit this file to import marked, then update the transform() function to parse and return HTML. Your file should look something like this:

import { Pipe, PipeTransform } from "@angular/core";
import * as marked from "marked";

@Pipe({
  name: "marked"
})
export class MarkedPipe implements PipeTransform {
  transform(value: any): any {
    if (value && value.length > 0) {
      return marked(value);
    }
    return value;
  }
}

The transform function will accept your text as value, and if it has a length, it returns the parsed HTML. Otherwise, it just returns the value that was passed.

Usage

The usage is similar to other Pipes, except unlike most others, your values need to entered into the innerHTML attribute of your HTML element.For example:

// app.component.ts
...
public markdownString: string = 'This is text with **markdown**';
...

// app.component.html
...
<div [innerHTML]="markdownString | marked"></div>
...