⚠️ This lesson is retired and might contain outdated information.

Generate and Render Angular 2 Template Elements in a Component

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 9 months ago

Angular 2 Components have templates, but you can also create templates inside of your templates using Angular 2 ViewContainer’s createEmbeddedView for more visual control of how you want to generate elements inside of your Angular 2 templates.

[00:00] There's actually a bit of a simpler way to manage all of this, if you just want to use what's called a template inside of your template. I know, it's kind of weird working, but this template means, it's something that's not going to be rendered by the DOM.

[00:13] It's just some HTML that you are going to write declaratively, and then you can reference that, and start stamping out these templates inside of your larger template, programmatically.

[00:24] We'll create a ref to this, so we can grab it. I'll save -child, get that template for me please, and I'll get a reference to that template, so that's this template here. Let's put some stuff inside of here, page two, MyAmazingTemplate, followed by MyAmazingButton. Then with that template, all I have to do is...I'll get rid of this to quit moving it around, and I'll say this.container, create embedded view, this.template.

[01:00] Let's change the text of the button to, "Create Template" hit Save. Now when this refreshes, I can start hitting this button and stamping out these templates beneath it. Every time it renders out a new template, based on this template we declared inside of our component template.

Grzegorz
Grzegorz
~ 7 years ago

Hi John, this example does not work. I got ERROR TypeError: templateRef.createEmbeddedView is not a function. Does anyone have similar issues?

Kian
Kian
~ 7 years ago

Use ng-template instead of template eg.

<ng-template #template>
  <h2>My amazing template</h2>
  <button>My amazing button</button>
</ng-template>

https://stackoverflow.com/questions/47157228/angular-5-templateref-createembeddedview-is-not-a-function

Markdown supported.
Become a member to join the discussionEnroll Today