I'm writing some content via markdown (because I want to learn md and why not) and I've connected my Angular app to my aws dynamodb via Nestjs. I'm storing markdown as an object in my table and converting it to html in a custom pipe and using a couple libraries:
import { Pipe, PipeTransform } from '@angular/core';
import { unified } from 'unified';
import remarkParse from 'remark-parse';
import remarkRehype from 'remark-rehype';
import rehypeStringify from 'rehype-stringify';
@Pipe({
name: 'convertToHtml',
standalone: true,
})
export class ConvertToHtmlPipe implements PipeTransform {
async transform(markdown: string): Promise<string> {
const res = await unified()
.use(remarkParse)
.use(remarkRehype)
.use(rehypeStringify)
.process(markdown);
const addAttributesToTags = (html: string): string => {
const doc = new DOMParser().parseFromString(html, 'text/html');
const images = Array.from(doc.getElementsByTagName('img'));
for (const image of images) {
image.setAttribute('width', '960');
}
const headings = Array.from(doc.getElementsByTagName('h1'));
for (const heading of headings) {
heading.setAttribute('style', 'color: white;');
}
return doc.body.innerHTML;
};
const newString = addAttributesToTags(String(res));
console.log(newString);
return newString;
}
}
The above is my attempt to add styles to the markdown before its rendered and it works for the img tag but not for the h1 tag. The img tag has its own props for styling unlike h1 so I'm assuming that's why, but the output string correctly transforms the strings into what I want (it just doesnt render it correctly):
<h1 style="color: white;">The unfortunate reality of <em>feeling good</em></h1>
<p><img src="--s3 src--" alt="alt text" width="960"></p>
Next, I'm using this output to render it in my template:
<style>
.article-container {
/* max-width: 970px; */
color: white;
}
.article-container > h1 {
color: red;
}
</style>
<ng-container *ngFor="let article of articles$ | async">
<div
class="article-container"
[innerHTML]="article.content | convertToHtml | async"
></div>
</ng-container>
The styles for the article-container work as expected but the font isn't red so not only is the styles I added directly to the string not working but the styles in the template itself isnt correctly updating the tag.
I know this whole idea isn't great because I'm pasting in html which is obviously dangerous, but I really want to be able to write md in vim, upload to dynamo and see it correctly rendered once refreshing my site.
Any ideas?