Declaring Variables in Angular Templates: A Comprehensive Guide

Nov 07, 2025 · Programming · 11 views · 7.8

Keywords: Angular | Template Variables | Declaration Methods | *ngIf | *ngVar | @let | ng-template

Abstract: This article provides an in-depth analysis of various techniques to declare local variables in Angular templates. It covers methods such as using *ngIf with the 'as' keyword, creating custom directives like *ngVar, utilizing ng-template with ngTemplateOutlet, employing *ngFor as a workaround, and introducing the new @let syntax. Each method is explained with detailed code examples and practical use cases to help developers select the most appropriate approach for their projects.

Introduction

In Angular development, there are frequent needs to declare local variables within templates to simplify expressions or avoid redundant computations. This article systematically explores multiple approaches, drawing from Q&A data and recent references, covering everything from basic directives to advanced syntax for flexible application in various scenarios.

Using *ngIf with the 'as' Syntax

A common method involves using the *ngIf structural directive combined with the 'as' keyword to assign the result of an expression to a variable. This approach is straightforward but relies on the truthiness of the variable; if the expression evaluates to a falsy value (e.g., false, 0, or null), the content will not render.

<div *ngIf="{ a: 1, b: 2, c: 3 + x } as variable">
  <span>{{variable.a}}</span>
  <span>{{variable.b}}</span>
  <span>{{variable.c}}</span>
</div>

In this example, an object is assigned to the variable 'variable', and its properties are accessed in child elements. Developers can define the value of x in the component, for instance, setting x = 5 in the TypeScript file to dynamically compute the c property.

Custom Directive: *ngVar

To overcome the limitations of *ngIf, a custom directive such as *ngVar can be created, which does not depend on truthiness checks and offers more flexibility in variable declaration. Below is a rewritten implementation of VarDirective based on core concepts.

@Directive({
  selector: '[ngVar]'
})
export class VarDirective {
  @Input()
  set ngVar(context: unknown) {
    this.context.$implicit = this.context.ngVar = context;
    if (!this.hasView) {
      this.vcRef.createEmbeddedView(this.templateRef, this.context);
      this.hasView = true;
    }
  }

  private context: { $implicit: unknown; ngVar: unknown; } = {
    $implicit: null,
    ngVar: null
  };

  private hasView: boolean = false;

  constructor(
    private templateRef: TemplateRef<any>,
    private vcRef: ViewContainerRef
  ) {}
}

Usage examples:

<div *ngVar="false as variable">
  <span>{{variable | json}}</span>
</div>
<div *ngVar="45 as variable">
  <span>{{variable | json}}</span>
</div>

This method allows direct variable declaration in templates without concerns about truthiness, suitable for various data types.

Using ng-template with ngTemplateOutlet

Another approach utilizes the <ng-template> element with ngTemplateOutlet to define a context and bind variables. This method is more versatile but can be verbose, ideal for complex use cases.

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

Here, the $implicit property is used for implicit variable assignment, and developers can extend the context to support multiple variables.

Alternative: Using *ngFor

As a temporary workaround, the *ngFor directive can be used to iterate over a single-element array to assign a variable. However, this method is not recommended for production due to potential performance overhead from unnecessary iterations.

<div *ngFor="let a of [aVariable]">
  <span>{{a}}</span>
</div>

When combined with async pipes, it can handle Observable data, but performance implications should be considered.

New Feature: @let Syntax

Angular has recently introduced the @let block, enabling direct variable declaration in templates without truthiness dependencies, and seamlessly integrating with features like signals and async pipes. This is the recommended approach in modern Angular development.

@let points = (points$ | async) ?? 0;
<h1>You have: {{ points }} points!</h1>

Additional use cases include aliasing complex expressions and using with control flow directives:

@let user = (user$ | async) ?? { name: 'Guest' };
<h1>{{ user.name }}</h1>

The @let syntax simplifies code and improves readability, especially when dealing with data that may be falsy.

Comparison and Best Practices

Each method has its strengths and weaknesses: *ngIf with 'as' is simple but truthiness-dependent; *ngVar is flexible but requires custom code; ng-template is powerful but verbose; *ngFor is a quick fix but not ideal; @let is the modern solution, particularly suitable for new projects. Developers should choose based on Angular version, performance needs, and code maintainability. It is advisable to prefer the @let syntax where possible to leverage the latest framework features.

Conclusion

Declaring variables in Angular templates can be achieved through various methods, from traditional directives to new syntax, each fitting different scenarios. By understanding these techniques, developers can optimize template code, enhancing application performance and maintainability. As Angular evolves, new features like @let will further streamline the development process.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.