question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Ivy: Render HTML from String / dynamic rendering

See original GitHub issue

Which @angular/* package(s) are relevant/releated to the feature request?

compiler, core, platform-browser-dynamic, platform-browser

Description

As far as I know the old aproach was to inject the JITCompiler and use it to render your HTML in an anonymous component. This worked so far. I use editable HTML in DB which uses key features as substituting variables and directives like *ngIf or *ngSwitch.

Which does not work anymore in production mode (Angular 12.x) I browsed stackoverflow and other forums to find an workarround for this and these are not working anymore (like loading the JITCompiler into Providers, which results in “JIT Compiler unavailable”.

As I found not soulution for ivy/ng 12 i considered this feature as still missing.

Best,

Malte

Proposed solution

Component to render html strings.

Example:

<render-component [html]="..." [render-data]="{ show: true}></render-component>

[html] has the following value:

"<p *ngIf=\"show\">Hello!</p>"

Which display in the case if show is true:

<p>Hello!</p>

Alternatives considered

An Service to render html on the fly.

E.g.:

p3x-compile Html Compile

Issue Analytics

  • State:open
  • Created 2 years ago
  • Reactions:41
  • Comments:22 (6 by maintainers)

github_iconTop GitHub Comments

4reactions
hydra1983commented, Feb 9, 2022

@joseluratm aot have to be disabled for now.

The change oftsconfig.json is not required.

  ...
  "angularCompilerOptions": {
  ...
  "compilationMode": "partial"
}

The complete component definition should be:

import {
    ChangeDetectionStrategy,
    Component,
    ComponentRef,
    createNgModuleRef,
    Input,
    ModuleWithProviders,
    NgModule,
    NgModuleRef,
    OnChanges,
    OnDestroy,
    OnInit,
    SimpleChanges,
    Type,
    TypeDecorator,
    ViewContainerRef,
  } from '@angular/core';
  import * as _ from 'lodash';
  import { Subject } from 'rxjs';

@Component({
  selector: '[dg-adhoc-html]',
  template: ``,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DgAdhocComponent implements OnChanges, OnInit, OnDestroy {
  constructor(private vcr: ViewContainerRef) {
  }

  @Input('dg-adhoc-html')
  html: string;

  @Input('dg-adhoc-styles')
  styles: string[];

  @Input('dg-adhoc-context')
  context: SafeAny;

  @Input('dg-adhoc-module')
  module: NgModule;

  @Input('dg-adhoc-imports')
  imports: Array<Type<SafeAny> | ModuleWithProviders<SafeAny> | SafeAny[]>;

  @Input('dg-adhoc-error-handler')
  errorHandler: (...args: SafeAny[]) => SafeAny = undefined;

  visibleEmitter = new Subject<boolean>();

  get isComponentVisible(): boolean {
    return typeof this.html === 'string' && this.html.trim() !== '';
  }

  private _componentRef: ComponentRef<SafeAny> | null = null;
  private _moduleRef: NgModuleRef<SafeAny> | null = null;
  private visible = false;

  ngOnChanges(changes: SimpleChanges) {
    try {
      this.update();
    } catch (e) {
      if (_.isNil(this.errorHandler)) {
        throw e;
      } else {
        this.errorHandler(e);
      }
    }
  }

  // eslint-disable-next-line @angular-eslint/no-empty-lifecycle-method
  ngOnInit(): void {
    // nothing
  }

  ngOnDestroy(): void {
    if (this._componentRef) {
      this._componentRef.destroy();
    }

    if (this._moduleRef) {
      this._moduleRef.destroy();
    }
  }

  update() {
    this.vcr.clear();
    this._componentRef = null;

    if (this._moduleRef) {
      this._moduleRef.destroy();
      this._moduleRef = null;
    }

    if (_.isNil(this.html) || this.html.trim() === '') {
      return;
    }

    const componentType = this.createComponentType(
      this.html,
      this.styles,
      this.context,
    );
    const moduleType = this.createModuleType(componentType);
    this._moduleRef = createNgModuleRef(moduleType, this.vcr.injector);
    this._componentRef = this.vcr.createComponent(componentType);
  }

  toggle() {
    // console.log(this.vcr.injector.get(AsyncPipe));
    this.visible = !this.visible;
    this.visibleEmitter.next(this.visible);
  }

  private createModuleType(
    componentType: Type<SafeAny>,
  ): Type<SafeAny> {
    let metadata: NgModule = {};

    if (!_.isNil(this.module)) {
      metadata = _.cloneDeep(this.module);
    }

    metadata.imports = metadata.imports || [];
    metadata.imports = metadata.imports.concat(this.imports || []);

    metadata.declarations = metadata.declarations || [];
    metadata.declarations = metadata.declarations.concat([componentType]);

    const moduleType = class AdhocModule {
      // nothing
    };
    const moduleTypeDecorator: TypeDecorator = NgModule(metadata);
    // noinspection UnnecessaryLocalVariableJS
    const decoratedModuleType = moduleTypeDecorator(moduleType);
    return decoratedModuleType;
  }

  // noinspection JSMethodCanBeStatic
  private createComponentType(
    html: string,
    styles: string[],
    context: SafeAny,
  ): Type<SafeAny> {
    const metadata: Component = {};
    metadata.selector = RandomUtil.nextSelector();
    metadata.template = html;
    metadata.styles = [...styles];
    metadata.changeDetection = ChangeDetectionStrategy.OnPush;

    const componentType = class AdhocComponent {
      context: SafeAny = context;
    };
    const componentTypeCreator: TypeDecorator = Component(metadata);
    // noinspection UnnecessaryLocalVariableJS
    const decoratedComponentType = componentTypeCreator(componentType);
    return decoratedComponentType;
  }
}

type SafeAny = any;

const reverse = (str: string) => {
  return str.split('').reverse().join('');
};

const random = () => {
  return (Math.floor(Math.random() * (99999999999999999 - 10000000000000000)) + 10000000000000000).toString(16);
};

let currentIdTime: number;
let currentId = 0;

abstract class RandomUtil {
  public static nextSelector(): string {
    const now = Date.now();
    if (currentIdTime !== now) {
      currentId = 0;
      currentIdTime = now;
    }
    const comingId = ++currentId;
    const randomHex = reverse(random()).padStart(15, '0');
    const timeHex = reverse(currentIdTime.toString(16).padStart(12, '0'));
    const comingIdHex = reverse(comingId.toString(16).padStart(3, '0'));
    return `adhoc-component-${timeHex}${comingIdHex}${randomHex}`;
  }

  private constructor() {}
}

This is working for both dev and prod.

2reactions
hydra1983commented, Jan 19, 2022

@nfMalde For v13, a workaround with minimum cost (bundle size) would be:

main.ts

import 'reflect-metadata'; // !! SHOULD BE KEPT IN FIRST LINE !!
import '@angular/compiler'; // !! TO FIX `Jit compiler unavailable` !!

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from '@app/app.module';
import { environment } from '@env/environment';

if (environment.production) {
  enableProdMode();
}

document.addEventListener('DOMContentLoaded', () => {
  platformBrowserDynamic()
    .bootstrapModule(AppModule)
    .catch((err) => console.error(err));
});

angular.json

              "production": {
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "6kb",
                  "maximumError": "10kb"
                }
              ],
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "outputHashing": "all",
              // Default is true, use false to fix jit compiler unavailable
              "buildOptimizer": false
            },
Read more comments on GitHub >

github_iconTop Results From Across the Web

Rendering dynamic components by selector name in Ivy
Rendering Components with component selector name along with lazy module loading. The approach that works with Angular Ivy & AOT compilation.
Read more >
Angular component not rendering when passed as a string in ...
Angular components are used in the html code but not shown in the application. How can I show an angular component when it...
Read more >
Angular — How to render HTML containing ... - Talentica
Are you thinking of rendering HTML containing Angular Components dynamically? Learn more on a significant subset of supporting dynamic ...
Read more >
Loading Components Dynamically in Angular 9 with Ivy
This article will show you how to start loading components dynamically using Angular 9 with Ivy. This is not exactly new and exclusive...
Read more >
Architecture with Angular Ivy - Part 2: Higher order and ...
With Ivy's private APIs, we can dynamically create components. ... of the passed component so that it can be rendered dynamically later:.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found