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

Angular

The document provides a comprehensive overview of Angular, a TypeScript-based framework for building Single Page Applications (SPAs). It covers key concepts such as component architecture, data binding, directives, services, and routing, along with examples for practical implementation. The document serves as a guide for setting up Angular projects, writing applications, and utilizing Angular's features for modern web development.

Uploaded by

RAVI TEJA C
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Angular

The document provides a comprehensive overview of Angular, a TypeScript-based framework for building Single Page Applications (SPAs). It covers key concepts such as component architecture, data binding, directives, services, and routing, along with examples for practical implementation. The document serves as a guide for setting up Angular projects, writing applications, and utilizing Angular's features for modern web development.

Uploaded by

RAVI TEJA C
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Angular

1. Introduction to SPA (Single Page Applications)


SPA is a web application that loads a single HTML page.
Only necessary content updates dynamically, improving speed.
Uses JavaScript frameworks like Angular, React, Vue.
Improves user experience (UX) by avoiding full page reloads.
Data is fetched via AJAX or Fetch API without reloading.
Uses client-side routing to change views without reloading.
Reduces server load since fewer requests are made.
Example SPAs: Gmail, Facebook, Trello, Netflix.
Implemented using Angular’s Router Module.
Ideal for modern web applications with high interactivity.

Example:

<nav>
<a routerLink="/home">Home</a>
<a routerLink="/about">About</a>
</nav>
<router-outlet></router-outlet>

2. Introduction to Angular
Angular is a TypeScript-based front-end framework.
Developed by Google for building SPAs.
Uses component-based architecture.
Features two-way data binding, dependency injection, and directives.
Supports modular development with reusable components.
Provides built-in HTTP Client for API integration.
Uses RxJS (Reactive Extensions) for handling asynchronous data.
Supports server-side rendering (SSR) via Angular Universal.
Works with Material Design for a modern UI.
Used by Google, PayPal, Upwork, and many enterprise apps.

Example:

export class AppComponent {


title = 'My Angular App';
}

3. Setup Angular Project


Install Node.js and npm before setting up Angular.
Use Angular CLI ( npm install -g @angular/cli ) for easy setup.
Create a project: ng new my-app and navigate to it.
Run ng serve to start the development server.
The src/app folder contains components, modules, and assets.
angular.json manages project configurations.
Supports hot module replacement (HMR) for real-time updates.
Use ng generate component component-name to create components.
Development server runs at http://localhost:4200 by default.
Uses TypeScript instead of JavaScript for better maintainability.

Example:

ng new my-angular-app
cd my-angular-app
ng serve

4. Writing First Angular App


Angular apps are built using components.
app.component.ts is the main component of an Angular app.
Uses HTML templates ( .html ) to render UI.
TypeScript ( .ts ) handles logic and data.
styles.css defines global styles for the app.
Components use @Component decorator for metadata.
ng serve runs the app locally at localhost:4200.
Modules (NgModules) group components together.
Uses {{ }} for interpolation to display variables.
Two-way binding syncs UI with data dynamically.

Example:

@Component({
selector: 'app-root',
template: `<h1>Welcome to Angular!</h1>`
})
export class AppComponent {}

5. How to Create an Angular Component?


Components are the building blocks of Angular apps.
Each component has a TypeScript file, HTML file, and CSS file.
Use ng generate component my-component to create one.
The component must be registered in app.module.ts .
Defined using @Component decorator with metadata.
selector defines how to use it in HTML.
templateUrl links to the component's HTML.
styleUrls points to stylesheets for that component.
Each component has its own lifecycle methods.
Components communicate using @Input and @Output decorators.

Example:

@Component({
selector: 'app-hello',
template: `<h2>Hello, Angular!</h2>`,
styles: [`h2 { color: blue; }`]
})
export class HelloComponent {}
6. Interpolation & Property Data Binding
Interpolation ( {{}} ) binds component variables to the view.
Example: {{ title }} renders the title variable dynamically.
Property Binding ( [property]="value" ) binds properties to DOM elements.
Example: <img [src]="imageUrl"> sets the image dynamically.
Property binding allows dynamic styling and content changes.
Ensures data flows from the component to the view (One-way binding).
Helps avoid manual DOM manipulation (like document.getElementById ).
Improves code readability and maintainability.
Can bind CSS styles, input values, and more.
Prevents XSS security vulnerabilities compared to innerHTML.

Example:

<h1>{{ title }}</h1>


<input [value]="name">

7. Event Binding and References


Event binding listens to user interactions (clicks, keypress, etc.).
Uses () syntax: (event)="function()" .
Example: <button (click)="sayHello()">Click Me</button> .
References ( #ref ) allow access to elements directly.
Example: <input #myInput> <button
(click)="logValue(myInput.value)">Log</button> .
Works with keyboard events, mouse events, etc..
Helps in form validation, navigation, and API calls.
Can pass parameters to event handler methods.
Reduces manual DOM manipulation for handling events.
Used extensively in buttons, forms, and UI interactions.

Example:

<button (click)="showMessage()">Click Me</button>


showMessage() {
alert("Hello, Angular!");
}

8. Class and Style Bindings


Class Binding dynamically applies CSS classes.
Uses [class.className]="condition" syntax.
Example: <div [class.active]="isActive">Hello</div> .
Style Binding dynamically applies inline styles.
Uses [style.property]="value" syntax.
Example: <p [style.color]="textColor">Dynamic Color</p> .
Helps in conditional styling based on state.
Works with functions and variables in TypeScript.
Enhances user experience and visual feedback.
Can combine multiple CSS classes dynamically.

Example:

<p [class.red]="isError">Error Message</p>


<p [style.color]="textColor">Dynamic Color</p>

isError = true;
textColor = 'blue';

9. Directives
Directives are special attributes that modify the behavior of elements.
Angular has three types:
Structural Directives ( *ngIf , *ngFor ) change DOM structure.
Attribute Directives ( ngClass , ngStyle ) modify appearance.
Custom Directives extend Angular functionality.
*ngIf hides/shows elements dynamically.
*ngFor loops through lists in the template.
ngClass adds/removes CSS classes dynamically.
ngStyle applies inline styles dynamically.
Custom directives use the @Directive decorator.
Helps in building dynamic and interactive UIs.

Example:

<p *ngIf="showText">This is conditionally visible.</p>


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

10. Inter-Component Data Transfer


Components communicate via Input & Output decorators.
Parent to Child: Use @Input() to pass data.
Child to Parent: Use @Output() with EventEmitter .
Helps maintain a modular and reusable component structure.
@Input() binds properties inside child components.
@Output() emits events for parent components to handle.
Useful in nested components and dynamic UI updates.
Avoids direct manipulation of DOM, following Angular principles.
Can also use services and shared states for complex data sharing.
Essential for building large-scale applications.

Example:
Parent Component ( app.component.html )

<app-child [message]="parentMessage" (childEvent)="receiveMessage($event)">


</app-child>

Child Component ( child.component.ts )

@Input() message: string;


@Output() childEvent = new EventEmitter<string>();
11. Pipes
Pipes transform data before displaying it in templates.
Built-in pipes include uppercase , lowercase , date , currency , etc.
Use | operator to apply pipes.
Example: {{ message | uppercase }} → Converts text to uppercase.
Can be chained: {{ amount | currency:'USD' }} .
Custom pipes use @Pipe decorator.
Pipes are pure by default, meaning they don’t change inputs.
Can be impure if they depend on external state changes.
Used for formatting numbers, dates, and complex data.
Great for improving readability and UI consistency.

Example:

<p>{{ today | date:'fullDate' }}</p>


<p>{{ price | currency:'USD' }}</p>

12. Form Validation (Template-Driven & Reactive


Forms)
Angular provides two ways to handle forms:
Template-Driven Forms (Simple, uses ngModel ).
Reactive Forms (More structured, uses FormGroup , FormControl ).
Forms handle user input validation, submission, and state tracking.
Uses required , minlength , pattern , etc. for validation.
Reactive Forms use FormBuilder for dynamic form creation.
Helps in login pages, registration forms, and data entry UIs.
Supports error handling and live feedback.
Uses Validators to define validation rules.
Helps prevent bad data input and enhances user experience.
Essential for enterprise applications with complex form logic.

Example (Template-Driven Form):

<form #myForm="ngForm">
<input type="text" name="username" ngModel required>
<button [disabled]="!myForm.valid">Submit</button>
</form>

13. Angular Services


Services share logic across multiple components.
Used for fetching data, authentication, and business logic.
Created using ng generate service service-name .
Uses @Injectable() to make it injectable in components.
Registered inside providers array in app.module.ts .
Works with HTTP requests to communicate with APIs.
Helps in state management and global data access.
Supports dependency injection for better scalability.
Reduces code duplication by centralizing logic.
Essential for large applications with multiple features.

Example:

@Injectable({ providedIn: 'root' })


export class DataService {
getData() {
return ["Angular", "React", "Vue"];
}
}

14. Observables
Observables handle asynchronous operations in Angular.
Used for HTTP calls, user events, and real-time data streams.
Part of RxJS (Reactive Extensions for JavaScript).
Works with subscribe() to listen for updates.
Helps in handling multiple async events smoothly.
Can be combined and manipulated using RxJS operators.
Better than Promises for handling multiple values over time.
Uses map() , filter() , debounceTime() , etc., for data transformation.
Improves performance and scalability of applications.
Works well with Angular’s HTTP Client for API calls.

Example:

this.http.get('https://api.example.com/data').subscribe(data => {
console.log(data);
});

15. Routes (Routing in Angular)


Angular uses client-side routing for SPAs.
Defined in app-routing.module.ts .
Uses RouterModule.forRoot(routes) to configure paths.
routerLink directive navigates without page reload.
router-outlet renders different components dynamically.
Supports lazy loading for performance optimization.
Uses route guards to protect pages from unauthorized access.
Works with dynamic parameters ( :id ) for dynamic pages.
Enhances navigation and user experience.
Essential for multi-page applications.

Example:
Routing Configuration ( app-routing.module.ts )

const routes: Routes = [


{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent }
];

Navigation in HTML ( app.component.html )

<a routerLink="/home">Home</a>
<a routerLink="/about">About</a>
<router-outlet></router-outlet>

You might also like