template vs templateUrl

In this tutorial, you will learn the difference between template and templateUrl. You will learn what is template and templateUrl with examples and when to use them.

template:

By using template in angular you can specify inline HTML for a component. If you use template you don’t have to provide an external path of HTML file.

template example:

You can render your view of an angular component by writing HTML code into a template.
You can use single quotes, double quotes to put your HTML code inside it. But in this case, all your HTML code has to be in a single line.
You can use backticks to put multiple HTML code lines. In the following example, I have used backticks to put multiple lines of HTML code into template.

@Component({
  selector: 'app-root',
  template:
    `
   <h1>Hello from Devconquer!!!</h1>
   <h3>
   Learn angular from following articles:
   <a target="_blank" href="https://devconquer.com/category/angular/">Angular articles</a>
   </h3>
  `,
  styleUrls: ['./app.component.css']
})

Output:

templateUrl:

In templateUrl, you can provide the relative path or absolute URL of a template file for a component. If templateUrl is used, do not use inline HTML using template.

templateUrl example:
By using templateUrl you can render a view of a component. You have to provide a path of an external HTML file for templateUrl.

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

You can then put all your HTML code into that external file. Here I have created the app.component.html external file and provided it as templateUrl. You can put your HTML code into an external HTML file like the following:

<h1>Hello from Devconquer!!!</h1>
<h3>
Learn angular from following articles:
<a target="_blank" href="https://devconquer.com/category/angular/">Angular articles</a>
</h3>

Output:

**Note: Output will be the same when the same HTML is included using property template or templateUrl.

When to use templateUrl and templateUrl?

  1. If you have small lines of code for a component then use template property.
  2. If you have complex and many lines of HTML code then it is recommended to use templateUrl.
  3. If you use template then you will not get the feature of VS Code like intelligence support, code-completion, and formatting. But if you use templateUrl you will get the feature of VS Code like intelligence support, code-completion, and formatting. It is always better to have a feature like intelligence support, code-completion, and formatting for faster coding and syntax error preventions.

From this article, you learned what is template and templateUrl. You also learned the difference between them and when to use them.

See also:

*ngFor in angular
Components in angular
Services in angular

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments