Add a blog to your Angular website using markdown files

Installation

npm install ngx-markdown --save

Content

  • assets > blog > blog.md: the list of blog entries
  • assets > blog > post > *.md: the articles (= blog posts) themselves

Routes

  • A route “/blog” which will display a list of all articles
  • A route “/blog/post/name-of-the-article” which will display a particular blog post. In this route example the blog post name is “name-of-the-article”

Implementation

@NgModule({
imports: [
CommonModule,
RouterModule.forChild([
{path: '', pathMatch: 'full', loadChildren: './blog/blog-view.module#BlogViewModule'},
{path: 'post', loadChildren: './post/blog-post-view.module#BlogPostViewModule'},
]),
MarkdownModule.forRoot()
]
})

Blog

@NgModule({
declarations: [BlogViewComponent],
imports: [
CommonModule,
RouterModule.forChild([
{ path: '', component: BlogViewComponent}
]),
ComponentsModule,
MarkdownModule.forChild()
]
})
<div markdown [src]="'./assets/blog/blog.md'"></div>
##  [Title](/blog/post/name-of-the-article)
### [Subtitle](/blog/post/
name-of-the-article)
Posted by [David](mailto:david@fluster.io) on September 6, 2018

Post

@NgModule({
declarations: [BlogPostViewComponent],
imports: [
CommonModule,
RouterModule.forChild([
{ path: '', component: BlogPostViewComponent},
{ path: ':id', component: BlogPostViewComponent, pathMatch: 'full'}
]),
ComponentsModule,
MarkdownModule.forChild()
]
})
<div markdown [src]="post"></div>
@Component({
selector: 'app-blog-post-view',
styleUrls: ['./blog-post-view.component.scss'],
templateUrl: './blog-post-view.component.html'
})
export class BlogPostViewComponent implements OnInit, OnDestroy {

private sub: Subscription;

post: string;

constructor(private route: ActivatedRoute) {

}

ngOnInit() {
this.sub = this.route.params.subscribe(params => {
this.post = './assets/blog/post/' + params['id'] + '.md';
});
}

ngOnDestroy() {
if (this.sub) {
this.sub.unsubscribe();
}
}

}

Cherry on the cake 🍒🎂

Bonus hack 🤖

import {Inject, Injectable, PLATFORM_ID} from '@angular/core';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';

import {isPlatformServer} from '@angular/common';

import {Observable} from 'rxjs'

@Injectable({
providedIn: 'root'
})
export class HttpInterceptorService implements HttpInterceptor {

constructor(@Inject(PLATFORM_ID) private platformId: Object) {
}

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (isPlatformServer(this.platformId) && req.url.includes('./')) {
return next.handle(req.clone({
url: `http://localhost:8000/${req.url.replace('./', '')}`
}));
}

return next.handle(req);
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
David Dal Busco

David Dal Busco

Freelancer by day | Creator of Papy.rs by night