How to use variable to define templateUrl in Angular2

I think you should use dynamic component loading to do that.

Let’s say we have a json file:

{
    "title": "My first article",
    "html": "app/articles/first.html"
}

We might create HtmlOutlet directive that will create component dynamicallу with desired templateUrl:

@Directive({
  selector: 'html-outlet' 
})
export class HtmlOutlet {
  @Input() html: string;

  constructor(private vcRef: ViewContainerRef, private compiler: Compiler) {}

  ngOnChanges() {
    const html = this.html;
    if (!html) return;

    @Component({
      selector: 'dynamic-comp',
      templateUrl: html
    })
    class DynamicHtmlComponent  { };

    @NgModule({
      imports: [CommonModule],
      declarations: [DynamicHtmlComponent]
    })
    class DynamicHtmlModule {}

    this.compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule)
      .then(factory => {
        const compFactory = factory.componentFactories
               .find(x => x.componentType === DynamicHtmlComponent);
        const cmpRef = this.vcRef.createComponent(compFactory, 0);
        cmpRef.instance.prop = 'test';
        cmpRef.instance.outputChange.subscribe(()=>...);;
    });
  }
}

And then use it like:

<html-outlet [html]="article?.html">

Where html is path to article html

See more details in this Plunkr

Leave a Comment