Abhishek Kasireddy Abhishek Kasireddy - 1 year ago 253
TypeScript Question

How to use variable to define templateUrl in Angular2

I want the component to set the

with a variable, but it doesn't work.

selector: 'article',
templateUrl: '{{article.html}}',
styleUrls: ['styles/stylesheets/article.component.css']

export class ArticleComponent implements OnInit {
constructor(private route: ActivatedRoute, private articleService: ArticleService) { }
articleArray = this.articleService.getArticles();
article: Article;

ngOnInit(): void {
this.route.params.forEach((params: Params) => {
let headline = params['headline'];
this.article = this.articleService.getArticle(headline)


Every where I look, I can only see solutions for Angular 1.X, It's really frustrating. I looked into the browser console and figured out that {{article.html}} isn't even resolving. It's reading as it is. It works totally fine when I set the path myself, so I know that the problem isn't anywhere but here.

Answer Source

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:

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

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

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

      selector: 'dynamic-comp',
      templateUrl: html
    class DynamicHtmlComponent  { };

      imports: [CommonModule],
      declarations: [DynamicHtmlComponent]
    class DynamicHtmlModule {}

      .then(factory => {
        const compFactory = factory.componentFactories
               .find(x => x.componentType === DynamicHtmlComponent);
        const cmpRef = this.vcRef.createComponent(compFactory, 0);

And then use it like:

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

Where html is path to article html

See more details in this Plunkr

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download