Advertisement
  1. Code
  2. JavaScript
  3. Angular

Creating Your First Angular App: Components, Part 1

Scroll to top
6 min read
This post is part of a series called Creating Your First Angular App.
Create Your First Angular App: Storing and Accessing Data
Creating Your First Angular App: Components, Part 2

The second tutorial of this series taught you how to store data inside the Angular app and access it using a service class. In this tutorial, we will create the HomeComponent for our Angular app.

The homepage or the HomeComponent that we are creating will list the top three countries in different categories like population and area. The data to determine the sorting order will be taken from the COUNTRIES array we created in the previous tutorial.

Creating the HomeComponent Class

To create the HomeComponent, change the directory in the console to your app folder and run the following command:

1
ng generate component home

This will create a folder called home inside the src/app folder with four files inside it. For this app, we only need to be concerned with three files named home.component.ts, home.component.css, and home.component.html. The home.component.ts file will contain all the logic for the component, and the CSS and HTML files will control the appearance and structure of the component.

Let's start by editing the home.component.ts file. The HomeComponent is supposed to show the top three most populated countries, the three largest countries, and the three countries with the highest GDP stored in the COUNTRIES array. 

We will be importing both the Country class and the CountryService class that we created in the last tutorial. We will also import Component and OnInit from @angular/core. The OnInit dependency provides a lifecycle hook that is called right after data-bound properties of a directive are initialized.

After importing all the necessary dependencies, we will define our component decorator. The component decorator is used to provide the necessary metadata information related to our component. We will set a value for the selector, templateUrl, and styleUrls inside the decorator. 

The selector is used to specify the tag that will be used to identify our component. The templateUrl is used to provide the URL for the template to be rendered when Angular encounters the provided selector. The styleUrls property is used to specify different stylesheets that should be applied to the given template. Here is the code inside home.component.ts up to this point:

1
import { Component, OnInit } from '@angular/core';
2
3
import { Country } from '../country';
4
import { CountryService } from '../country.service';
5
6
@Component({
7
  selector: 'app-home',
8
  templateUrl: './home.component.html',
9
  styleUrls: [ './home.component.css' ]
10
})

Now we will start defining the HomeComponent class with different properties and methods to help us show the country data to users. The HomeComponent class will have three different properties, which will accept an array of countries as their value. We can inject a dependency in the component's constructor by specifying a constructor parameter with the dependency type. That's how we will inject the CountryService class inside our HomeComponent

Here is the rest of the code for the home.component.ts file:

1
export class HomeComponent implements OnInit {
2
  populatedCountries: Country[] = [];
3
  largestCountries: Country[] = [];
4
  gdpCountries: Country[] = [];
5
6
  constructor(private countryService: CountryService) { }
7
8
  ngOnInit() {
9
    this.setPopulatedCountries();
10
    this.setLargestCountries();
11
    this.setGDPCountries();
12
  }
13
14
  setPopulatedCountries(): void {
15
    this.populatedCountries = this.countryService.getPopulatedCountries();
16
  }
17
18
  setLargestCountries(): void {
19
    this.largestCountries = this.countryService.getLargestCountries();
20
  }
21
22
  setGDPCountries(): void {
23
    this.gdpCountries = this.countryService.getGDPCountries();
24
  }
25
}

We have created three methods that use the CountryService class to get the countries with the largest area, the highest population, and the highest GDP. The arrays returned by different CountryService methods are then assigned to the corresponding properties of the HomeComponent class.

You should note that all these methods that set the value of populatedCountries, largestCountries, and gdpCountries are called inside the ngOnInit() method so that their values can be used as soon as the component is created.

Creating the HomeComponent Template

After writing the code for the HomeComponent class, it is time to create the HTML template for the component. Since the code inside home.component.html is mostly HTML, I will only be explaining the Angular-specific parts. Here is the code for the whole file:

1
<div class="container">
2
  <h2>Three Most Populated Countries</h2>
3
  <div class="group">
4
    <a *ngFor="let country of populatedCountries" class="country-unit" routerLink="/detail/{{country.name}}">
5
      <div class="country-block">
6
        <h4>{{country.name}}</h4>
7
        <p>{{country.population | number}}</p>
8
        <p>People</p>
9
      </div>
10
    </a>
11
  </div>
12
  <br>
13
  <h2>Three Largest Countries (Area)</h2>
14
  <div class="group">
15
    <a *ngFor="let country of largestCountries" class="country-unit" routerLink="/detail/{{country.name}}">
16
      <div class="country-block">
17
        <h4>{{country.name}}</h4>
18
        <p>{{country.area | number}} km
19
          <sup>2</sup>
20
        </p>
21
      </div>
22
    </a>
23
  </div>
24
  <br>
25
  <h2>Countries with Highest GDP</h2>
26
  <div class="group">
27
    <a *ngFor="let country of gdpCountries" class="country-unit" routerLink="/detail/{{country.name}}">
28
      <div class="country-block">
29
        <h4>{{country.name}}</h4>
30
        <p>{{country.gdp | number}} USD</p>
31
      </div>
32
    </a>
33
  </div>
34
</div>

As I have explained earlier, the populatedCountries, largestCountries, and gdpCountries have been assigned an array of Country objects as their value. We are using the NgFor directive to loop over all the countries in a specific array and show their names and respective properties. For example, *ngFor="let country of populatedCountries" loops over all the country objects inside the populatedCountries array and assigns that value to the local variable country. This directive also renders the corresponding a tag as well as all other tags inside it for each country object inside the populatedCountries array. The same explanation goes for all the country blocks rendered by iterating over largestCountries and gdpCountries.

We are using Angular pipes to properly format the population, area, and GDP values for different countries to make them more readable. One thing that you might find confusing is the routerLink directive that I have used with all the a tags. We will discuss it in more detail in the last tutorial of the series when we write code to traverse between different components or sections of the app. The value of the routerLink directive acts like a regular link that we come across on websites that we visit. The important difference is that instead of loading pages, we will be loading components.

Creating the CSS File for HomeComponent

Finally, you can write some CSS to make the HTML template more presentable. Here is the CSS that I have used for the HomeComponent. Keep in mind that this CSS needs to go inside the home.component.css file.

1
body {
2
  font-family: 'Lato';
3
}
4
5
h2, h3, h4, p {
6
  font-family: 'Lato';
7
  margin: 10px;
8
}
9
10
.country-block p {
11
  margin-top: 0;
12
  margin-bottom: 0;
13
}
14
15
.country-block h4 {
16
  margin-bottom: 10px;
17
}
18
19
h4 {
20
  position: relative;
21
  font-size: 1.25rem;
22
}
23
.container {
24
  margin: 0 50px;
25
  text-align: center;
26
}
27
28
.country-unit {
29
    width: 200px;
30
    display: inline-block;
31
    margin: 10px;
32
}
33
34
br {
35
  clear: both;
36
}
37
38
.country-block {
39
    padding: 30px 0;
40
    text-align: center;
41
    color: white;
42
    height: 150px;
43
    background-color: #795548;
44
    border-radius: 2px;
45
}
46
47
.country-block:hover {
48
  background-color: #9C27B0;
49
  cursor: pointer;
50
  color:white;
51
}

It is important that the CSS inside home.component.css is only applied to the elements inside the home.component.html file.

You might want to render HomeComponent inside the application shell by changing the contents of the app.component.html file to the following:

1
<h1>{{title}}</h1>
2
<app-home></app-home>

Unfortunately, you will get the following error when trying to do so:

1
Can't bind to 'routerLink' since it isn't a known property of 'a'.

We will talk more about the routerLink directive and how to get rid of this error in the fifth tutorial of this series. Right now, you can remove all mentions of routerLink from the home.component.html file to run your Angular application without any error. Just make sure that you add everything back to the file.

Final Thoughts

If you have never created an Angular app before, getting comfortable with components will take some time. For ease of understanding, you can consider components similar to different iframes loaded inside a webpage. The .ts files contain the logic for the component, just as .js files contain the logic for iframes. 

The .html files contain the elements that you want to render in an iframe or inside a component, and the .css files contain different style rules for those elements. I admit that this is not a very accurate comparison, but it should help beginners make sense of components and the relationship between different files of a component.

In the next tutorial, we will create two more components that will help you understand components more clearly. If you have any questions about the code related to HomeComponent, please let me know in the comments.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.