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

Unit - 05 Mean Stack

The document provides an overview of AngularJS, detailing its history, features, and benefits as a front-end web application framework. It covers key concepts such as modules, components, templates, change detection, and forms, along with practical instructions for setting up an Angular project using Angular CLI. Additionally, it discusses advanced topics like dependency injection, services, and observables, emphasizing Angular's capabilities for building scalable and maintainable applications.

Uploaded by

shanuthanoj
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Unit - 05 Mean Stack

The document provides an overview of AngularJS, detailing its history, features, and benefits as a front-end web application framework. It covers key concepts such as modules, components, templates, change detection, and forms, along with practical instructions for setting up an Angular project using Angular CLI. Additionally, it discusses advanced topics like dependency injection, services, and observables, emphasizing Angular's capabilities for building scalable and maintainable applications.

Uploaded by

shanuthanoj
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 28

POTTI SRIRAMULU CHALAVADI

MALLIKARJUNA RAO COLLEGE OF


ENGINEERING & TECHNOLOGU
MEAN STACK UNIT - 05
ANGULAR JS
BY
MD. BUSHRA
ASSISTANT PROFESSOR
DEPARATEMENT OF CSE DATA
SCIENCE
Angular JS
History of Angular JS
• AngularJS version 1.0 was released in 2012.
• Miško Hevery, a Google employee, started to work with AngularJS in 2009.
• The idea turned out very well, and the project is now officially supported by Google.

What is Angular JS

• Angular is an open-source front-end web application framework that is


used for building single-page and complex web applications. By default,
angular uses TypeScript for creating logic but as the browser doesn’t know
typescript it converts typescript into javascript in order to make typescript
understandable.
• Other frameworks deal with HTML’s shortcomings by either abstracting
away HTML, CSS, and/or JavaScript or by providing an imperative way for
manipulating the DOM. Neither of these address the root problem that
Features of Angular JS
• Model-view-controller (MVC) architecture: Divides an application into three parts:
model, view, and controller
• Two-way data binding: Automatically updates the view when the model changes, and
vice versa
• Routing: Creates single-page applications with multiple views, each with a different URL
• Dependency injection: Makes it easier to develop, understand, and test applications
• Filters: Transforms data before displaying it in templates
• Services: Reusable components that provide specific functionality
• Directives: Build reusable components and isolate scope
• Testing: Unit tests can be written using Jasmine and Karma, and end-to-end testing can
be done with Protractor
Benefits
• Improved server performance
• Code reusability
• Long-term support from Google
• Quick application prototyping
• Real-time testing
• Large community support
• Plug-and-play feature
ANGULAR APPLICATION
You can use the Angular CLI to create projects, generate application and library code, and perform a variety of
SETUP
ongoing development tasks such as testing, bundling, and deployment.
To install the Angular CLI, open a terminal window and run the following command:
npm install -g @angular/cli@17
To create a new workspace and initial starter app:
1.Run the CLI command ng new and provide the name my-app, as shown here:
ng new my-app
2. The ng new command prompts you for information about features to include in the initial app. Accept
the defaults by pressing the Enter or Return key.
The Angular CLI installs the necessary Angular npm packages and other dependencies. This can take a few
minutes.
The CLI creates a new workspace and a simple Welcome app, ready to run.
Run Application
The Angular CLI includes a server, for you to build and serve your app locally.
1.Navigate to the workspace folder, such as my-app.
2.Run the following command:
content_copycd my-app
ng serve --open
The --open (or just -o) option automatically opens your browser to http://localhost:4200/.
MODULES AND COMPONENTS
The AngularJS module defines the functionality of the application which is applied on the entire HTML page. It
helps to link many components. So it is just a group of related components. It is a container that consists of
different parts like controllers, services, and directives.
Note: These modules should be made in normal HTML files like index.html and no need to create a new project in
VisualStudio for this section.
Creating a Module in AngularJS:
var app = angular.module("Module-name", []);
In this [], we can add a list of components needed
but we are not including any components in this case.
This created module is bound with any tag like
div, body, etc by adding it to the list of modules.
<div ng-app = "module-name">
The code in which the module is required.
</div>
Adding a Controller:
app.controller("Controller-name", function($scope) {
$scope.variable-name= "";
});
ELEMENTS OF TEMPLATE
Templates in AngularJS are simply HTML files filled or enriched with AngularJS stuff like attributes and directives. A
directive is a marker element that is used to target a particular attribute or class to render its behavior according
to the needs. Model and controller in Angular are combined with the templates to manipulate the view the user
sees in his/her browser. Angular templates can also accommodate CSS, Form controls, Filters, and Expressions.
There are two types of templates:
• Static Template
• Dynamic Templates
Below are examples illustrating both templates.
Static Template: A static template is defined by using a script tag. An id and type attribute with value text/ng-
template must be provided to it for the static template to work. Also, it should be noted that a static template will
work only if it is under the ng-app scope, otherwise, it will be ignored by Angular. A static template can be
rendered by using the
ng-include directive.
For example:
<div ng-include="'index.html'"></div>
Dynamic Templates: Just like the name suggests, the dynamic templates are used to work with the runtime
environments. It is compiled and rendered by Angular on user demand. A dynamic template can be rendered
by using the ng-include directive.
For example:
<div ng-include="'templates/geeksforgeeks.html'"></div>
CHANGE DETECTION
Change detection in Angular is the process of checking if the application's state has changed and updating the
view if needed. It's a core feature of Angular that keeps views in sync with models.
How it works
• Angular runs change detection periodically.
• It can be triggered manually or by events like user interactions or AJAX requests.
• Angular compares the current and new state of the application.
• If there are changes, it updates the view.
How it's implemented
• Angular uses a change detector tree to collect views that need to be checked for changes.
• It runs the change detector from the root component down through the component tree.
• Angular has different strategies for change detection, including Default and OnPush.
STRUCTURAL DIRECTIVES
Structural directives are responsible for the Structure and Layout of the DOM Element. It is used to hide or display
the things on the DOM. Structural Directives can be easily identified using the ‘*’. Every Structural Directive is
preceded by a ‘*’ symbol.
Some of the Build in Structural Directives with Examples are as follows:
1. *ngIf: ngIf is used to display or hide the DOM Element based on the expression value assigned to it.
The expression value may be either true or false.
Syntax: <div *ngIf="boolean"> </div>
2. *ngIf-else: ngIf-else works like a simple If-else statement, wherein if the condition is true then ‘If’ DOM
element is rendered, else the other DOM Element is rendered. Angular uses ng-template with element selector in
order to display the else section on DOM.
Syntax: <div *ngIf="boolean; else id_selector"> </div> <ng-template #id_selector> </ng-
template>
3. *ngFor: *ngFor is used to loop through the dynamic lists in the DOM. Simply, it is used to build data
presentation lists and tables in HTML DOM.
Syntax: <div *ngFor="let item of item-list"> </div>
4. *ngSwitch : ngSwitch is used to choose between multiple case statements defined by the expressions inside
the *ngSwitchCase and display on the DOM Element according to that. If no expression is matched, the default
case DOM Element is displayed.
Syntax: <div [ngSwitch]="expression"> <div *ngSwitchCase="expression_1"></div>
<div *ngSwitchCase="expression_2"></div>
<div *ngSwitchDefault></div>
PROPERTY & ATTRIBUTE
• Property Binding is a one-way data-binding technique. In property binding, we bind a property of a DOM

BINDING
element to a field which is a defined property in our component TypeScript code. Actually, Angular
internally converts string interpolation into property binding.
• In this, we bind the property of a defined element to an HTML DOM element.
• Syntax: <element [property]= 'typescript_property'>
• Attribute binding in Angular helps you set values for attributes directly. With attribute binding, you
can improve accessibility, style your application dynamically, and manage multiple CSS classes or
styles simultaneously.
• Attribute binding syntax resembles property binding, but instead of an element property between brackets,
you precede the name of the attribute with the prefix attr, followed by a dot. Then, you set the attribute
value with an expression that resolves to a string.
• content_copy<p [attr.attribute-you-are-targeting]="expression"></p>
PIPES IN ANGULAR
• Pipes are a special operator in Angular template expressions that allows you to transform data
declaratively in your template. Pipes let you declare a transformation function once and then use
that transformation across multiple templates. Angular pipes use the vertical bar character (|).
Built-in Pipes
Angular includes a set of built-in pipes in the
@angular/common package:
Passing parameters to pipes
Some pipes accept parameters to
configure the transformation.
To specify a parameter,
append the pipe name with a colon (:) f
ollowed by the parameter value.
For example,
the DatePipe is able to take parameters to format the date
in a specific way.
<p>The event will occur at {{ scheduledOn | date:'hh:mm' }}.</p>
check Some pipes may accept
multiple parameters. You can specify additional parameter values separated by the colon character (:).
For example, we can also pass a second optional parameter to control the timezone.
<p>The event will occur at {{ scheduledOn | date:'hh:mm':'UTC' }}.</p>
NESTED COMPONENTS BASICS
• When you work with a large Angular application, placing all features in a single Component is not a
good idea. As the application grows, maintaining it can become quite challenging. Therefore, we
need to split it into multiple components. It may require creating components inside others to form a
hierarchical structure.
• In Angular, it is possible to nest components inside each other. The outside container is known as
the parent container, and the inner one is known as the child container.
• How to Create Nested Components in Angular?
• Nested components are normal Angular Components with parent-child relations. The parent can
access and share data with the child, either partially or fully. Creating nested components follows
the same process as creating regular components.
• Example: Let's look at an example of how to create nested components in an Angular application.
Following are the steps −
• Step 1: Create an application named nestedApplication. ng new nestedApplication
• Step 2: Use the cd command to navigate inside the project folder. Then, create a component called
parent using the following command − ng g c parent
• Step 3: To create child component, use the command given below − ng g c parent/child
PASSING DATA FROM CONTAINER COMPONENT TO
CHILD COMPONENT
• We can use the @Input directive for passing the data from the Parent to Child component in Angular
• Using Input Binding: @Input – We can use this directive inside the child component to access
the data sent by the parent component. Here app.component is the Parent component and
cdetail.component is the child component.
• Parent Component app.component.ts There are two arrays. One for list_prog – list of languages,
prog_details – details of languages.
For Example:
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-cdetail',
templateUrl: './cdetail.component.html',
styleUrls: ['./cdetail.component.css']
})
export class CdetailComponent implements OnInit {
@Input() details: string;
@Input() title: string;
constructor() { }
ngOnInit(): void { }}
PASSING DATA FROM CHILD COMPONENT TO CONTAINERCOMPONENT
• To pass data from a Child Component to a Container (Parent) Component in Angular, you use the
@Output decorator and EventEmitter to emit an event from the child component, which the parent
component can listen to and receive the data within the event payload.
In the Parent Component:
• Bind the child component's @Output property to a method in the parent component using the
(event) syntax in the template.
• Inside the parent component's method, access the data passed through the event payload.
//childcomp.ts //parentcomp.ts
import { Component, Output, import { Component } from '@angular/core';
EventEmitter } from '@angular/core'; @Component({selector: 'app-parent', template: `
@Component({ selector: 'app-child', <app-
template: ` child(dataFromChild)="onChildData($event)"></app-
<button (click)="sendData('Some data child>
from child')">Send Data</button>`}) <p>Data from child: {{ childData }}</p>})export
export class ChildComponent { class ParentComponent {childData: string = '';
@Output() dataFromChild = new onChildData(data: string) {
EventEmitter<string>(); // Emits a this.childData = data; // Update parent component's
string data
sendData(data: string) }}
{ this.dataFromChild.emit(data); // Send
SHADOW DOM
• Shadow DOM in Angular is a way to isolate a component's styles and scripts from the rest of an
application. This encapsulation improves maintainability and performance.
• How does Shadow DOM work?
• Shadow DOM creates a "shadow root" around a component's template
• Styles and scripts within the shadow DOM are only applied to that DOM
• The shadow DOM is self-contained and can be developed, tested, and deployed independently
COMPONENT LIFE CYCLE
• In Angular, Components are the fundamental building blocks of an application. Understanding the
lifecycle of these components is crucial for effective Angular Development. Angular provides several
lifecycle hooks that allow developers to tap into key moments in a Component’s lifecycle and
execute custom logic during those times.
Component Lifecycle Stages
The component lifecycle in Angular consists of several stages:
• Creation: The component is instantiated and its dependencies are injected.
• Change Detection: Angular checks for changes
in the data-bound properties.
• Rendering: The component's template
is rendered or updated.
• Destruction: The component is destroyed
and cleaned up.
TEMPLATE DRIVEN FORMS
• Angular supports two design approaches for interactive forms. You can build forms by using
Angular template syntax and directives to write templates with the form-specific directives.
• Template-driven forms are suitable for small or simple forms, while reactive forms are more
scalable and suitable for complex forms.
you bind a sample form to data and handle user input using the following steps.
1.Build the basic form.
⚬ Define a sample data model
⚬ Include required infrastructure such as the FormsModule
2.Bind form controls to data properties using the ngModel directive and two-way data-binding
syntax.
⚬ Examine how ngModel reports control states using CSS classes
⚬ Name controls to make them accessible to ngModel
3.Track input validity and control status using ngModel.
⚬ Add custom CSS to provide visual feedback on the status
⚬ Show and hide validation-error messages
4.Respond to a native HTML button-click event by adding to the model data.
5.Handle form submission using the ngSubmit output property of the form.
⚬ Disable the Submit button until the form is valid
MODEL DRIVEN FORMS OR REACTIVE FORMS
• Reactive forms provide synchronous access to the data model, immutability through observable
operators, and change tracking through observable streams. They maintain form-state integrity
by returning a new state for each modification, using an explicit and immutable approach. Built
on observable streams, they provide synchronous access to form inputs and values, which
improves form state management.
DEPENDENCY INJECTION
• Angular is an open-source framework for building web modern web applications. One of the key
principles of Angular is dependency injection. Dependency Injection is one of the widely used
techniques in application programming. It is included in almost every framework. In this article,
we will learn about Dependency Injection and how to perform Dependency Injection in Angular.
Steps to Create Angular Application And Installing Module:
Step 1: Create a Angular application using the following command:
ng new my-App
Step 2: Go to your project directory
cd my-App
Step 3: Create a service using the following command.
ng generate service my-service
SERVICES BASICS & RXJS OBSERVABLES
• Angular services provide a way for you to separate Angular app data and functions that can be
used by multiple components in your app.

Observables
• An observable is a function that creates an observer and attaches it to the source where values
are expected from, for example, clicks, mouse events from a dom element or an Http request,
etc.
• Observer is an object with callback functions, that will get called when there is interaction to the
Observable, i.e., the source has interacted for an example button click, Http request, etc.
SERVER COMMUNICATION USING HTTPCLIENT
• Http Client Module is introduced in Angular 4 , this is a former implementation of Http Module .
The HttpClient service is a part of Http Client Module only and it is used to intiate requests from
server and process response with your application.
• To use HttpClientService in our module , first we need to import HttpClientModule in our
application. For eg:- import{HttpClientModule} from '@angular/common/http';

Error Handling:
A HttpRequest can fail , for various reasons , so to handle error case in our module ,
we have to add second callback method to subscribe. For eg:-
ngOnInit(){
this.http.get('http://jsonplaceholder.com/users').subscribe(
success=>{
console.log(success);
},error=>{console.log(error);}});}
To summarize , HttpClient module is used to fetch the api from service and
subscribe the method and get the response in return from respective api's.
COMMUNICATING WITH DIFFERENT BACKEND SERVICES USING
ANGULAR HTTPCLIENT
• To communicate with backend services using HTTP in Angular, you typically use the HttpClient
module, which is part of the @angular/common/http package. This module allows you to
interact with RESTful APIs, fetch data, submit forms, perform CRUD operations, and more.
Example:
import { HttpClientModule }
from'@angular/common/http';
@NgModule({
imports: [
// ... other modules
HttpClientModule],// ...})
export class AppModule { }
Example of a POST request to different backend
services:
postDataToService1(data: any) {
return this.http.post(`${this.baseUrl1}/data`,
data);}
ROUTING
• In a single-page app, you change what the user sees by showing or hiding portions of the display
that correspond to particular components, rather than going out to the server to get a new page.
As users perform application tasks, they need to move between the different views that you
have defined.
• To handle the navigation from one view to the next, you use the Angular Router. The Router
Routing
enables navigation by interpreting a browser URL as an instruction to change the view.
Links
• When applied to an element in a template, makes that element a link that initiates navigation to
a route. Navigation opens one or more routed components in one or more <router-outlet>
locations on the page.
• Given a route configuration [{ path: 'user/:name', component: UserCmp }], the following
creates a static link to the route: <a routerLink="/user/bob">link to user component</a>
• You can use dynamic values to generate the link. . For example, ['/team', teamId, 'user',
userName, {details: true}] generates a link to /team/11/user/bob;details=true.
• \For instance, suppose the current URL is /user/(box//aux:team). The link <a
[routerLink]="['/user/jim']">Jim</a> creates the URL /user/(jim//aux:team)
Example
<a [routerLink]="['/user/bob']" [queryParams]="{debug: true}" fragment="education">
link to user component</a>
Routing
• In Angular, guards are special classes used to control and manage access to different parts of an
Guards
application. They decide whether a user can navigate to a particular route or perform certain
actions based on specific conditions, like checking if the user is logged in or has the necessary
permissions. Guards act as gatekeepers, allowing or preventing access to different parts of the
application, ensuring security and controlling the flow of navigation within the app.
Types of Route Guards in Angular:
CanActivate:
• Determines if a route can be activated and allows navigation based on certain conditions.
• Implemented using CanActivate interface.
Use Case — Authentication Guard:
• Let’s say you have an application with a dashboard page that should only be accessible to
authenticated users. The CanActivate guard ensures that only authenticated users can access
this page, redirecting unauthenticated users to the login page.
CanActivateChild:
• Similar to CanActivate but controls the activation of child routes.
• Implemented using CanActivateChild interface.
CanDeactivate:
• Checks if a route can be deactivated, often used to confirm navigation away from a route.
• Implemented using CanDeactivate interface.
Asynchronous
• routing
Asynchronous routing is a network communication scenario where data packets take different
paths when traveling in opposite directions. It's also known as asymmetric routing.
How does it work?
• When traveling from point A to B, packets take one path
• When traveling from point B to A, packets take a different path
Nested Routing
• Nested routing in Angular allows you to create child routes within a parent route. This is useful
for structuring applications with multiple views or layouts.
• Nested routing in Angular helps in structuring applications efficiently. With the use of <router-
outlet>, children in Routes, and lazy loading, you can create a scalable routing system.
Nested Routing Display the component using Router-outlet
The components are always rendered in the
import { Routes } from '@angular/router';
import { HomeComponent} from
<RouterOutlet> of the parent component.
'./home.component'
import { ContactComponent} from
Hence, we need to add <router-outlet></router-outlet> in
'./contact.component' the product.component.html
import { ProductComponent} from <h1>Product List</h1>
'./product.component' <div class='table-responsive'>
import { ErrorComponent} from <table class='table'>
<thead>
'./error.component'
<tr>
import { ProductDetailComponent} from <th>ID</th>
'./product-detail.component' <th>Name</th>
export const appRoutes: Routes = [ <th>Price</th>
{ path: 'home', component: </tr>
</thead>
HomeComponent },
<tbody>
{ path: 'contact', component: <tr *ngFor="let product of products;">
ContactComponent }, <td>{{product.productID}}</td>
{ path: 'product', component: <td><a
[routerLink]="['detail',product.productID]">{{product.name}}
ProductComponent,
</a> </td>
children: [ <td>{{product.price}}</td>
{ path: 'detail/:id', component: </tr>
ProductDetailComponent } </tbody>
] </table>
</div>
},
{ path: '', redirectTo: 'home', pathMatch: <router-outlet></router-outlet>
Thank
You

You might also like