Aliasger Jaffer
Aliasger Jaffer's Blog

Aliasger Jaffer's Blog

Quick Notes: Using ng-template with ng-container

Quick Notes: Using ng-template with ng-container

Learn how to pass data to ng-template

Aliasger Jaffer's photo
Aliasger Jaffer
·Oct 4, 2021·

2 min read

ng-template element does not display it's content to the browser. Instead, you can use ng-container and pass it the template to use. ng-container in turn, renders the template.

Here is an example of ng-container displaying the greeting ng-template:

<ng-template #greeting>
  Hello World

<ng-container [ngTemplateOutlet]="greeting"></ng-container>

The input [ngTemplateOutlet] refers to the variable pointing to the template to be used.

One of the benefits of ng-template is that it allows us to define variables that it can display. There are two types of variables that can be passed - $implicit and an explicit one. Below is an example that passes both:

<ng-template #greeting let-name let-country="birthPlace">
  {{name}} lives in {{county}}

<ng-container [ngTemplateOutlet]="greeting" [ngTemplateOutletContext]="data"></ng-container>

Notice that ng-template has two let-* properties:

  • let-name : We don't assign any value to this attribute, and as such, it is considered an implicit variable. Implicit variables pick their values from the context object when the object has a key $implicit. You can have many implicit variables (such as let-a let-b, etc), and they will all pick up the same $implicit variable value.
  • let-country="birthPlace" : This property sets the variable country to point to the birthPlace key within the context.

ng-container has another property passed to it - the context object, through the input property named ngTemplateOutletContext.

Here is the typescript file with the context object named data:

  data = {
    $implicit: 'Mark',
    birthPlace: 'Canada'

Remember, if you don't assign a value to the let-* property, it will pick up value from $implicit within your context. Context must be an object, otherwise nothing will be displayed (empty value on the template).