Enhancing Angular Templates with Untagged Template Literals
Angular’s latest release, 19.2.0-next.0, introduces a powerful enhancement that developers will love: support for untagged template literals in expressions. This feature brings greater flexibility and expressiveness to Angular templates, allowing developers to write cleaner, more concise, and dynamic templates without extra workarounds. Let’s explore what this means and how you can leverage it in your applications.
Key Use Cases
Here are some practical examples of how untagged template literals can simplify your Angular templates:
1. Dynamic Content
You can directly embed dynamic expressions into your templates:
<p>Message: {{ `Hello, ${name} - ${value}` }}</p>
2. Dynamic Classes
Creating dynamic class names has never been easier:
<p class="{{ `foo-${postfix}` }}">Custom class</p>
<p [class]=`foo-${postfix}`>Custom class</p>
Both of these examples achieve the same result: dynamically assigning classes based on the value of postfix
.
3. Interpolations with Multiple Expressions
Easily handle more complex interpolations:
<p>With interpolations: {{ `Hello ${name}, it is currently ${timeOfDay}!` }}</p>
4. Pipes and Template Literals
Template literals can also be combined with Angular pipes:
<p>With pipe: {{ `hello ${name}` | uppercase }}</p>
In this case, the entire template literal is passed through the uppercase
pipe, transforming it into uppercase text.
5. Dynamic URLs
Simplify dynamic URL generation for images or other assets:
<img [src]="`${base}/600x400`" />
6. Loops with Template Literals
You can use untagged template literals even in Angular’s structural directives, like @for
:
@for(n of [1,2,3]; track $index) {
<button [attr.data-id]=`${n}-button`>{{ `Click ${n}` }}</button>
}
This allows for dynamic rendering of repeated content while embedding values directly into strings.
Follow me on Medium or Twitter to read more about Angular and JS!