Basics of Angular with Examples
Angular is a popular front-end framework for building dynamic, single-page web applications using HTML, CSS, and TypeScript. It provides a complete solution for building scalable apps with clear structure, reusable components, built-in routing, form handling, HTTP communication, and more.
If you are coming from plain JavaScript or jQuery, Angular might look complex at first, but once you understand a few core concepts—components, templates, data binding, directives, services, and modules—the framework starts to feel much more logical and powerful.
What Is Angular?
Angular is a TypeScript-based, component-driven framework maintained by Google. It is used mainly for building single-page applications (SPAs), where most of the UI is rendered on the client side and the page does not reload on every navigation.
Unlike simple libraries that only handle one part of the UI, Angular is a full-featured framework. It comes with its own CLI, routing system, dependency injection, form handling, HTTP client, and a powerful template syntax, so you can build complete applications without constantly adding third-party tools.
Setting Up an Angular Project (Quick Overview)
To work with Angular, you typically use the Angular CLI (Command Line Interface). Once you have Node.js and npm installed, you can install the CLI and create a new project.
// Install Angular CLI globally
npm install -g @angular/cli
// Create a new Angular project
ng new my-angular-app
// Navigate into the project folder
cd my-angular-app
// Run the development server
ng serve -o
The command ng serve -o starts a dev server and opens your app in the browser, usually at http://localhost:4200. The CLI also helps you generate components, services, and other building blocks using simple commands.
Core Building Block: Components
Components are the heart of Angular applications. A component controls a part of the user interface, called a view. Each component is made up of:
- A TypeScript class that holds data and logic.
- An HTML template that defines how the view looks.
- Optional CSS styles that apply to that template.
- A metadata decorator that tells Angular how to use the component.
Basic Component Example
Here is a simple Angular component that displays a greeting:
// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular Basics';
username = 'Developer';
}
<!-- app.component.html -->
<h1>{{ title }}</h1>
<p>Welcome, {{ username }}!</p>
The @Component decorator provides metadata like selector, templateUrl, and styleUrls. The selector (app-root) is the custom HTML tag you use to place this component in your main HTML file.
Templates and Data Binding
Angular templates extend regular HTML with special syntax for binding data from the component class to the view and responding to user events. Data binding is one of the most important Angular basics to understand.
Types of Data Binding
- Interpolation – Display data from the component in the template using
{{ }}. - Property binding – Bind values to HTML element or component properties using
[ ]. - Event binding – Listen for events and call component methods using
( ). - Two-way binding – Combine property and event binding for form elements using
[(ngModel)].
Interpolation Example
<h2>User: {{ username }}</h2>
<p>Today is {{ currentDate }}</p>
In the component, you might have:
currentDate = new Date().toDateString();Property Binding Example
<img [src]="profileImageUrl" [alt]="username + ' profile'">profileImageUrl = 'assets/profile.png';Event Binding Example
<button (click)="onLogin()">Login</button>onLogin() {
alert('Login clicked!');
}Two-Way Binding Example (with ngModel)
For two-way binding, you need to import FormsModule in your module. Then you can bind form fields directly to component properties:
<input [(ngModel)]="username" placeholder="Enter your name">
<p>Hello, {{ username }}!</p>
Now, whenever the user types in the input field, the username property in the component is updated automatically, and the view reflects the latest value.
Directives: Adding Behavior to Templates
Directives are special markers in the DOM (attributes or tags) that tell Angular to do something with the element. Angular has three main types of directives:
- Component directives – basically components themselves.
- Structural directives – change the DOM layout (for example,
*ngIf,*ngFor). - Attribute directives – change the appearance or behavior of an element (for example,
[ngClass],[ngStyle]).
*ngIf Example
<button (click)="isLoggedIn = !isLoggedIn">
Toggle Login
</button>
<p *ngIf="isLoggedIn">You are logged in.</p>
<p *ngIf="!isLoggedIn">You are logged out.</p>
isLoggedIn = false;
The *ngIf directive adds or removes elements from the DOM based on the condition.
*ngFor Example
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
items = ['Angular', 'React', 'Vue'];
The *ngFor directive repeats the <li> element for each item in the items array.
Attribute Directive Example (ngClass)
<p [ngClass]="{ 'active': isActive, 'inactive': !isActive }">
Status: {{ isActive ? 'Active' : 'Inactive' }}
</p>isActive = true;
Here, the paragraph element will get the active or inactive CSS class based on the boolean value.
Services and Dependency Injection
In Angular, components should focus on displaying data and handling user interactions. Shared logic, API calls, and state are often better placed inside services. Services are classes that provide reusable functionality across the app.
Angular has a built-in dependency injection (DI) system that makes it easy to provide and use services in components or other services.
Simple Service Example
First, create a service:
// message.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class MessageService {
getWelcomeMessage(name: string): string {
return `Welcome to Angular, ${name}!`;
}
}
Then inject and use it in a component:
// app.component.ts
import { Component } from '@angular/core';
import { MessageService } from './message.service';
@Component({
selector: 'app-root',
template: `
<h1>{{ title }}</h1>
<input [(ngModel)]="username" placeholder="Enter your name">
<button (click)="showMessage()">Show Message</button>
<p>{{ message }}</p>
`
})
export class AppComponent {
title = 'Angular Basics';
username = '';
message = '';
constructor(private messageService: MessageService) {}
showMessage() {
this.message = this.messageService.getWelcomeMessage(this.username || 'Guest');
}
}
The MessageService is provided in the root injector, meaning a single instance is shared across the app. The component receives the service through its constructor and can call its methods whenever needed.
Modules in Angular
An Angular application is organized into modules. A module is a container for related components, directives, pipes, and services. The main module of most apps is called AppModule.
A typical root module looks like this:
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent // declare components, directives, pipes here
],
imports: [
BrowserModule,
FormsModule // import other Angular modules here
],
providers: [],
bootstrap: [AppComponent] // root component to bootstrap
})
export class AppModule {}
The bootstrap array defines the root component that Angular should load first. The imports array brings in other modules, like BrowserModule for browser support and FormsModule for template-driven forms.
Routing Basics (Optional but Common)
Most real Angular apps have multiple pages (views) managed on the client side using Angular’s Router. Routing lets you map URLs to specific components.
Here is a minimal routing example:
// app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home.component';
import { AboutComponent } from './about.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
You then include <router-outlet></router-outlet> in a template (usually in AppComponent) to tell Angular where to render the routed components.
Putting It All Together: Small Example App
Imagine a very simple Angular “Task List” app with these features:
- Input field to add a task.
- List of tasks displayed below.
- Click to mark a task as done.
Component Class
// app.component.ts
import { Component } from '@angular/core';
interface Task {
title: string;
done: boolean;
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
newTask = '';
tasks: Task[] = [
{ title: 'Learn Angular basics', done: false },
{ title: 'Build a simple app', done: false }
];
addTask() {
const title = this.newTask.trim();
if (!title) {
return;
}
this.tasks.push({ title, done: false });
this.newTask = '';
}
toggleTask(task: Task) {
task.done = !task.done;
}
}Component Template
<h1>Angular Task List</h1>
<input
[(ngModel)]="newTask"
placeholder="Enter a new task">
<button (click)="addTask()">Add Task</button>
<ul>
<li
*ngFor="let task of tasks"
(click)="toggleTask(task)"
[ngClass]="{ 'done': task.done }">
{{ task.title }}
</li>
</ul>Basic Styles (Optional)
/* app.component.css */
ul {
list-style: none;
padding: 0;
}
li {
cursor: pointer;
padding: 4px 0;
}
li.done {
text-decoration: line-through;
color: gray;
}
This small example already uses several Angular basics you learned: components, templates, interpolation, two-way binding, *ngFor, [ngClass], and event binding. From here, you can extend the app with services, routing, and more advanced features.
Conclusion
The basics of Angular revolve around a few fundamental concepts: components, templates, data binding, directives, services, and modules. Once you understand how these pieces work together, you can start building clean, maintainable single-page applications with a clear structure.
As a next step, you can explore Angular forms, routing in more depth, HTTP communication with backend APIs, and state management patterns. With practice, Angular becomes a powerful and productive tool for building modern web applications.

0 Comments