String Interpolation In Angular 4

In this write-up, I will be showing you how to dynamically change the content of your component’s template file with String Interpolation.

I will assume that you already know how to create a new Angular 4 application but if you don’t, check http://www.c-sharpcorner.com/article/creating-first-angular-4-application/ by Sourabh Somani to learn how to create an Angular 4 application.

After installing Angular, let’s create a new component called users with our Angular CLI using -

ng generate component users

or

ng g c users

which will generate users directory in our src/app directory with the following files. 

  1. Users.component.css  
  2. Users.component.html  
  3. Users.component.spec.ts  
  4. Users.component.ts  

Let’s modify our users.component.html file by adding a paragraph tag.

  1. <p>  
  2.    My Name is Adewale and i am 25 years old  
  3. </p>  

What we will change dynamically is the name and age in users.component.html, by creating name and age property in users.component.ts TypeScript file.

  1. @Component({  
  2.     selector: 'app-users',  
  3.     templateUrl: './users.component.html',  
  4.     styleUrls: ['./users.component.css']  
  5. })  
  6. export class UsersComponent implements OnInit {  
  7.     name = 'Adewale';  
  8.     age = 24;  
  9.     constructor() {}  
  10.     ngOnInit() {}  
  11. }  

Note that we can also create the properties by specifying the types using TypeScript in this way.

  1. name:string = 'Adewale';  
  2. age:number = 25;  

In users.component.html, we will be using double curly braces {{}} which will enable us to type TS expressions in between. Modify the name and age like the following code.

  1. <p>  
  2.    My name is {{name}} and i am {{age}} years old  
  3. </p>  

Note- String interpolations can only display strings or types that can be easily converted to string like age in the above example. We can also insert normal strings {{“name”}} or methods inside our curly braces.

The next thing is to insert our component tag in our app.component.html in the Angular 4 app directory.

  1. <h1>  
  2.    <app-users></app-users>  
  3. </h1>  

Run your app with the following command.

ng serve

Finally, navigate your browser to localhost:4200