angular 5: templateRef.createEmbeddedView is not a function

后端 未结 5 1149
忘掉有多难
忘掉有多难 2020-12-29 03:58

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

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

@Component         


        
相关标签:
5条回答
  • 2020-12-29 04:03

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

    0 讨论(0)
  • 2020-12-29 04:03

    When you reference in the *ngIf, else clause can’t be any arbitrary component, but it must be a ng-template.

    For eg,

    in a component where you have a source code similar to this:

    <div *ngIf="myCondition ; else elseSection">
        <!-- ... -->
    </div>
    <div #elseSection>
        <!-- ... -->
    </div>
    

    The resulting source code should look like this:

    <div *ngIf="myCondition ; else elseSection">
        <!-- ... -->
    </div>
    <ng-template #elseSection>
        <!-- ... -->
    </ng-template>
    

    ref : https://techoverflow.net/2018/02/17/how-to-fix-angular-typeerror-templateref-createembeddedview-is-not-a-function/

    0 讨论(0)
  • 2020-12-29 04:15

    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.

    0 讨论(0)
  • 2020-12-29 04:19

    Seems obvious, but I missed this.

    In newer version(Angular 8+) this error is thrown if you're not passing the template when template was expected by Angular.

    <ng-container *ngIf="getTemplate(col) as template; else defaultColumn">
      <ng-container *ngTemplateOutlet="template; context: {'cell': rowData[col.field]}"></ng-container>
    </ng-container>
    <ng-template #defaultColumn>
      {{rowData[col.field]}}
    </ng-template>
    

    In above case your getTemplate method should return actual template or null, nothing else. I was returning Directive Class here. Hence the error.

    0 讨论(0)
  • 2020-12-29 04:20

    For me, the problem was using the same name for a variable in the component, and for a template in the HTML file.

    0 讨论(0)
提交回复
热议问题