I have written a simple code to demonstrate ngTemplate
<div> <ng-container [ngTemplateOutlet] ="template1"> </ng-container></div>
<ng-template #template1> This is 1st template </ng-template>
<ng-template #template2>This is 2nd template </ng-template>
[ngTemplateOutlet]
<div> <ng-container [ngTemplateOutlet] ="selectTemplate"></ng-container> </div>
template1
template2
ERROR TypeError: templateRef.createEmbeddedView is not a function
if(some condition) {
this.selectTemplate = "template1";
} else {
this.selectTemplate = "template2";
}
In your first example, you're binding ngTemplateOutlet
to the value of the expression template1
, which is the first ngTemplate
element. So far so good.
In your second example, you're binding ngTemplateOutlet
to the value of the expression selectTemplate
, which is not a template element - you've set it to be a string!
To fix this, you first need to add the template references to your component as fields using the ViewChild
annotation:
@ViewChild('template1') template1;
@ViewChild('template2') template2;
Then set selectTemplate
to refer to the element itself rather than its name:
if (some condition) {
this.selectTemplate = this.template1;
}
else {
this.selectTemplate = this.template2;
}
Note that the ViewChild
variables will not be set until the component's view has been initialized - you can use the ngViewAfterInit
hook to wait for that to happen.