How to fix Angular 'TypeError: templateRef.createEmbeddedView is not a function'
Problem:
You encounter an error message like this:
ERROR TypeError: templateRef.createEmbeddedView is not a function
at ViewContainerRef_.createEmbeddedView (core.js:11389)
at NgIf._updateView (common.js:2843)
at NgIf.set [as ngIfElse] (common.js:2815)
at updateProp (core.js:12602)
at checkAndUpdateDirectiveInline (core.js:12313)
at checkAndUpdateNodeInline (core.js:13876)
at checkAndUpdateNode (core.js:13819)
at debugCheckAndUpdateNode (core.js:14712)
at debugCheckDirectivesFn (core.js:14653)
at Object.eval [as updateDirectives] (MyComponent.html:1)
in a component where you have a source code similar to this
<div *ngIf="myCondition ; else elseSection">
<!-- ... -->
</div>
<div #elseSection>
<!-- ... -->
</div>
Solution
Whatever element you reference in the *ngIf else clause can’t be any arbitrary component, but it must be a ng-template.
In order to solve this, change <div #elseSection>
to <ng-template #elseSection>
. Note that using just <template>
is deprecated since Angular4.
The resulting source code should look like this:
<div *ngIf="myCondition ; else elseSection">
<!-- ... -->
</div>
<ng-template #elseSection>
<!-- ... -->
</ng-template>