Angular String/Text Interpolation

Angular String/Text Interpolation

Text interpoalation lets you use dynamic string values into your HTML templates.

Interpolation embedds expressions in HTM.

By default, interpolation uses the double curly braces **{{** and **}}** as delimiters.

Lets look at an example

We have an Angular component that contains a currentUser variable:

The text between the braces is often the name of a component property(can be used for other purposes too).

Angular replaces that name with the string value of the corresponding component property.

Output

What other stuff can we do with String/Text interpolation?

1. Resolves the Template Expression

A template expression produces a value and appears within double curly braces, {{ }}.

Angular resolves the expression and assigns it to a property of a binding target. The target could be an HTML element, a component, or a directive.

Output

Illegal Javascript expressions that you cannot use in String Interpolation

You can’t use JavaScript expressions that have or promote side effects, including:

  • Assignments (=, +=, -=, ...)
  • Operators such as new, typeof, or instanceof
  • Chaining expressions with ; or ,
  • The increment and decrement operators ++ and --
  • Some of the ES2015+ operators

2. You can use String Functions within interpolation brackets

Interpolated expressions support string built-in functions

3. Functions Output can be shown using String Interpolation

You can even show call a function inside the curly brackets and show the output of a function.

I created a fucntion called userComment and it returns a random comment.

Check how I used it inside HTML file.

Best Practices for Template Expressions

When using template expressions, follow these best practices:

  • Use short expressions: Use property names or method calls whenever possible. Keep application and business logic in the component, where it is accessible to develop and test
  • Quick execution: Expressions should finish quickly to keep the user experience as efficient as possible
  • No visible side effects: Template expression should not change any application state other than the value of the target property.

Thank you for reading this post, I hope you enjoyed and learn something new today. Feel free to contact me through my blog if you have questions, I will be more than happy to help.

LinkedIn: linkedin.com/in/zainuleb

Github: github.com/zainuleb (Github)

Email:

Stay safe and Happy learning!