0% found this document useful (0 votes)
3 views

angularr

Angular is an open-source web application framework developed by Google, designed for building single-page applications using HTML, CSS, and TypeScript. Key features include a component-based architecture, TypeScript support, two-way data binding, and dependency injection, among others. The framework has evolved through various versions, introducing significant enhancements such as the Ivy rendering engine and standalone components.

Uploaded by

22b81a05y0.2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

angularr

Angular is an open-source web application framework developed by Google, designed for building single-page applications using HTML, CSS, and TypeScript. Key features include a component-based architecture, TypeScript support, two-way data binding, and dependency injection, among others. The framework has evolved through various versions, introducing significant enhancements such as the Ivy rendering engine and standalone components.

Uploaded by

22b81a05y0.2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

ANGULAR

**

Angular is a popular open-source web application framework developed and maintained by Google.
It is used to build single-page applications (SPAs) using HTML, CSS, and TypeScript.

Key Features of Angular:

1. Component-based architecture – Applications are built using reusable and encapsulated


components.

2. TypeScript support – Angular uses TypeScript, which is a superset of JavaScript that adds
strong typing.

3. Two-way data binding – Automatically synchronizes data between the model and the view.

4. Dependency injection – Improves code maintainability and modularity by injecting services.

5. Routing – Allows navigation between different views or pages in a single-page application.

6. Directives – Special HTML attributes that enhance the behavior of elements.

7. Angular CLI – A command-line tool to create, build, test, and deploy Angular apps easily.

Version Year Importance

AngularJS (1.x) 2010 Original version (JavaScript-based, MVC) – Now obsolete.

Angular 2 2016 Complete rewrite using TypeScript, component-based, decoratos.

Angular 4 2017 Skipped Angular 3, improved performance, *ngIf & *ngFor enhancements.

Angular 9 2020 Ivy rendering engine became the default (faster and smaller apps).

Angular 14 2022 Introduced Standalone Components (can work without NgModule).

Angular 16 2023 Introduced Signals (new reactivity model).

Installing angular:

• npm install -g @angular/cli@latest

ng new <project-name>

Running application: ng serve –open


Main Building Blocks of Angular (Simple Version)

1. Modules

 Angular apps are divided into smaller parts called modules.

 Every app has at least one root module (usually called AppModule).

 Modules help organize the app and group related features together.

 A module is just a class marked with @NgModule.

2. Components

 A component controls a part of the screen (called a view).

 Example: Home page, Course list, Course detail – each can be a separate component.

 Components are classes marked with @Component, and they have:

o HTML (template)
o CSS (style)

o TypeScript (logic)

3. Templates

 A template is the HTML that defines how a component looks on the screen.

 It contains normal HTML plus some Angular code like {{title}} or *ngIf.

4. Decorators

 A decorator is a special function (like @Component, @NgModule) that gives extra info to
Angular about how to use a class.

 It helps Angular know what that class does (like whether it’s a component, module, service,
etc.).

5. Metadata

 Metadata means extra data about a class.

 Angular uses it (through decorators) to understand how to process and use the class.

6. Directives

 Directives are special instructions in templates that change how things appear or behave.

 Example: *ngIf hides/shows things; *ngFor repeats elements.

 Components are also directives, but with a template.

7. Services

 A service is a class that has some useful code or logic (like fetching data).

 Services are used to share data or functions across components.

 They are not directly shown on the screen.

8. Dependency Injection (DI)

 DI means Angular gives the needed services to components automatically.

 You don’t create a service yourself; Angular injects it where needed.

9. Data Binding
 Data Binding is a way to connect your component's data with the HTML view.

 It makes the app dynamic—when data changes in the component, it automatically updates
the screen and vice versa.

Component:

What is a Component in Angular?

A Component is one of the core building blocks of an Angular application.


It controls a part of the web page (called a view) and defines what should appear, how it should
behave, and how it should look.

A Component Has 3 Main Parts:

1. Template (HTML)

o This is the UI part of the component (what you see on the screen).

o Written in HTML and may include Angular features like {{ }} for displaying data or
*ngIf, *ngFor, etc.

2. Class (TypeScript code)

o This is the logic of the component.

o It holds data (as variables) and defines behavior (as methods).

o Example: If you're building a to-do list, the logic for adding or removing items will be
here.

3. Style (CSS)

o This part handles the look and feel of the component – colors, fonts, layout, etc.

Structure of a Component:

// app.component.ts

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

@Component({

selector: 'app-root', // tag used in HTML to use this component

templateUrl: './app.component.html', // HTML file

styleUrls: ['./app.component.css'] // CSS file

})

export class AppComponent {


title = 'My First Angular App'; // data used in the HTML

//app.component.html

<h1>{{ title }}</h1> <!-- displays data from the component class -->

//app.component.css

h1 {

color: darkblue;

Key Points:

 @Component decorator tells Angular that this class is a component.

 The selector is the custom HTML tag used to insert this component into another template
(like <app-root></app-root>).

 The class handles data and functions.

 Components can use other components inside them (like a parent-child relationship).

MODULE:

A Module in Angular is a container that groups related parts of the app together — such as
components, directives, pipes, and services.

It helps keep your app organized and maintainable, especially when your app grows big.

Every Angular App Must Have at Least One Module

That is called the Root Module, usually named AppModule.

// app.module.ts

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

import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';


@NgModule({

declarations: [ AppComponent ], // components that belong to this module

imports: [ BrowserModule ], // other modules used here

providers: [], // services

bootstrap: [ AppComponent ] // starting point of the app

})

export class AppModule { }

In the @NgModule decorator:

1. declarations:

o List of components, directives, and pipes that belong to this module.

2. imports:

o Other modules you want to use in this module.

o Example: BrowserModule, FormsModule, etc.

3. providers:

o Services that should be available in this module.

4. bootstrap:

o The root component that Angular should start the app with (usually AppComponent).

Why Use Modules?

 Helps split the app into smaller, manageable parts.

 Allows lazy loading: load parts of the app only when needed.

 Helps with code reuse: create feature modules and import them where required.

Type Description

Root Module Main entry point of the app (AppModule)

Feature Modules For specific features (e.g., UserModule, AdminModule)

Shared Module Contains common code (components/pipes used in many places)

Core Module Contains singleton services (like authentication, API services)

Directives:
Directive is a special instruction that you can add to HTML to change the behavior or appearance of
elements.

Types of Directives

Angular has 3 main types of directives:

1. Component Directive (most common)

 A Component is actually a special type of directive with a template (HTML + logic).

 It uses the @Component decorator.

Eg:

@Component({

selector: 'app-header',

templateUrl: './header.component.html'

})

2. Structural Directives

 These change the layout or structure of the DOM.

 They usually start with a * (asterisk).


Common ones:

 *ngIf – adds or removes elements based on a condition.

 *ngFor – loops over a list to generate elements.

 *ngSwitch – switch-case like structure.

Eg:

<p *ngIf="isLoggedIn">Welcome back!</p>

<ul>

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

</ul>

3. Attribute Directives

 These change the appearance or behavior of an existing element.

 They look like regular HTML attributes.

Common ones:

 ngClass – dynamically add/remove CSS classes.

 ngStyle – dynamically change styles.


Eg;

<p [ngStyle]="{ color: isError ? 'red' : 'green' }">Status message</p>

<button [ngClass]="{ 'active': isActive }">Click Me</button>

Data Binding:
Data Binding in Angular is a technique to connect your component (TypeScript logic) and your
template (HTML view) so they can communicate and stay in sync.

It helps you:

 Show dynamic data on the screen.

 Update data based on user input or events.

There are 5 main types:

1. Interpolation ({{ }})

To display dynamic data from the component to the view (HTML).

Eg: <h1>Hello, {{ userName }}</h1>

Angular replaces {{ userName }} with the value of the userName property from the component at
runtime.

Can also use expressions:


{{ 10 + 5 }} → 15

{{ user.age >= 18 }} → true or false

{{ user.name.toUpperCase() }} → uppercase name

2. Property Binding ([property])

To bind values from the component to HTML element properties

<img [src]="user.imageUrl">

<input [value]="user.name">

3. Class Binding

To dynamically apply or remove CSS classes based on conditions in the component.

<div [ngClass]="{ 'valid': isValid, 'invalid': !isValid }"></div>

Instead of {} we can also use [] and nothing(works for only 1 class)

4. Event Binding ((event))

To listen to user events (clicks, inputs, etc.) and call functions in your component.
<button (click)="onClick()">Click Me</button>

<input (input)="onInputChange($event)">

onClick() {

console.log("Button was clicked");

onInputChange(event: any) {

console.log("Input changed to:", event.target.value);

Common events:

 click, mouseover, keydown, submit, input, etc.

5. Two-Way Data Binding ([(ngModel)])

To bind input values both ways — from component to view AND from view to component.

You must import FormsModule in the module:

import { FormsModule } from '@angular/forms';

<input [(ngModel)]="userName">

<p>Your name is: {{ userName }}</p>

It's a shortcut for combining property binding + event binding:

Angular Services

Angular Services are reusable pieces of code or logic that perform specific tasks. They are designed
to share data, logic, or functionality across multiple components in an Angular application.

Why use Services?


 Avoid Code Duplication: Instead of repeating logic in every component, put it in a service.

 Share Data: Services can hold data that multiple components can access or update.

 Separation of Concerns: Components handle view logic; services handle business logic or
data logic.

 Easier Testing: Services are easier to test in isolation than components.

Common Use Cases

 Fetching data from an API (HttpClient)

 Business logic (e.g., calculations, filtering)

 Sharing values between components (e.g., a shopping cart)

 Authentication & authorization

Step 1: Create a Service

ng generate service data

This creates data.service.ts.

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

@Injectable({

providedIn: 'root' // makes it globally available

})

export class DataService {

private message = "Hello from Service!";

getMessage() {

return this.message;

setMessage(newMsg: string) {

this.message = newMsg;
}

Step 2: Use it in a Component

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

import { DataService } from './data.service';

@Component({

selector: 'app-my',

template: `<p>{{ msg }}</p>`,

})

export class MyComponent implements OnInit {

msg: string = '';

constructor(private dataService: DataService) {} //Dependency Injection

ngOnInit() {

this.msg = this.dataService.getMessage();

**

CREATING API AND CONSUMING IT:

First Write a simple api using express in backend (‘/api/greeting’)

In frontend:

Angular uses the HttpClient module to call APIs.


**

STEPS:

1.Import HttpClientModule in app.module.ts

import { HttpClientModule } from '@angular/common/http';

@NgModule({

imports: [

HttpClientModule

})

export class AppModule {}

2. Create a Service to handle API

//api.service.ts

ng generate service api

import { HttpClient } from '@angular/common/http';

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

@Injectable({

providedIn: 'root'

})

export class ApiService {

constructor(private http: HttpClient) {}

getGreeting() {

return this.http.get<any>('http://localhost:3000/api/greeting');

}
3.Use it in a component:

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

import { ApiService } from './api.service';

@Component({

selector: 'app-home',

template: `<p>{{ message }}</p>`,

})

export class HomeComponent implements OnInit {

message: string = '';

constructor(private apiService: ApiService) {}

ngOnInit() {

this.apiService.getGreeting().subscribe(data => {

this.message = data.message;

});

Dependency Injection (DI) in Angular

Dependency Injection is a design pattern where Angular automatically provides objects (like services)
to components or other services.

Why use it?

 Makes components cleaner and easier to test.

 Reduces the need to manually create instances of classes.

 Promotes loose coupling (one part doesn't tightly depend on another).

Example of DI
constructor(private apiService: ApiService) {}

Here, Angular injects an instance of ApiService when the component is created. You don't need to
use new ApiService() — Angular handles it.

**

ROUTING:

Routing in Angular means navigating between different views or pages of your application without
reloading the whole page.

Instead of loading new HTML files, Angular just displays the component associated with a particular
route — this is called a Single Page Application (SPA) behavior.

Why is Routing Important?

 Allows navigation between pages (like Home, About, Contact)

 Keeps your app fast (no full page reloads)

 Supports browser navigation (Back, Forward buttons)

 Enables deep linking (sharing specific pages)

How Angular Routing Works

1. Define routes (path + component mapping)

2. Use <router-outlet> to display routed components

3. Navigate using <a [routerLink]> or programmatically

Step-by-Step Example:

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

const routes: Routes = [


{ path: '', component: HomeComponent },

{ path: 'about', component: AboutComponent }

];

@NgModule({

imports: [RouterModule.forRoot(routes)],

exports: [RouterModule]

})

export class AppModule {}

Add <router-outlet> in app.component.html:

<nav>

<a routerLink="">Home</a>

<a routerLink="about">About</a>

</nav>

<router-outlet></router-outlet>

Create Components

ng generate component Home

ng generate component About

Using HttpClient, Observables:

Angular provides HttpClient to send HTTP requests to external APIs or servers.

//MODULE

import { HttpClientModule } from '@angular/common/http';


@NgModule({

imports: [ HttpClientModule ]

})

export class AppModule {}

//SERVICE

import { HttpClient } from '@angular/common/http';

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

@Injectable({ providedIn: 'root' })

export class ApiService {

constructor(private http: HttpClient) {}

getData() {

return this.http.get<any>('https://api.example.com/data');

Observables – To handle async data

Angular’s HttpClient returns Observables. Observables let you subscribe to data that might arrive
later (like a response from an API).

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

import { ApiService } from './api.service';

@Component({

selector: 'app-home',

template: `<p>{{ data | json }}</p>`

})
export class HomeComponent implements OnInit {

data: any;

constructor(private api: ApiService) {}

ngOnInit() {

this.api.getData().subscribe(response => {

this.data = response;

});

The .subscribe() method is what actually executes the HTTP request and allows you to use the
result.

Pipes:

Pipes format your data in the HTML. Examples:

 date – formats a date

 uppercase, lowercase – changes case

 currency – shows currency symbols

 json – shows object as JSON string

Example:

<p>Upper: {{ name | uppercase }}</p>

<p>Formatted Date: {{ today | date:'shortDate' }}</p>

<p>Currency: {{ price | currency:'INR' }}</p>

<p>JSON: {{ data | json }}</p>

FORMS:
Angular Forms are used to collect and manage user input in your application, like filling out a login
or registration form.

Angular provides two main approaches to build forms:

1. Template-Driven Forms:

 Easy to use
 Logic mostly in the HTML
 Ideal for simple forms

Example:

<form #userForm="ngForm" (ngSubmit)="submitForm(userForm)">

<input name="username" ngModel required>

<input name="email" ngModel email>

<button type="submit">Submit</button>

</form>

submitForm(form: NgForm) {

console.log(form.value);

2.Reactive Forms

 More powerful & scalable

 All logic in the TypeScript file

 Better for complex/large forms

//Module

import { ReactiveFormsModule } from '@angular/forms';

//Component
import { FormGroup, FormControl } from '@angular/forms';

form = new FormGroup({

username: new FormControl(''),

email: new FormControl('')

});

submit() {

console.log(this.form.value);

//html

<form [formGroup]="form" (ngSubmit)="submit()">

<input formControlName="username">

<input formControlName="email">

<button type="submit">Submit</button>

</form>

**

You might also like