Ajinkya Dhote Ajinkya Dhote - 3 years ago 258
Javascript Question

Angular4 Template

I have written a simple code to demonstrate ngTemplate

<div> <ng-container [ngTemplateOutlet] ="template1"> </ng-container></div>

and here are the template

<ng-template #template1> This is 1st template </ng-template>
<ng-template #template2>This is 2nd template </ng-template>

It is working as expected, but my problem is I am not able to pass dynamic value to

I want to achieve something like this

<div> <ng-container [ngTemplateOutlet] ="selectTemplate"></ng-container> </div>

Which will either select

Whenever I am passing some dynamic value which I have defined in my typescript file it gives is error

ERROR TypeError: templateRef.createEmbeddedView is not a function

My typescript file contains this code

if(some condition) {
this.selectTemplate = "template1";
} else {
this.selectTemplate = "template2";

Answer Source

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 ngViewAfterInithook to wait for that to happen.

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