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.
- Users.component.css
- Users.component.html
- Users.component.spec.ts
- Users.component.ts
Let’s modify our users.component.html file by adding a paragraph tag.
- <p>
- My Name is Adewale and i am 25 years old
- </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.
- @Component({
- selector: 'app-users',
- templateUrl: './users.component.html',
- styleUrls: ['./users.component.css']
- })
- export class UsersComponent implements OnInit {
- name = 'Adewale';
- age = 24;
- constructor() {}
- ngOnInit() {}
- }
Note that we can also create the properties by specifying the types using TypeScript in this way.
- name:string = 'Adewale';
- 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.
- <p>
- My name is {{name}} and i am {{age}} years old
- </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.
- <h1>
- <app-users></app-users>
- </h1>
Run your app with the following command.
ng serve
Finally, navigate your browser to localhost:4200