Introduction
The world of front-end web development is continuously evolving, choice of framework or library is crucial. Angular is a powerful framework used by developers worldwide to build dynamic and scalable web applications.
In this blog, we'll explore foundational elements of Angular in depth. By the end of this blog, you'll have a clear understanding of the key Angular concepts and how they work together to create efficient, maintainable applications.
What is Angular?
Angular is a TypeScript-based open-source front-end framework developed by Google. It's designed to build scalable, robust, and dynamic web applications.
Angular is a framework and not library having all built-in tools for everything from state management to form handling which makes it an obvious choice over other frontend libraries.
Angular Essentials
Modules
Components
Templates and Data Binding
Directives
Services and Dependency Injection
Routing
Modules
Think of Modules as a container that groups the related code into separate units. Angular has at least one module (root module) which acts as an entry point of your application.
Modules make the app more manageable and organized which also helps in lazy loading. You can think of modules analogous to packages in Java. We use @NgModule
to create a module.
In below code snippet, we used @NgModule
to create AppModule and,
declarations
: Defines which components, directives, and pipes belong to this module.
imports
: Specifies other modules that this module depends on.
providers
: This is where services are listed.
bootstrap
: Defines the root component (AppComponent
) that Angular should use to start the app.
Components
Components are the main building blocks of Angular applications. Each component represents a part of a larger web page.
For example, the navbar and the footer are the components of a landing web page. We use @Component
decorator to define a component in Angular. It’s responsible for displaying data, handling user input, and connecting to services to fetch or modify data. Each component in Angular consists of three main parts:
HTML Template: The structure of the UI that defines what the component will display.
CSS/Styles: The appearance and styling of the component’s UI elements.
TypeScript Class: The logic and behavior that control how the component works, interact with data, and handle user events.
// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `<h1>{{ title }}</h1>`,
styles: [`h1 { color: blue; }`]
})
export class AppComponent {
title = 'Hello, Angular!';
}
In above code snippet,selector
: The custom tag <app-root></app-root>
that will be used in the HTML to reference this component.
template
: A simple inline HTML template that displays the title
property.
styles
: Inline styles for the component, where the h1
text color is set to blue.
Templates and Data Binding
In Angular, templates define the basic structure of the component’s view and to connect the component’s data to template, we use data binding.
Types of Data Binding in Angular:
Interpolation
{{ }}
: To bind data from the component to the template (view).Example: Now consider in data you have set title as “First Blog” so as per below code snippet, it will dynamically display the title value i.e. “First Blog” in
<h1>
tag.<h1>{{ title }}</h1>
Property Binding: You are giving a property to an element. It's like telling a puppet, "Here’s your costume".
Example: You give the
src
property of the image the value ofimageUrl
from the component. IfimageUrl
changes, the image source updates automatically.<img [src]="imageUrl" />
Event Binding (
(event)
): To listen to events (like clicks or key presses) in the template and trigger component methods.Example: In below code, it listens for the
click
event and calls theonClick()
method in the component when the button is clicked.<button (click)="onClick()">Click Me!</button>
Two-Way Binding (
[(ngModel)]
): To bind data both ways — from the component to the view and from the view to the component.Example: Here,
[(ngModel)]
binds theuserName
property in the component to the input field. If the user types in the input field, theuserName
property in the component is updated automatically, and vice versa.<input [(ngModel)]="userName" /> <p>Hello, {{ userName }}!</p>
Directives
In Angular, directive are used to talk to the DOM. Directives tell Angular to do something with a DOM element, component or attribute.
There are three types of directives in Angular:
Structural Directives: These change the structure of the DOM by adding, removing, or manipulating elements.
Example:
*ngIf
,*ngFor
,*ngSwitch
In below, code because of
*ngIf
the<div>
is shown only ifisVisible == true
<div *ngIf="isVisible">This will only be displayed if isVisible is true.</div>
Attribute Directives: These change the appearance or behavior of an element, component, or another directive.
Example:
ngClass
,ngStyle
,ngModel
In below code snippet,
isHovered
value controls whether thehovered
class is added to the button. IfisHovered
istrue
, the button will have the "hovered" styling. IfisHovered
isfalse
, it will not.<!-- app.component.html --> <button [ngClass]="{ 'hovered': isHovered }"> Hover over me! </button>
Component Directives: These are technically a form of directive but are more specific. Components themselves are directives with templates.
Example:
app-root
(your custom component)
Services and Dependency Injection
Dependency Injection (DI): It is a design pattern in Angular that allows you to inject services or dependencies into components or other services. This promotes loose coupling by making it easy to manage dependencies.
Angular has an internal DI container which keeps the track of services and make sure that same instance is used throughout. This is similar to DI in Spring Boot.
Example:
@Injectable()
: The decorator makes this class available for dependency injection andprovidedIn: 'root'
: This tells Angular to provide the service globally (in the root injector).// data.service.ts import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class DataService { private data = ['Angular', 'React', 'Vue']; getData() { return this.data; } addData(newData: string) { this.data.push(newData); } }
Service: A service in Angular is a class that provides a specific functionality that can be used across multiple components. Services are typically used to manage data, business logic, and external API interactions.
Example: In below example, the
DataService
has a methodgetData()
that returns a list of items. The@Injectable()
decorator is used to tell Angular that this class can be injected into other components or services.
// data.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
getData() {
return ['Item 1', 'Item 2', 'Item 3'];
}
}
Routing
Routing in Angular allows you to navigate between different views (or pages) in a single-page application (SPA). It helps in mapping URL paths to components, enabling dynamic navigation, and allowing users to interact with different parts of the application without reloading the entire page.
Key Concepts of Routing in Angular:
RouterModule: The
RouterModule
is an Angular module that provides the routing functionalities, including defining routes, handling navigation, and configuring router-outlets.Routes: A route is an object that defines a path and a component that should be displayed when the URL matches that path.
Router Outlet: The
<router-outlet>
directive is a placeholder in the template where the routed component will be displayed.
Let’s understand routing step by step through a simple example.
Example: Setting Up Routing in Angular
Step 1. Create Components: We are defining three components(Pages) Home, About and Fallback page (NotFound)
ng generate component Home
ng generate component About
ng generate component NotFound
Step 2. Define Routes in AppRoutingModule
: First, we will set up our routes in a dedicated routing module (app-routing.module.ts
).
// app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { NotFoundComponent } from './not-found/not-found.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: '**', component: NotFoundComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Step 3. Import AppRoutingModule
in AppModule
: In our main app module (app.module.ts
), we will import the AppRoutingModule
.
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { NotFoundComponent } from './not-found/not-found.component';
@NgModule({
declarations: [
AppComponent,
HomeComponent,
AboutComponent,
NotFoundComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Step 4: Define Navigation Links in the Template: Now, we will use the routerLink
directive in your app.component.html
to create navigation links.
<!-- app.component.html -->
<nav>
<a routerLink="/">Home</a> |
<a routerLink="/about">About</a>
</nav>
<router-outlet></router-outlet>
Step 5: Add the Components’ Content: Now, we will add the contents of all the components in their respective files.
<!-- home.component.html -->
<h1>Welcome to the Home Page!</h1>
<p>This is the default page of the app.</p>
-------------------------------------------------------------------------------
<!-- about.component.html -->
<h1>About Us</h1>
<p>Learn more about the application.</p>
-------------------------------------------------------------------------------
<!-- not-found.component.html -->
<h1>404 - Page Not Found</h1>
<p>Sorry, the page you're looking for doesn't exist.</p>
By using the RouterModule
, router-outlet
, and routerLink
, Angular allows you to set up routing in a simple and efficient way.
Conclusion:
Mastering Angular’s core concepts— Modules, Components, Data Binding, Directives, Services, and Routing — forms the foundation for building dynamic, scalable applications. With these essentials in hand, you’re well on your way to further deep dive into Angular Development.
If you found this guide helpful, please share your thoughts in the comments and give a like. Your feedback is always appreciated. Happy coding!
Image credits - https://angular.dev/