Skip to main content

Angular Introduction

What is Angular?

Angular logo

Angular is a powerful, open-source front-end web application framework developed and maintained by Google. It allows developers to build dynamic, single-page applications (SPAs) with a clean architecture and powerful features. Angular uses TypeScript, a superset of JavaScript that adds static typing and other features to help you build robust applications.

Angular provides a complete solution for front-end development with built-in features like:

  • Component-based architecture
  • Dependency injection
  • Declarative templates
  • End-to-end tooling
  • Comprehensive routing capabilities
  • Form handling
  • HTTP client

Why Learn Angular?

Here are compelling reasons to learn Angular:

  1. Enterprise-Ready: Angular is designed for enterprise-scale applications with stability and long-term support.
  2. Complete Framework: Unlike some libraries that handle only UI components, Angular provides a complete solution.
  3. Strong TypeScript Integration: Enjoy the benefits of type checking, better code completion, and improved refactoring.
  4. Large Community: Access extensive resources, libraries, and community support.
  5. Backed by Google: Benefit from continuous updates and improvements from Google's engineering team.

Angular vs. Other Frameworks

FeatureAngularReactVue.js
TypeComplete frameworkLibraryProgressive framework
LanguageTypeScriptJavaScript (with JSX)JavaScript
Learning CurveSteeperModerateGentle
Data BindingTwo-wayOne-wayTwo-way
DOMRegular DOMVirtual DOMVirtual DOM
FlexibilityOpinionatedFlexibleFlexible

Setting Up Your First Angular Project

Prerequisites

Before you start, make sure you have:

  1. Node.js and npm: Angular requires Node.js version 14.x or higher.
  2. Angular CLI: A command-line interface tool for initializing, developing, and maintaining Angular applications.

Installation Steps

  1. Install the Angular CLI globally:
bash
npm install -g @angular/cli
  1. Create a new Angular project:
bash
ng new my-first-angular-app

During setup, you'll be asked if you want to:

  • Add Angular routing (recommended for most applications)
  • Select a stylesheet format (CSS, SCSS, Sass, or Less)
  1. Navigate to your project directory:
bash
cd my-first-angular-app
  1. Start the development server:
bash
ng serve

This will start a development server at http://localhost:4200/. Your application will automatically reload when you make changes to any of the source files.

Angular Core Concepts

Components

Components are the building blocks of Angular applications. A component consists of:

  • A TypeScript class with the @Component decorator
  • An HTML template
  • CSS styles (optional)

Here's a simple example of an Angular component:

typescript
// hello.component.ts
import { Component } from '@angular/core';

@Component({
selector: 'app-hello',
template: '<h1>Hello, {{name}}!</h1>',
styles: ['h1 { color: blue; }']
})
export class HelloComponent {
name = 'Angular';
}

To use this component, you would include it in a template using its selector:

html
<app-hello></app-hello>

Output:

Hello, Angular!

(displayed in blue)

Modules

Angular applications are modular. The NgModule decorator identifies a class as an Angular module. The main module in every Angular application is the AppModule:

typescript
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';

@NgModule({
imports: [BrowserModule],
declarations: [AppComponent, HelloComponent],
bootstrap: [AppComponent]
})
export class AppModule { }

Templates

Templates are written in HTML but can include Angular-specific syntax for data binding, directives, and expressions:

html
<div>
<h1>{{title}}</h1>
<p *ngIf="isVisible">This paragraph is conditionally displayed.</p>

<ul>
<li *ngFor="let item of items">{{item}}</li>
</ul>

<button (click)="doSomething()">Click me!</button>
</div>

Data Binding

Angular provides several ways to bind data:

  1. Interpolation: {{expression}}
  2. Property binding: [property]="expression"
  3. Event binding: (event)="handler"
  4. Two-way binding: [(ngModel)]="property" (requires FormsModule)

Example:

typescript
// counter.component.ts
import { Component } from '@angular/core';

@Component({
selector: 'app-counter',
template: `
<h2>Counter: {{ count }}</h2>
<button (click)="increment()">Increment</button>
<button (click)="decrement()">Decrement</button>
`
})
export class CounterComponent {
count = 0;

increment() {
this.count++;
}

decrement() {
if (this.count > 0) {
this.count--;
}
}
}

Building a Simple To-Do List Application

Let's apply what we've learned by creating a simple to-do list application:

  1. Create a new component:
bash
ng generate component todo-list
  1. Define the component class:
typescript
// todo-list.component.ts
import { Component } from '@angular/core';

interface Todo {
id: number;
text: string;
completed: boolean;
}

@Component({
selector: 'app-todo-list',
templateUrl: './todo-list.component.html',
styleUrls: ['./todo-list.component.css']
})
export class TodoListComponent {
todos: Todo[] = [
{ id: 1, text: 'Learn Angular', completed: false },
{ id: 2, text: 'Build a todo app', completed: false },
{ id: 3, text: 'Deploy application', completed: false }
];

newTodoText = '';

addTodo() {
if (this.newTodoText.trim()) {
const newId = this.todos.length > 0 ? Math.max(...this.todos.map(t => t.id)) + 1 : 1;
this.todos.push({
id: newId,
text: this.newTodoText.trim(),
completed: false
});
this.newTodoText = '';
}
}

toggleComplete(todo: Todo) {
todo.completed = !todo.completed;
}

deleteTodo(id: number) {
this.todos = this.todos.filter(todo => todo.id !== id);
}
}
  1. Create the template:
html
<!-- todo-list.component.html -->
<div class="todo-container">
<h2>My Todo List</h2>

<div class="add-todo">
<input
type="text"
[(ngModel)]="newTodoText"
placeholder="Add a new task..."
(keyup.enter)="addTodo()"
>
<button (click)="addTodo()">Add</button>
</div>

<ul class="todo-list">
<li *ngFor="let todo of todos" [class.completed]="todo.completed">
<input
type="checkbox"
[checked]="todo.completed"
(change)="toggleComplete(todo)"
>
<span>{{ todo.text }}</span>
<button class="delete" (click)="deleteTodo(todo.id)">Delete</button>
</li>
</ul>

<div class="stats">
<p>{{ todos.length }} total items, {{ todos.filter(t => !t.completed).length }} remaining</p>
</div>
</div>
  1. Add some styles:
css
/* todo-list.component.css */
.todo-container {
max-width: 500px;
margin: 0 auto;
padding: 20px;
font-family: Arial, sans-serif;
}

.add-todo {
display: flex;
margin-bottom: 20px;
}

.add-todo input {
flex: 1;
padding: 8px;
margin-right: 8px;
}

.todo-list {
list-style-type: none;
padding: 0;
}

.todo-list li {
display: flex;
align-items: center;
padding: 8px 0;
border-bottom: 1px solid #eee;
}

.todo-list li.completed span {
text-decoration: line-through;
color: #888;
}

.todo-list li span {
flex: 1;
margin: 0 10px;
}

.delete {
background: #ff6b6b;
color: white;
border: none;
padding: 5px 10px;
border-radius: 3px;
cursor: pointer;
}

.stats {
margin-top: 20px;
color: #666;
font-size: 0.9em;
}
  1. Import FormsModule in your app.module.ts:
typescript
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms'; // Add this import

import { AppComponent } from './app.component';
import { TodoListComponent } from './todo-list/todo-list.component';

@NgModule({
declarations: [
AppComponent,
TodoListComponent
],
imports: [
BrowserModule,
FormsModule // Add this module
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
  1. Add the to-do component to your app.component.html:
html
<!-- app.component.html -->
<div class="app-container">
<h1>Angular Todo App</h1>
<app-todo-list></app-todo-list>
</div>

This simple to-do list demonstrates several core Angular concepts:

  • Components and templates
  • Property and event binding
  • Two-way binding with ngModel
  • Structural directives (ngFor and ngIf)
  • Class binding
  • TypeScript interfaces

Best Practices for Angular Development

  1. Follow Angular Style Guide: Adhere to the official Angular Style Guide.

  2. Maintain a Clean Component Structure: Keep components focused on specific functionality.

  3. Use Lazy Loading: Load features only when needed to improve initial load time.

  4. Implement Proper Error Handling: Handle errors gracefully in services and components.

  5. Write Unit Tests: Use Jasmine and Karma (built into the Angular CLI) for testing.

  6. Use TypeScript Features: Take advantage of interfaces, types, and other TypeScript features.

  7. Optimize Change Detection: Use OnPush change detection strategy for better performance.

Summary

In this introduction to Angular, we've covered:

  • What Angular is and why it's a powerful framework for web applications
  • How to set up your development environment and create your first Angular project
  • Core Angular concepts like components, modules, templates, and data binding
  • Building a practical to-do list application that demonstrates these concepts
  • Best practices for Angular development

Angular's robust architecture and comprehensive features make it an excellent choice for building complex, scalable web applications. While it has a steeper learning curve than some alternatives, the structure and tools it provides can lead to more maintainable code in larger projects.

Additional Resources

Exercises

  1. Enhance the to-do list application with the ability to edit existing items.
  2. Add priority levels (high, medium, low) to tasks and allow sorting by priority.
  3. Implement local storage to persist the to-do items between page refreshes.
  4. Create a filter system to show all, active, or completed tasks.
  5. Split the application into multiple components (e.g., TodoItem, TodoForm, TodoFilters).

Good luck with your Angular journey! The concepts you learn here will provide a solid foundation for building modern web applications.



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)