Categories
Angular Answers

How to declare a variable in a template in Angular?

Spread the love

Sometimes, we want to declare a variable in a template in Angular.

In this article, we’ll look at how to declare a variable in a template in Angular.

How to declare a variable in a template in Angular?

To declare a variable in a template in Angular, we can use ng-template.

For instance, we write

<ng-template
  #selfie
  [ngTemplateOutlet]="selfie"
  let-a="aVariable"
  [ngTemplateOutletContext]="{ aVariable: 123 }"
>
  <div>
    <span>{{ a }}</span>
  </div>
</ng-template>

to define the template variable a with

let-a="aVariable"

We set the variable’s value to aVariable.

And we set aVariable‘s value with

[ngTemplateOutletContext]="{ aVariable: 123 }"

Then in the span inside ng-template, we render a.

Conclusion

To declare a variable in a template in Angular, we can use ng-template.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *