Skip to main content

My Angular 18 crash course

· 5 min read
Guster
Full-stack Staff Engineer

image

Introduction

Angular is a powerful and versatile web application framework that enables developers to create robust, high-performance applications with ease. It provides a rich set of tools and features designed to streamline the development process and enhance code maintainability. By leveraging Angular's component-based architecture, developers can build scalable and modular applications that are both efficient and easy to maintain.

In this guide, I’ll briefly walk you through the essential steps to set up and run an Angular project, giving you a solid foundation to start your journey into Angular development. From installation and project creation to understanding the core concepts.

Installation

Prerequisites

  • Node.js - v18.9.1 or newer
  • CLI

Install Angular CLI

npm install -g @angular/cli

For more details, follow the installation guide on the official documentation.

CLI Commands

  • ng new <project-name> - Create a new project

  • ng generate - Generate Angular resources

    • ng generate component <name> - Generate component
    • ng generate service <name> - Generate service class
    • ng generate class <name> - Generate a class
    • ng generate directive <name> - Generate a directive
    • ng generate interceptor <name> - Generate an interceptor
    • ng generate guard <name> - Generate a authentication guard
  • npm start - Start local development

  • npm run test - Run unit tests

  • npm run build - Build a project

Create a new project

To create a new project, run command ng new <project_name>, eg. ng new my-todo-app, this will generate a new project with the following file structure. The source codes will be inside the /src directory.

.
├── README.md
├── angular.json
├── dist
├── package-lock.json
├── package.json
├── public
├── server.ts
├── src
├── tsconfig.app.json
├── tsconfig.json
└── tsconfig.spec.json

Component

When we generate a Angular component with ng generate component, the CLI will scaffold the following files. Example:

src/app/
├── app.component.css
├── app.component.html
├── app.component.spec.ts
├── app.component.ts

These files are self-explanatory: the .css file contains the CSS styling, while the .html file defines the component's UI, and .spec for unit test.

Alternatively, we can use the template and styles attributes in the @Component decorator to include CSS and HTML code directly in app.component.ts, creating a single-file component.

Component with external template and CSS:

@Component({
selector: 'app-root',
standalone: true,
imports: [],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent {}

Single-file component:

@Component({
selector: 'app-root',
standalone: true,
imports: [],
template: `<div>hello world</div>`,
styles: {...}
})
export class AppComponent {}

A component can be used in a template with its selector. For example, if you want to use a custom component <my-custom-button>in this component, you first need to import it with imports: [MyCustomButton]

@Component({
selector: 'app-root',
standalone: true,
imports: [MyCustomButton],
styleUrl: './app.component.css',
template: `
<my-custom-button></my-custom-button>
`,
})
export class AppComponent {}

Dependency Injection (DI)

Make a class Injectable

Dependency Injection (DI) is a core concept in Angular, widely used throughout the application. DI allows us to incorporate dependencies into classes while Angular manages their lifecycle.

To make a class injectable, decorate it with the @Injectable decorator. For instance, consider a service class named AuthService.

@Injectable({ providedIn: 'root' })
class AuthService {}

The providedIn: 'root' option tells Angular to provide AuthService at the application's root level, allowing it to be injected into all other classes. This approach enables Angular and JavaScript code optimizers to effectively remove unused services—a process known as "tree-shaking."

Injecting a dependency

Once we have made a class injectable with @Injectable, there are two ways we can use it in other classes.

  1. Inject in the constructor

    @Component({})
    class AppComponent {
    constructor(private service: AuthService) {}
    }
  2. Inject with the built-in inject method

    @Component({})
    class AppComponent {
    private service = inject(AuthService);
    }

💡 Tips: Angular CLI provides a quick way to create a service class: ng generate service services/auth

This create a AuthService in /services directory

Routing

Angular features a built-in router for implementing navigation between pages. Here are the steps to set up the navigation routes:

  1. Add provideRouter in app.config.ts

    export const appConfig: ApplicationConfig = {
    providers: [provideRouter(routes)]
    };
  2. Setup a list of routes in app.routes.ts

    export const routes: Routes = [
    { path: '', component: MainPage },
    { path: 'login', component: LoginPage },
    { path: '**', component: NotFoundPage }, // all other routes
    ];
  3. Add RouterLinkRouterLinkActive, and RouterOutlet to your AppComponent's imports option

    @Component({
    selector: 'app-root',
    standalone: true,
    imports: [RouterOutlet, RouterLink, RouterLinkActive],
    templateUrl: './app.component.html',
    styleUrl: './app.component.css'
    })
    export class AppComponent {}
  4. Add the routes to your app-component.html. <router-outlet> tells Angular to render the selected route’s component view into the application.

    <nav>
    <ul>
    <li><a routerLink="/" routerLinkActive="active" ariaCurrentWhenActive="page">Home</a></li>
    <li><a routerLink="/login" routerLinkActive="active" ariaCurrentWhenActive="page">Login</a></li>
    </ul>
    </nav>

    <router-outlet></router-outlet>

For more advanced routing techniques in Angular, visit the official documentation.

Environment Configuration

Angular has a built-in feature to customise configuration for different environments such as dev, staging, prod, etc. Follow the steps below.

Step 1:

Run ng generate environments to generate default environment files. Angular will generate the following files:

  • environments/environment.ts - file as the default config
  • angular.json - where you define the environments

Step 2:

Create a custom environment file, eg. environments/environment.staging.ts and copy the values from the default config file here.

Step 3:

Run ng build --configuration staging and it will replace the environments/environment.ts with environments/environment.staging.ts

Concluding Thoughts

Angular is a comprehensive web framework packed with built-in features that enable efficient and unified web application development. This guide merely scratches the surface of Angular's capabilities. For a deep dive into its more advanced features, check out the official documentation.