Understanding Components

In this lesson, we'll discuss what components are.

Let’s discuss some theory before jumping into our project code. One of the major features of Angular is components. Components are custom reusable elements. They were introduced to break an application into smaller pieces.

The browser has a limited set of markup tags that it can understand. There are some tags that have functionality defined by the browser, such as the <select>, <video>, and <audio> tags. These are powerful tags, but what if we want to teach the browser additional tags? Maybe we want a tag that displays a credit card number input or a tag that outputs pagination links.

This is where components come into play. Components are a way to teach the browser new tags.

The problem

Let’s look at an example of why components are necessary. In the example below, we have a list of posts.

Press + to interact
<div class="post">
<img src="image1.png">
<div class="author">John</div>
<div class="title">Some Title</div>
</div>
<div class="post">
<img src="image2.png">
<div class="author">Jane</div>
<div class="title">Another Title</div>
</div>
<div class="post">
<img src="image3.png">
<div class="author">Luis</div>
<div class="title">A Third Title</div>
</div>

The HTML structure is the same for each post. There’s an image, author, and title. The difference between each post is the content.

This approach is not scalable. If we want to add more posts, we’d have to duplicate the same HTML structure and replace the content. What if we want to change the structure of a post? We’d have to update each post’s markup. This would take a lot of time if there were hundreds of posts.

The solution

Components easily solve this ...