To Parse HTML, Create A Custom Markdown Pipe In Angular 13

New Angular Application Setup

Without the Angular CLI installed on your machine, it is impossible to create a new Angular application. So, enter the command to install the global Angular CLI from the command prompt.

npm install -g @angular/cli

Run the command to build an angular application next; if the app is already installed on your computer, you can skip this step.

ng new demo

Find the project root by navigating to:

cd demo
Install Marked Parser Package

Through NPM, install the indicated Markdown parser plugin. Its low-level and potent compiler allows Markdown to be parsed without long delays or caching.

npm i marked
Angular Pipe creation

To create a new Pipe for your Angular application, go to the command prompt with the Angular CLI.

ng generate pipe markdown

As of right now, two pipe files have been produced, as is evident. To add the following code, open the markdown.pipe.ts file and do so.

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;
  }
}

Let me explain the straightforward reasoning above; the first indicated package gets imported first. The HTML is then parsed using the convert() function.

Markdown Pipe import in AppModule

The MarkdownPipe pipe must then be imported into the app.module.ts file.

import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { MarkdownPipe } from './markdown.pipe';

@NgModule({
  declarations: [
    AppComponent, 
    MarkdownPipe],
  imports: [
    BrowserModule, 
    AppRoutingModule, 
    FormsModule, 
    ReactiveFormsModule],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

We can now put the markdown HTML pipe into use.

Add the code listed below to the app.component.ts file.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  public name: string = '**In The Big Bang Theory**';
  public text: string = 'Custom **Markdown in Angular** example!';
}

Markdown pipe names are used to pass the text or content value to the [innerHTML] directive. In the file app.component.html, add the following code.

<div>
  <h1 [innerHTML]="name | markdown"></h1>
  <p [innerHTML]="text | markdown"></p>
</div>

See the results by running the Angular project.

ng serve --open

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories