ANGULAR
Complete Angular Tutorial For Beginners Introduction to Angular | What is Angular? Architecture Overview & Concepts of Angular How to Install Angular How to Create a new project in Angular Bootstrapping in Angular: How It Works Internally Angular Components Overview & Examples Data Binding in Angular Interpolation in Angular Property Binding in Angular Event Binding in Angular ngModel & Two way Data binding in Angular NgModelChange & Change Event in Angular Child/Nested Components in Angular angular directives angular ngFor directive ngSwitch, ngSwitchcase, ngSwitchDefa ult Angular Example How to use ngIf, else, then in Angular By example NgClass Example Conditionally apply class Angular ngStyle Directive Angular Trackby to improve ngFor Performance How to Create & Use Custom Directive In Angular Working with Angular Pipes How to Create Custom Pipe in Angular Formatting Dates with Angular Date Pipe Using Angular Async Pipe with ngIf & ngFor angular keyValue pipe Using Angular Pipes in Components or Services Angular Component Communication & Sharing Data Angular Pass data to child component Angular Pass data from Child to parent component Component Life Cycle Hooks in Angular Angular ngOnInit And ngOnDestroy Life Cycle hook Angular ngOnChanges life Cycle Hook Angular ngDoCheck Life Cycle Hook Angular Forms Tutorial: Fundamentals & Concep t s Angular Template-driven forms example How to set value in template-driven forms in Angular Angular Reactive Forms Example Using Angular FormBuilder to build Forms SetValue & PatchValue in Angular StatusChanges in Angular Forms ValueChanges in Angular Forms FormControl in Angular FormGroup in Angular Angular FormArray Example Nested FormArray Example Add Form Fields Dynamically SetValue & PatchValue in FormArray Angular Select Options Example in Angular Introduction to Angular Services Introduction to Angular Dependency Injection Angular Injector, @Injectable & @Inject Angular Providers: useClass, useValue, useFactory & useExisting Injection Token in Angular How Dependency Injection & Resolution Works in Angular Angular Singleton Service ProvidedIn root, any & platform in Angular @Self, @SkipSelf & @Optional Decorators Angular '@Host Decorator in Angular ViewProviders in Angular Angular Reactive Forms Validation Custom Validator in Angular Reactive Form Custom Validator with Parameters in Angular Inject Service Into Validator in Angular template_driven_form_validation_in_angular Custom Validator in Template Driven Forms in Angular Angular Async Validator Example Cross Field or Multi Field Validation Angular How to add Validators Dynamically using SetValidators in Angular Angular HttpClient Tutorial & Example Angular HTTP GET Example using httpclient Angular HTTP POST Example URL Parameters, Query Parameters, httpparams in Angular HttpClient Angular HTTPHeaders Example Understanding HTTP Interceptors in Angular Angular Routing Tutorial with Example Location Strategy in Angular Angular Route Params Angular : Child Routes / Nested Route Query Parameters in Angular Angular Pass Data to Route: Dynamic/Static RouterLink, Navigate & NavigateByUrl to Navigate Routes RouterLinkActive in Angular Angular Router Events ActivatedRoute in Angular Angular Guards Tutorial Angular CanActivate Guard Example Angular CanActivateChild Example Angular CanDeactivate Guard Angular Resolve Guard Introduction to Angular Modules or ngModule Angular Routing between modules Angular Folder Structure Best Practices Guide to Lazy loading in Angular Angular Preloading Strategy Angular CanLoad Guard Example Ng-Content & Content Projection in Angular Angular @input, @output & EventEmitter Template Reference Variable in Angular ng-container in Angular How to use ng-template & TemplateRef in Angular How to Use ngTemplateOutlet in Angular '@Hostbinding and @Hostlistener_in_Angular Understanding ViewChild, ViewChildren &erylist in Angular ElementRef in Angular Renderer2 Example: Manipulating DOM in Angular ContentChild and ContentChildren in Angular AfterViewInit, AfterViewChecked, AfterContentInit & AfterContentChecked in Angular Angular Decorators Observable in Angular using RxJs Create observable from a string, array & object in angular Create Observable from Event using FromEvent in Angular Using Angular observable pipe with example Angular Map Operator: Usage and Examples Filter Operator in Angular Observable Tap operator in Angular observable Using SwitchMap in Angular Using MergeMap in Angular Using concatMap in Angular Using ExhaustMap in Angular Take, TakeUntil, TakeWhile & TakeLast in Angular Observable First, Last & Single Operator in Angular Observable Skip, SkipUntil, SkipWhile & SkipLast Operators in Angular The Scan & Reduce operators in Angular DebounceTime & Debounce in Angular Delay & DelayWhen in Angular Using ThrowError in Angular Observable Using Catcherror Operator in Angular Observable ReTryWhen inReTry, ReTryWhen in Angular Observable Unsubscribing from an Observable in Angular Subjects in Angular ReplaySubject, BehaviorSubject & AsyncSubject in Angular Angular Observable Subject Example Sharing Data Between Components Angular Global CSS styles View Encapsulation in Angular Style binding in Angular Class Binding in Angular Angular Component Styles How to Install & Use Angular FontAwesome How to Add Bootstrap to Angular Angular Location Service: go/back/forward Angular How to use APP_INITIALIZER Angular Runtime Configuration Angular Environment Variables Error Handling in Angular Applications Angular HTTP Error Handling Angular CLI tutorial ng new in Angular CLI How to update Angular to latest version Migrate to Standalone Components in Angular Create Multiple Angular Apps in One Project Set Page Title Using Title Service Angular Example Dynamic Page Title based on Route in Angular Meta service in Angular. Add/Update Meta Tags Example Dynamic Meta Tags in Angular Angular Canonical URL Lazy Load Images in Angular Server Side Rendering Using Angular Universal The requested URL was not found on this server error in Angular Angular Examples & Sample Projects Best Resources to Learn Angular Best Angular Books in 2020

Interpolation in Angular

In this guide let us learn the interpolation in Angular with examples. We use interpolation to bind a component property, method or to a template reference variable to a string literal in the view. We also call this as string interpolation. It is one way from component to view as the data flow from the component to view.

What is Interpolation in Angular

Interpolation allows us to include expressions as part of any string literal, which we use in our HTML. The angular evaluates the expressions into a string and replaces it in the original string and updates the view. You can use interpolation wherever you use a string literal in the view.

Angular interpolation is also known by the name string interpolation. Because you incorporate expressions inside another string.

Interpolation syntax

The Angular uses the {{ }} (double curly braces) in the template to denote the interpolation. The syntax is as shown below

                              

{{ templateExpression }}
                            
                        

The content inside the double braces is called Template Expression

The Angular first evaluates the Template Expression and converts it into a string. Then it replaces Template expression with the result in the original string in the HTML.Whenever the template expression changes, the Angular updates the original string again

image

Interpolation Example

Create a new angular application using the following command

                              
 
ng new interpolation 
                            
                        

Open the app.component.html and just add the following code

                              

{{title}}
                            
                        

Open the app.component.ts and add the following code

                              

import { Component } from '@angular/core';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Angular Interpolation Example';
}
 
                            
                        

Run the app. You will see the “Angular Interpolation Example” on the screen

In the example above the title is the Template Expression. We also have title property in the component. The Angular evaluates {{title}} and replaces it with the value of the title property from the component class.

If the user changes the title in the component class, the Angular updates the view accordingly.

The interpolation is much more powerful than just getting the property of the component. You can use it to invoke any method on the component class or to do some mathematical operations etc.

Notes on Interpolation

Interpolation is one-way binding

Interpolation is one way as values go from the component to the template. When the component values change, the Angular updates the view. But if the values changes in the view components are not updated.

Should not change the state of the app

The Template expression should not change the state of the application. The Angular uses it to read the values from the component and populate the view. If the Template expression changes the component values, then the rendered view would be inconsistent with the model

It means that you cannot make use of the following

  1. Assignments (=, +=, -=, …)
  2. Keywords like new,typeof,instanceof, etc
  3. Chaining expressions with ; or ,
  4. The increment and decrement operators ++ and --
  5. bitwise operators such as | and &

The expression must result in a string

Interpolation expression must result in a string. If we return an object it will not work. If you want to bind the expression that is other than a string (for example – boolean), then Property Binding is the best option.

Works only on Properties & not attributes

Interpolation and property binding can set only properties, not attributes. For Attributes use attribute binding

Examples of interpolation

You can use interpolation to invoke a method in the component, Concatenate two string, perform some mathematical operations or change the property of the DOM element like color, etc.

Invoke a method in the component

We can invoke the component’s methods using interpolation.

                              

//Template
 
{{getTitle()}}
 
 
//Component
title = 'Angular Interpolation Example';
getTitle(): string {
     return this.title;
 }
 
                            
                        

Concatenate two string

                              
 
<p>Welcome to {{title}}</p>
<p>{{ 'Hello & Welcome to '+ ' Angular Interpolation '}}</p>
<p>Welcome {{firstName}}, {{lastName}}</p>
<p>Welcome {{getFirstName()}}, {{getLastName()}}</p>
 
                            
                        

Perform some mathematical operations

                              
<h2>Mathematical Operations</h2>
 
<p>100x80 = {{100*80}}</p>
<p>Largest: {{max(100, 200)}}</p>
 
//Component
max(first: number, second: number): number {
  return Math.max(first, second);
}
 
                            
                        

Bind to an element property

We can use it to bind to a property of the HTML element, a component, or a directive. in the following code, we bind to the style.color property of the p element. We can bind to any property that accepts a string.

                              

<p>Show me <span class = "{{giveMeRed}}">red</span></p>
<p style.color={{giveMeRed}}>This is red</p>
 
                            
                        
Bind to an image source
                              
 
<div><img src="{{itemImageUrl}}"></div>
                            
                        
href
                              
 
<a href="/product/{{productID}}">{{productName}}</a>
                            
                        

Use a template reference variable

You can also use the template reference variable. The following example creates a template variable #name to an input box. You can use it get the value of the input field {{name.value}}

                              

<label>Enter Your Name</label>
<input (keyup)="0" #name>
<p>Welcome {{name.value}} </p>
                            
                        

We also use (keyup)="0" on the input element. It does nothing but it forces the angular run the change detection, which in turn updates the view.

                              
 
//Template
 
<p>items</p>
<ul>
  <li *ngFor="let d of items">
    {{ d.name }}
    </li>
</ul>
 
//Component
  items= [
    new item(1, 'Mobile'),
    new item(2, 'Laptop'),
    new item(3, 'Desktop'),
    new item(4, 'Printer')
  ]
 
class item {
  code:string
  name:string
 
  constructor(code,name) {
    this.code=code;
    this.name=name
  }
}
 
 
                            
                        

Cross-site Scripting or XSS

Angular Sanitizes everything before inserting into DOM, thus preventing Cross-Site Scripting Security bugs (XSS). For example values from the component property, attribute, style, class binding, or interpolation, etc are sanitized. The script in the following example is not invoked but shown as it is.

                              

//Template
<p>{{script}}</p>
<p>{{div}}</p>
 
//Component
script ='<script>alert("You are hacked")</script>'
div='<div>this is a div</div>';
                            
                        

NgNonBindable

Use ngNonBindable to tell Angular not to compile or bind the contents of the current DOM element. I.e any expression is not evaluated but shown as it is.

                              

<p>Evaluate: {{variable}}</p>
<p ngNonBindable>Do not evaluate: {{variable}}</p>
 
 
<p>Angular uses {{ variable }} syntax for Interpolation</p>
<p ngNonBindable>Angular uses {{ variable }} syntax for Interpolation</p>
                            
                        

Use Pipes

You can make use of Angular Pipes to transform the expression result. Like converting to an uppercase, date formats, adding currency symbols, etc

                              

<p>uppercase pipe: {{title | uppercase}}</p>
<p>pipe chain: {{title | uppercase | lowercase}}</p>
<p>json pipe: {{items | json}}</p>
                            
                        

The safe navigation operator (?)

You can make use of a safe navigation operator (?) to guards against null and undefined values.

The following code results in an error because there is no nullItem

                              
 
<p>The item name is: {{nullItem.Name}}</p>     
 
TypeError: Cannot read property 'itemName' of undefined
                            
                        

Use a safe navigation operator and the error goes away. Angular replace it with an empty string

                              

<>
                            
                        

The non-null assertion operator

Typescript enforces the strict null checking if you enable the --strictNullChecks flag in your tsconfig.json. Under strict null check any variable not defined or null results in a compiler error. The type checker also throws an error if it can’t determine whether a variable will be null or undefined at runtime

You can use the non-null assertion operator to inform typescript not to throw any compile errors. Note that it is a compile-time feature & not runtime.

                              
The item's name is: {{item!.name}}
                            
                        

Summary

Interpolation in Angular is a simple, yet powerful feature. It allows us to embed expressions in the string literal, Hence we can dynamically generate the string literal using the values from the component class.