Monty  Boehm

Monty Boehm

1626696300

Render Angular Components Using Plain Text

I recently  tweeted about the ability to use plain text to render Angular components. This made some people curious as to how I did it. So let me explain:

Actually, it quite simple. The “trick” is to use Web Components. Thanks to the Angular elements package, we can create native custom elements from Angular components. This way, we can use the native innerHTML property, passing a plain string that contains our custom elements, and let Angular do the rest.

In this article, I’ll not go over the Angular elements API. If you want to know how it works under the hood, I highly recommend reading one of my previous articles:

Let’s create an AlertComponent so that we have something to work it:

import { CommonModule } from '@angular/common';
import { Component, Input, NgModule } from '@angular/core';

@Component({
  selector: 'app-alert',
  template: `
    <div class="alert alert-{{ type }}" role="alert">
     <ng-content></ng-content>
    </div>
  `
})
export class AlertComponent {
  @Input() type = 'primary';
}

@NgModule({
  imports: [CommonModule]
})
export class AlertModule {}

#angular #javascript #angular2

Render Angular Components Using Plain Text