Angular Custom Markdown Pipe Example

By Hardik Savani May 2, 2024 Category : Angular

Hi,

In this tutorial we will go over the demonstration of how to create markdown pipe in angular. i would like to share with you angular markdown to html pipe. Here you will learn angular custom markdown pipe example. We will look at example of angular markdown pipe example.

if you have question what is markdown then i will show you. Markdown is an uncomplicated text format whose purpose is to be relentless to read and write, even when not converted to HTML. in this example we will use npm marked package to parse html. so let's see bellow step by step example.

you can easily create custom pipe for markdown convert html in angular 7, angular 8, angular 9, angular 10, angular 11, angular 12, angular 13, angular 14, angular 15, angular 16 and angular 17 version.

Step 1: Create New App

If you are doing example from scratch then You can easily create your angular app using bellow command:

ng new my-app

Step 2: Install marked package

In this step, we will install marked npm package.

npm i marked

Step 3: Create Custom Pipe

We need to run following command to creating pipe in angular application.

ng generate pipe markdown

Now we need to write some logic on our custom pipe ts file. so let's write logic as i written for demo now.

app/markdown.pipe.ts

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

import marked from "marked";

@Pipe({

name: 'markdown'

})

export class MarkdownPipe implements PipeTransform {

transform(value: any, args?: any[]): any {

if (value && value.length > 0) {

return marked(value);

}

return value;

}

}

now it should be import in module.ts file as bellow:

app/app.module.ts

import { BrowserModule } from '@angular/platform-browser';

import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

import { MarkdownPipe } from './markdown.pipe';

@NgModule({

declarations: [

AppComponent,

MarkdownPipe

],

imports: [

BrowserModule

],

providers: [],

bootstrap: [AppComponent]

})

export class AppModule { }

Step 4: Use Custom Pipe

Now we need to create one variables and use it, let's add code as like bellow:

app/app.component.ts

import { Component } from '@angular/core';

@Component({

selector: 'app-root',

templateUrl: './app.component.html',

styleUrls: ['./app.component.css']

})

export class AppComponent {

public title: string = '**The Big Post Angular**';

public body: string = 'Custom **Markdown in Angular** example!';

}

Ok, now we can use 'markdown' custom pipe in html file, so let's write it.

app/app.component.html

<div class="container-fluid">

<h1>Angular Markdown Custom Pipe Example - ItSolutionStuff.com</h1>

<h1 [innerHTML]="title | markdown"></h1>

<p [innerHTML]="body | markdown"></p>

</div>

Output:

I hope it can help you...

Tags :
Shares