Unit - 05 Mean Stack
Unit - 05 Mean Stack
What is Angular JS
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