0% found this document useful (0 votes)
14 views9 pages

Angular Syllabus

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)
14 views9 pages

Angular Syllabus

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/ 9

1.

Angular Basics

• Components: Core building blocks with HTML templates, styles, and logic.
o Metadata and Decorators: @Component decorator attaches metadata (selector, templateUrl,
styleUrls).
o Component Lifecycle: Angular creates, updates, and destroys components based on
navigation and user interactions.
o Real-World Example: A UserCardComponent showing user details. It binds user data passed via
@Input and emits events using @Output.
• Modules: Containers for organizing components, services, and pipes.
o NgModules and Root Module: Every Angular app has a root module (usually AppModule) that
bootstraps the application.
o Lazy-loaded Modules: Modules loaded only when accessed. Use loadChildren in routing for
lazy loading.
o Example: Split an app into AdminModule, UserModule, and ProductModule for better code
organization and lazy load as needed.
• Data Binding:

o Interpolation: Display data in the view.


o Property Binding: Bind properties to elements.
o Event Binding: Listen to DOM events.

o Two-Way Binding: Sync data between model and view


o One-way and Two-way Binding: Use [(ngModel)] for two-way binding, {{variable}} for
interpolation.
o Example: A login form with two-way binding on input fields for username and password.

2. Directives

• Structural Directives: Modify the DOM structure (*ngIf, *ngFor, *ngSwitch)


o ngIf: Conditionally add/remove elements. Efficient because it detaches components from
the DOM when conditions are unmet.
o ngFor and TrackBy: ngFor iterates arrays, while trackBy optimizes performance by tracking list
elements.
o Example: *ngFor displays a list of tasks, and trackBy optimizes it for large data by identifying
list items uniquely.
• Attribute Directives: Modify behavior/appearance of elements (ngClass, ngStyle)
o ngClass/ngStyle: Dynamically apply styles/classes based on component data.
o Example: Use ngStyle to change a progress bar's color based on progress level.
• Custom Directives: Create reusable custom behavior
o Example: A ClickOutsideDirective to close dropdowns when clicking outside of a specified area.
3. Dependency Injection (DI)

Service: Used for sharing data and functions across components.


Injectors and Providers: Mechanism of DI in Angular.

• Services and Dependency Injection Hierarchy:


o Service Providers: @Injectable decorator enables DI, with providedIn: 'root' making it a singleton.
o Hierarchical Injection: Services can be provided at different levels, creating unique instances at
each level.
o Example: Use AuthService for managing login and logout, and provide it globally to maintain a
single user session.

4. Services and HTTP Client

An Observable is a data structure that allows you to work with asynchronous data streams. It can emit
mulOple values over Ome, making it useful for handling events and data that come in asynchronously.

• HTTP Client and Observables: for CreaNng and Using Services: Centralize business logic and share
data
o HTTP Methods: GET, POST, PUT, DELETE, with optional headers and params for API
customization.
o Error Handling: Use .pipe() with catchError to manage API errors gracefully.
o Example: In an e-commerce app, use ProductService with HttpClient to fetch product data from
an API and handle errors (e.g., network issues) using catchError.
• HTTP Interceptors: An interceptor is a service that implements the HTpInterceptor interface provided
by Angular's @angular/common/hTp package. Interceptors can inspect, modify, or handle requests and
responses globally for all HTTP calls made by the applicaOon.
o Authentication Token Interceptor: Attach JWT tokens to requests for secure APIs.
o Error Handling Interceptor: Centralize error responses, such as redirecting to login on 401
Unauthorized.
o Example: An interceptor that adds an auth token for every request if the user is logged in.

5. Routing and Navigation

Setting Up Routes: Define routes for components.


Lazy Loading: Load modules only when needed.
Route Guards: Protect routes (e.g., AuthGuard).

• RouterModule and Route Configuration:


o Route Parameters and Query Params: Pass parameters via URL for dynamic routing.
o Lazy Loading with Route Modules: Load feature modules only on navigation to optimize
load times.
o Example: A blog app with PostModule that loads when accessing /posts, and each post loads
by ID as a route parameter (/posts/:id).
• Guards:
o Types of Guards: CanActivate, CanDeactivate, Resolve, and CanLoad.
o Example: An AuthGuard to prevent unauthenticated users from accessing sensitive routes
(e.g., /dashboard).

6. Forms in Angular

• Template-Driven Forms:
o Simplicity and Use Case: Best for simple forms. Use ngModel for data binding.
o Form Validation: Validators like required, minLength, and custom validators.
o Example: A newsletter signup form where user input binds directly to a model.
• Reactive Forms:
o Form Control and Validation: Powerful with FormControl, FormGroup, and FormArray.
o Dynamic Forms: Add/remove controls dynamically.
o Example: A checkout form where users can dynamically add multiple shipping addresses
using FormArray.

7. Pipes

o Built-in Pipes: Transform data (e.g., uppercase, date, currency).


o Creating Custom Pipes: Create reusable data transformaOons

o Pure vs Impure Pipes: Pure pipes optimize performance by recalculating only when input
changes.
o Example: A currencyConvertPipe to convert currency based on user-selected currency.

8. Lifecycle Hooks

Component Lifecycle Hooks: Execute code at specific moments (ngOnInit, ngOnDestroy).

1. ngOnChanges: Called whenever data-bound input properties change. Receives a SimpleChanges object
with the previous and current values.
2. ngOnInit: Called once after the first ngOnChanges. Typically used to initialize component data.
3. ngDoCheck: Called during every change detection run. Allows custom change detection.
4. ngAfterContentInit: Called once after Angular projects external content into the component’s view
(e.g., content projected with <ng-content>).
5. ngAfterContentChecked: Called after every check of the projected content.
6. ngAfterViewInit: Called once after the component's view and child views have been initialized.
7. ngAfterViewChecked: Called after every check of the component's view and child views.
8. ngOnDestroy: Called just before Angular destroys the component. Used for cleanup (e.g.,
unsubscribing from Observables, detaching event handlers).

Typical Lifecycle Hook Sequence

The typical order of execution is:

1. ngOnChanges
2. ngOnInit
3. ngDoCheck
4. ngAfterContentInit
5. ngAfterContentChecked
6. ngAfterViewInit
7. ngAfterViewChecked

• ngOnChanges and ngAfterViewInit:


o ngOnChanges: Called when data-bound properties change.
o ngAfterViewInit: Useful for manipulating child components after the view initializes.
o Example: Use ngOnChanges to detect when a user profile changes, updating the component
data accordingly.

9. Change Detection Strategy

• ChangeDetectionStrategy.OnPush:
o OnPush Strategy: Optimizes performance by limiting checks to cases where input properties
change.
o Example: In a news feed, OnPush is used to update only when new articles are received
instead of rechecking every item.

10. Observables and RxJS

• Subjects:
o BehaviorSubject: Emits last value to new subscribers, often used for state sharing.
o ReplaySubject: Caches a specified number of last emissions, allowing late subscribers to get
recent values.
o Example: Use BehaviorSubject to manage user session data across multiple components.
• Operators:
o Combination Operators: combineLatest, merge, concat, zip to combine streams.
o Error Handling and Retry: catchError, retry, retryWhen for handling and retrying failed requests.
o Example: Use switchMap in a search feature to cancel previous requests and only process the
latest input.
11. Angular Modules (Advanced)

• Feature and Shared Modules:


o Shared Modules: Consolidate common components, directives, pipes.
o Lazy Loading Best Practices: Only import feature modules needed for specific routes to
enhance performance.
o Example: A SharedModule with utility pipes and commonly used components, imported only
in feature modules.

12. Advanced Component Communication

• EventEmitter and Output Decorators:


o @Output EventEmitter: Child components emit data to parent components.
o Example: A ProductCardComponent emits a remove event to the parent component when a
product is removed.
• Service-based Communication:
o Example: Use a CartService to share cart items between ProductListComponent and CartComponent
in an e-commerce app.

13. State Management with NgRx

• Store Module: Manages the global state using reducers and selectors.
• Actions, Reducers, and Selectors:
o Actions: Define state transitions.
o Reducers: Pure functions to handle actions and update the state.
o Selectors: Retrieve slices of the state tree.
o Example: Use NgRx to handle a shopping cart, with actions for adding/removing items and
selectors for calculating totals.
• Effects:
o Side Effects: Manage async operations outside the component, like API calls, using effects.
o Example: An effect that listens for LOGIN actions, triggers an API call, and dispatches
LOGIN_SUCCESS or LOGIN_FAILURE.

14. Angular Universal (SSR)

• Server-Side Rendering (SSR):


o Setup with Angular Universal: Prerender critical parts for better SEO and faster initial load.
o Example: Pre-render a ProductPage to enhance SEO and improve load times for search
engines.
15. Progressive Web Apps (PWA)

• Service Workers:
o Cache Strategies: NetworkFirst, CacheFirst, StaleWhileRevalidate.
o Example: In a news app, use CacheFirst for static assets, while NetworkFirst is used for fresh
content.

16. Testing in Angular

• Unit Tests:
o Mocking and Stubs: Mock services and components to test in isolation.
o Example: Test a LoginComponent by mocking AuthService.
• End-to-End Testing:
o Protractor: Automates testing flows, like login or checkout.
o Example: E2E test simulates a user logging in, searching products, and adding an item to the
cart.

17. Angular CLI and Best Practices

• CLI and Schematics:


o CLI Commands: ng generate, ng build, ng test for consistent app scaffolding.
o Linting and Formatting: Use ESLint and Prettier to maintain code quality.
o Example: Use ng generate component to standardize the creation of new components, ensuring
consistency across the app.

• angular.json: Configures Angular CLI settings for building, serving, and structuring the Angular app.
• package.json: Manages dependencies and scripts for the project and provides basic project
information.

OpNmizaNon methods in Angular:

1. Disable production mode: Run in development mode (e.g., ng serve without --prod), which skips certain
optimizations to make debugging easier.
2. Modify Build Optimizations in angular.json:
o Set optimization to false in the angular.json file:

json
Copy code
"configurations": {
"production": {
"optimization": false
}
}

o This turns off tree-shaking, minification, and bundling optimizations.


3. Disable aot (Ahead-of-Time) Compilation:
o Set "aot": false in angular.json or use ng build --aot=false.
o This skips the pre-compilation of templates and reduces build time but increases runtime
work.
4. Turn Off Source Maps:
o Set "sourceMap": true in development configurations but false for production.
o Source maps are useful for debugging but increase the bundle size.
5. Disable Lazy Loading:
o Avoid lazy loading to simplify module loading and reduce the complexity of application state
for debugging.
o For example, instead of lazy-loading modules in the AppRoutingModule, import them directly.
6. Disable Ivy Rendering:
o If using Angular 9+, you can opt-out of Ivy ("enableIvy": false in tsconfig.json) for a less optimized,
legacy view engine.
7. Set Build Mode to Development:
o In angular.json, under build.options, set optimization to false, aot to false, and buildOptimizer to false.

Each of these methods lowers the optimization level in Angular to simplify debugging but should typically
be used only in development.

Purpose of Ports in Angular

In Angular, ports are used to define the local address where the development server runs, allowing you to
test and develop the applicaOon in a local environment.
• Development Environment: Running the Angular app locally on a specified port allows for isolated
testing and development.
• Concurrent Instances: Setting different ports enables running multiple instances of Angular apps on
the same machine for simultaneous development/testing.
• Network Access: Specifying ports can make the app accessible within a local network for
collaborative testing or showcasing.

How to Set Ports in Angular

1. Using the Angular CLI Command:


o You can specify the port directly in the command line:

bash
Copy code
ng serve --port 4201

oThis starts the Angular development server on http://localhost:4201.


2. Updating the angular.json File:
o Set the default port in the angular.json configuration file.
o Locate the projects > your-app > architect > serve > options section and add a port field:

json
Copy code
"serve": {
"options": {
"port": 4201
}
}

oThis will set 4201 as the default port whenever ng serve is run.
3. Running on a Random Free Port:
o If you want Angular to use any free port available, specify --port 0:

bash
Copy code
ng serve --port 0

4. Specifying Ports in Proxy Configurations:


o For apps that require a backend server, ports can be configured in a proxy.conf.json file to
forward requests to the backend server:

json
Copy code
{
"/api": {
"target": "http://localhost:3000",
"secure": false
}
}
o Then, run with the proxy config:

bash
Copy code
ng serve --proxy-config proxy.conf.json

Setting the port is helpful for organizing multiple projects, sharing access for development, or testing
various app versions side-by-side.

You might also like