DevEmma
DevEmma

Reputation: 19

Store angular components in database

I'm looking into the possibility to store components in a database and add them to the Angular application. I see the hinder to add components from a database at runtime with the AOT compiler. My other thought is to store HTML (with usage of ng modules like *ngIf etc.) and CSS for the component in the database and assign it to the component template and styles by fetching the data in the ngInit() function. The main goal is to be able to alter the HTML/CSS from the database.

Does anyone have any thought, experience or tips on this?

Thank you!

Upvotes: 1

Views: 1650

Answers (1)

davidveen
davidveen

Reputation: 388

Storing HTML in a database and loading that into a component at runtime, as you suggest, is entirely possible.

On the Angular side, it's as simple as:

<div [innerHtml]="queryResult()">
  whatever is in here will be replaced when queryResult returns
</div>

In the contexts of headless CMSs specifically this is not at all uncommon. Say you want a user to generate content but want angular to do the page layout. Then the user will generate (rich) content through the CMS, which stores (a modified version of it) as a blob in your database, and creates a back-end endpoint for your front-end to access it. Angular in turn will request that content on component load (through a content.service for example) and take care of the actual view. Angular handles proper sanitization of the HTML string when you use the [innerHtml] property as shown, so it shouldn't be a security concern.

I don't know your use case, but I wouldn't suggest directly storing HTML in the database. I'd strongly suggest using a headless CMS to handle that for you, but it really depends on your stack and use case.

Upvotes: 2

Related Questions