Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 5: templateRef.createEmbeddedView is not a function

Here's the code I'm trying to get to work (angular 5):

  import { Component, ViewChild, TemplateRef, ViewContainerRef } from '@angular/core';

@Component({
  selector: 'vcr',
  template: `
    <template #tpl>
      <h1>ViewContainerRef</h1>
    </template>
    <div>Some element</div>
    <div #container></div>
  `,
})
export class VcrCmp {
  @ViewChild('container', { read: ViewContainerRef }) _vcr;
  @ViewChild('tpl') tpl: TemplateRef<any>;

  constructor(
    private viewContainerRef: ViewContainerRef
  ) {

  }

  ngAfterViewInit() {
    console.info(this.viewContainerRef);
    console.info(this._vcr);

    this._vcr.createEmbeddedView(this.tpl);
    this.viewContainerRef.createEmbeddedView(this.tpl);
  }
}

The problem is that I've got this (templateRef.createEmbeddedView is not a function) error and don't really understand why.

This code is based on this example https://netbasal.com/angular-2-understanding-viewcontainerref-acc183f3b682 so I guess it should work.

What am I doing wrong?

like image 684
k102 Avatar asked Nov 07 '17 11:11

k102


People also ask

What is Templateref in Angular?

TemplateReflinkRepresents an embedded template that can be used to instantiate embedded views. To instantiate embedded views based on a template, use the ViewContainerRef method createEmbeddedView() .

What is Ng container and ng template?

ng-container serves as a container for elements which can also accept structural directives but is not rendered to the DOM, while ng-template allows you to create template content that is not rendered until you specifically (conditionally or directly) add it to the DOM.

Can't bind to ngTemplateOutlet since it isn't a known property of ng template?

The issue occurs because our template does not reference BrowserModule in the app-routing. module. ts file as we do not use its functionality on these pages. So, you need to import this module to resolve the issue.


2 Answers

According to angular 5 changelog:

The compiler option enableLegacyTemplate is now disabled by default as the element was deprecated since v4. Use <ng-template> instead.

So you should use ng-template instead of template:

<ng-template #tpl>
   <h1>ViewContainerRef</h1>
</ng-template>

Stackblitz Example

or set enableLegacyTemplate to true:

platformBrowserDynamic().bootstrapModule(AppModule, { enableLegacyTemplate: true })

Stackblitz Example

But you should know that

The option enableLegacyTemplate and the <template> element will both be removed in Angular v6.

like image 139
yurzui Avatar answered Oct 23 '22 06:10

yurzui


In my case the error was due to me forgetting * (asterisk) before ngTemplateOutlet

like image 32
Maxim Krabov Avatar answered Oct 23 '22 06:10

Maxim Krabov