Monday, June 7, 2021

ng-template,Templateref,ViewContainerRef

 

What is ng-Template?

The <ng-template> is an Angular element, which contains the template. A template is an HTML snippet. The template does not render itself on DOM.

To understand let us create a new Angular Application and copy the following code to app.component.html

The above code generates the following output. The Angular does not render Say Hello. You won’t even find it as a hidden element in the DOM.

i.e because ng-template only defines a template. It is our job to tell angular where & when to display it.

There are few ways you can display the template.

  1. Using the ngTemplateOutlet directive.
  2. Using the TemplateRef & ViewContainerRef

Displaying the Template

ngTemplateOutlet

The ngTemplateOutlet, is a structural directive, which renders the template.

To use this directive, first, we need to create the template and assign it to a template reference variable (sayHelloTemplate in the following template).

We use the ngTemplateOutlet in the DOM, where we want to render the template.

The following code assigns the Template variable sayHelloTemplate to the ngTemplateOutlet directive using the Property Binding.

The content inside the ngTemplateOutlet directive is not displayed. It replaces it with content it gets from the sayHelloTemplate.

The ngTemplateOutlet is a very powerful directive. You can use it render templates, pass data to the template, pass the template to child components, etc. You can learn all these from our ngTemplateOutlet tutorial

TemplateRef & ViewContainerRef

What is TemplateRef?

TemplateRef is a class and the way to reference the ng-template in the component or directive class. Using the TemplateRef we can manipulate the template from component code.

Remember ng-template is a bunch of HTML tags enclosed in a HTML element <ng-template>

To access the above ng-template in the component or directive, first, we need to assign a template reference variable#sayHelloTemplate is that variable in the code below.

Now, we can use the ViewChild query to inject the sayHelloTemplate into our component as an instance of the class TemplateRef.

Now, we need to tell Angular where to render it. The way to do is to use the ViewContainerRef.

The ViewContainerRef is also similar to TemplateRef. Both hold the reference to part of the view.

  • The TemplateRef holds the reference template defined by ng-template.
  • ViewContainerRef, when injected to via DI holds the reference to the host element, that hosts the component (or directive).

Once, we have ViewContainerRef, we can use the createEmbeddedView method to add the template to the component.

The template is appended at the bottom.

Angular makes use of ngTemplate extensively in its structural directives. But it hides its complexities from us.

Source : https://www.tektutorialshub.com/angular/ng-template-in-angular/#what-is-templateref


No comments:

Followers

Link