Dynamic templates in RC.0

Hi! I am in desperate need of some pro Angular help here. What I am trying to do is replicate the examples of using dynamic templates in components, ultimately compiling the components (and a custom module, since the latest release) at runtime. However, although it works during testing in the browser, it fails when running on the emulator. I have traced to to most likely be due to the AoT compilation, as I am getting an exception saying that the “Runtime compiler is not loaded”.

My code for creating this custom component looks like this:
import { Directive, Input, ViewContainerRef, Compiler, Component, NgModule, ComponentFactory } from ‘@angular/core’;
import {IONIC_DIRECTIVES, IonicModule} from ‘ionic-angular’;
import { CommonModule } from ‘@angular/common’;

@Directive({
    selector: 'component-constructor' // Attribute selector
})
export class ComponentConstructor {

  @Input() type: string;

  constructor(public vcRef: ViewContainerRef, public compiler: Compiler, public typeBuilder: DynamicTypeBuilder) {
    console.log("Creating dynamic element");
  }

  ngOnChanges(changes?: any)
  {
    console.log("Starting create process...");
    const type = this.type;
    if(!type) return;

    @Component({
      selector: 'dynamic-comp',
      template: type
    })
    class DynamicHtmlComponent {
      name: string = "empty";
    };

    @NgModule({
      imports: [CommonModule, IonicModule],
      declarations: [DynamicHtmlComponent]
    })
    class DynamicHtmlModule {};
    console.log("Compiling module...");


    this.compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule)
        .then(factory => {
          console.log("Compiled! Time to create component...");
          const compFactory = factory.componentFactories.find(x => x.componentType === DynamicHtmlComponent);
          const cmpRef = this.vcRef.createComponent(compFactory, 0);
          console.log("Created!");

        });
  }

}

Any insight on this will be much appreciated!

1 Like

Right, so. The AoT compilation breaks any possibility of having dynamic templates in Ionic 2. My question is, is there any way to opt out of AoT, dealing with the obvious drawbacks?

The AoT compilation breaks any possibility of having dynamic templates in Ionic 2

You base your statement on this for example?

No. I base it on the fact that the Runtime Compiler is not available when using AoT. The Runtime Compiler is what allows you to compile the temple, thus without it removing any possibility of using dynamic templates.