How to dynamically render a markdown file in Angular? How to dynamically render a markdown file in Angular? angular angular

How to dynamically render a markdown file in Angular?


Base on the documentation https://www.npmjs.com/package/ngx-markdown#directive you can load file via [src]:

<!-- loaded from remote url --><div markdown [src]="'path/to/file.md'" (load)="onLoad($event)" (error)="onError($event)"></div>


After lot of trail and errors ,there is one more approach for dynamic rendering of markdown using ngx-markdown package via http calls.

use httpclient to make http call for md files

import { HttpClient } from '@angular/common/http';import { MarkdownService } from 'ngx-markdown';    export class AppComponent {          title = 'personal-blog';          markdownRaw ='';          markdown='';     constructor(private mdService:MarkdownService, private _httpClient:HttpClient){}          async ngOnInit() {            this.markdownRaw = await this._httpClient.get(`/assets/hello.md`, {               responseType: 'text'            }).toPromise();                    this.markdown=this.mdService.compile(this.markdownRaw);             }             onLoad(data:any){         console.log(data);          }                   onError(data:any){           console.log(data);          }}  

Now use the declared and initialized variable as data property in markdown directive.

<markdown [data]="markdown" (load)="onLoad($event)" (error)="onError($event)"></markdown>