How To Use The Ng-Template In Angular?

In Angular, the ng-template directive is used to declare a template that can be used to stamp out elements in the component’s template. It is similar to a JavaScript function, but it is not executed until the template is stamped out.

Here is an example of how you can use the ng-template directive in an Angular component:

<ng-template #template>
  <p>This is the template content</p>
</ng-template>

<button (click)="showTemplate()">Show Template</button>

<div *ngIf="show">
  <ng-container *ngTemplateOutlet="template"></ng-container>
</div>

In this example, the ng-template directive is used to define a template with a p element that displays the text “This is the template content”. The button element has a click event binding that calls the showTemplate() method when clicked.

The div element has an *ngIf directive that displays the div element only if the show property is true. Inside the div element, there is an ng-container element with an *ngTemplateOutlet directive that stamps out the template defined by the ng-template directive.

To use the ng-template directive in your component, you need to do the following:

  1. Declare a template variable using the # symbol, like this: #template.
  2. Define the template content inside the ng-template element.
  3. Use the *ngTemplateOutlet directive to stamp out the template in the component’s template.
  4. Pass the template variable to the *ngTemplateOutlet directive as an input.

By following these steps, you can use the ng-template directive in your Angular component to stamp out elements in the component’s template.

You can also pass input data to the ng-template directive using the ngTemplateOutletContext input. Here is an example of how you can do this:

<ng-template #template let-name="name">
  <p>Hello, {{name}}!</p>
</ng-template>

<ng-container *ngTemplateOutlet="template; context: {name: 'John'}"></ng-container>

In this example, the ng-template directive has a template variable name that is passed to the template using the let keyword. The ng-container element has an *ngTemplateOutlet directive that stamps out the template and passes the input data using the context input.

By using the ngTemplateOutletContext input, you can pass data to the ng-template directive and use it to display dynamic content in the component’s template.

Facebook
Twitter
LinkedIn
Pinterest

Table of Contents

Related posts