Categories
Frontend Development Web Development

Learning Angular: Part 1 (Components, Routing, Directives & Services)

Learn what Angular is and the basic concepts around the popular framework created by Google so you can start developing frontend applications.

What is Angular?

Angular is an open-source frontend framework created at Google. It facilitates the creation of Single Page Applications (SPA) through its many of functionalities and concepts.

An important note to know is that “Angular” is a totally different framework from “Angular.js”. While Angular.js refers to the version 1.x of the framework, Angular is a complete rewrite of the framework starting in version 2.x and currently going at version 8.x.

Because Angular.js and Angular are two completely different frameworks I wanted to let you know that this post is focused on the most recent version called Angular.

Requirements

Installation

Installation of Angular is very simple because the Angular team created an Angular CLI which helps with the creation of projects, components, services and different concepts that you’ll learn through this post. The Angular CLI is also used for building an application for development and production.

  1. First we’ll need to install the Angular CLI through NPM
    • npm install -g @angular/cli
  2. Then we need to create an Angular App.
    • ng new angular-awesome-app
  3. And finally you can serve your application to your web browser:
    • cd angular-awesome-app
    • ng serve --open

The ng serve --open command will serve and open your application in http://localhost:4200/ and whenever you make a change in the Angular files the server will automatically reload and show the updated version so you can develop more easily.

Angular Concepts

Components

Components are the basic building blocks of Angular applications and they encapsulate reusable code normally by page being displayed or in a bigger and more modular application, by features or UI elements.

Components are made by three important elements:

  1. Component Class: The class is responsible for handling the dependencies to use in a component, the methods and properties available to use and component specific functionalities.
  2. Component Template: Template is used to display the user with the content that they’ll see whenever that component loads and is normally created with HTML or more components.
  3. Component Styles: Styles are CSS rules specific for the component and they control how the template should look like.

You can generate new components through the Angular CLI with the following command:


ng generate component 'components/Profile'

Because we specified the path of the new component as 'components/Profile' the command will create a new folder called components inside /src/app first, and then it will create a profile folder for the component inside the components folder. This will help us keep all the components more organized under one common folder and not messed with all the files under the /src/app directory.

Routing

As this is just the first post of a series of posts on Angular, I’m covering Routing in a very simple way but I’ll cover it in more detail in the upcoming posts.

Angular Routing is managed through the Angular Router module and in its more basic functionality, allows you to map the URL being displayed in the browser with a component in your application like this:


// File: /src/app/app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { ProfileComponent } from './components/profile/profile.component';

const routes: Routes = [
  { path: 'profile', component: ProfileComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Now whenever you visit the url http://localhost:4200/profile you’ll see the content of the ProfileComponent being displayed on the page.

A couple of things make the routing functionality posible and I’ll explain them here in their more basic form. One way I think is easier to understand routing is to think about this 3 questions relative to Angular Components.

What? (Which Component?)

In the example above we are telling in the routes that we want to show the ProfileComponent.

When? (When to show the Component?)

Following the example above, the criteria to show the ProfileComponent is that the URL path must be equal to profile, that means that the URL in the browser needs to look something like this http://localhost:4200/profile.

Where? (Where to show the Component?)

The where is instructed by the location of the <router-outlet></router-outlet> directive in the application. In a new Angular application this directive is normally located in the file: /src/app/app.component.html and that means that whenever the router needs to display a component it will load it in here.

As I mentioned above this is just the basic functionality on Routing, I’ll update this post with the link to the post covering Routing more deeply when I finished with that post. If you are curious or want to know more options on Routing you can check the resources section at the end of this post.

Directives

In Angular there are three types of directives:

  1. Components Directives: These directives are the most common because they refer to the same components we talked above in this post. Examples:
    1. <app-root></app-root>
    2. <profile></profile>
  2. Attribute Directives: The attribute directives look like normal HTML attributes but they allow the customization of a component or another directive.
    1. <div [ngClass]="(isLogged) ? 'logged' : '';"></div>
    2. <span customAttribute="true"></span>
  3. Structural Directives: They influence how the structure of a template should look like, like deciding to show or hide elements like *ngIf or deciding how many items to show on a list like *ngFor, etc.
    1. <p *ngIf="hasTitle">{{ title }}</p>
    2. <div>*ngFor="let item of items;">{{ item }}</div>

Services

Services are special classes normally created with the functionality and logic needed in different components (like API calls, validations, loggers, etc). By creating a Service with functionalities that needs to be use in different components we reduce the size of our components and make the code on our Services reusable and easily maintainable in one place.

The Services can be injected into a component through Dependency Injection and use their functionalities from an instance in the Component, this lets the Components focus only on the methods and properties use specifically for data binding with the templates.

Angular CLI allows simple generation of Services through the command:


ng generate service 'services/user/User'

In the same way we generated a component with the CLI this will also generate a services folder inside the /src/app folder and then a user folder inside /src/app/services. This will helps us keep all the services organized under the /src/app/services folder.

The UserService will look like this:


// File: /src/app/services/user/user.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class UserService {

  constructor() { }

  getUser(): object {
    return {
      name: 'Jon',
      lastName: 'Snow',
      position: 'King in the north'
    };
  }
}

And then we can use the UserService in the ProfileComponent like this:


// File: /src/app/components/profile/profile.component.ts

import { Component, OnInit } from '@angular/core';

import { UserService } from '../../services/user/user.service';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.scss']
})
export class ProfileComponent implements OnInit {

  public user: any;

  constructor(private userService: UserService) { }

  ngOnInit() {
    this.user = this.userService.getUser();
  }

}

Conclusion

We cover some of the basic concepts from Angular in this post, going from the building blocks of Angular, The Components, through the classes where we can group reusable functionality independent from the Components, The Services.

I hope this guide helps you and if you have a suggestion or feedback please leave it in the comments, thank you for reading.

In the next post I plan to cover some other concepts of Angular but in the mean time you can get to play with the Angular CLI, Components, Routing, Directives and Services.

Resources

You can find all of the source code for this project in its GitHub repository. And also you can see the live example in Stackblitz.

For additional resources you can check the following links:

1 reply on “Learning Angular: Part 1 (Components, Routing, Directives & Services)”

Leave a Reply

Your email address will not be published. Required fields are marked *