Reputation: 1478
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 [ngTemplateOutlet]
I want to achieve something like this
<div> <ng-container [ngTemplateOutlet] ="selectTemplate"></ng-container> </div>
Which will either select template1
or template2
.
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";
}
Upvotes: 1
Views: 316
Reputation: 657308
update Angular 5
ngOutletContext
was renamed to ngTemplateOutletContext
See also https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29
original
You can pass a context
<ng-container [ngTemplateOutlet]="template1; context: {foo: 'foo', bar: 'bar', $implicit: 'implit' }"
In the template you can use it like
<ng-template #template1 let-foo1="foo" let-foo2="bar" let-item>
This is 1st template
<div>foo1: {{foo1}}</div>
<div>foo2: {{foo2}}</div>
<div>foo1: {{item}}</div>
</ng-template>
I hope the names I used are not too confusing. I tried to make the distinction between
="somename"
in the template variable definintion (let-item
)Upvotes: 1
Reputation: 35797
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.
Upvotes: 2