Declare a Template within a Template using `ng-template` in Angular

Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 5 years ago

In this lesson we learn about ng-template, an Angular component that allows us to declare some piece of Angular template. We will explore how to use @ViewChild to grab the template from within our Angular component and how we can then pass it along accordingly.

Instructor: [00:01] If you want to have some kind of dynamic template, which we can then grab from our code and pass around to other components, we first of all need to find a way to define it within our components template. That's exactly where the ng-template tag comes into play.

[00:16] This is a special tag which we can define within our template of another component. We can also write here something inside. When we then save this, you can immediately see that template actually doesn't get displayed our UI, because this is something we can define inside here, and then grab later and use it somewhere else, for instance.

[00:36] Of course, in order to be able to grab this template, we need to have a way to access it from our code. The first step here is to define a so-called template variable. Let's call this PersonAdded, for instance. Then, we can go back into our component code, and we can use an annotation which is called viewChild. Inside there, we reference the PersonAdded, which we just found.

[01:00] If you change something, we need to import from @angular/core, as well, with viewChild. Next, for being able to access that viewChild, we need to also use a specific lifecycle hook of our component, which is the AfterViewInIt. We need to import that as well, AfterViewInIt here. Then, implement our interface accordingly.

[01:23] As a result, for down here, we can now implement ngAfterViewInIt lifecycle hook, and inside here, we can simply try and log out the reference to our PersonAdded template. Once the application refreshes, you can see we get a so-called TemplateRef inside here, which has a couple of properties, which we can now go and explore further.