Defining HTML Templates In Angular App

We can define HTML Templates in Angular App in two different ways.

We can write inline HTML within the template property of the component decorator, or we can place all the HTML for a given component within it’s own HTML file, with a path defined by the template URL property of the component decorator.

Templates_In_Angular

Templates_In_Angular

Depending upon the length of your HTML, you should decide whether you want to use a template file or just write inline HTML within the Component file. If you have a small segment of HTML write inline, otherwise it is better to write a separate template file to avoid cluttering within the Component file.

Creating HTML Templates In Angular Using Component File

To see how HTML templates in angular app work, let’s go the our “app.component.html file and replace the content with the following text:

<h1>

Welcome to {{ title }}!

</h1>

<p> Or does it? </p>
Save the file and ask the Angular CLI to serve this page by typing:
ng serve
You should be able to see the change immediately.

 

Loading Template In Angular

Loading Template In Angular

Thus the Template File is working as expected. Finally, let’s use Inline Template, to see if it works as well.

Creating HTML Templates In Angular Using Inline Template

In the “app.component.ts” file, rename the “templateUrl” property to simply “template“. Clear the existing value of it’s property and let’s add new value here.

First of all, write two back-ticks i.e “` `” which will allow us to write multi-line string values. Then within those back-ticks, add:

<h1>

Welcome to {{ title }}!

</h1>

<p> Or does it? </p>

Save the file and you can see we can see that instead of the HTML coming from an external template file, the HTML for this component is now coming from the component decorator’s template property.

In this way, we can define HTML templates in angular app in two different ways. Depending upon your needs, choose the right approach wisely.