Intro_Angular_1
Intro_Angular_1
INTERNAL
25 Apr 2023
Agenda
Session 1
• Angular Introduction
• Typescript
• Understanding a Hello world Angular application
• Creating your first component
• Interpolation and Property Data Binding
Session 2
Document Name
-2- CONFIDENTIAL
Agenda…
Session 3
Session 4
Document Name
CONFIDENTIAL
Angular Introduction
Document Name
CONFIDENTIAL
Angular Versions
1.0 2010 It also referred as AngularJS designed especially for single-page web
apps.
2.0 2016 It is compatible with mobile devices. Moreover, Angular 2 can be able
to use ES5, ES6, or TypeScript to write the codes.
4.0 2017 Bug fixed version for Angular 2.0
5.0 2017 In this version, there is a Build Optimizer that created with the Angular
CLI by which allows you to apply build optimizer by default. ie; It
identifies code that can be removed at build time without side effects.
6.0 2018 Some new features added like, Angular Elements, Component Dev Kit,
Angular Material Starter Components, Library support, and Tree
Shakeable Providers
--- ---
14.0 2022 All GitHub issues are removed, No Dependency with Ng module. Uses
TypeScript 4.7
Document Name
CONFIDENTIAL
Angular JS v/s Angular 2.0
AngularJS code can write by using only ES5, We can use ES5, ES6, Typescript to write an
ES6, and Dart. Angular 2 code.
Factory, service, provider, value and constant are The class is the only method to define services in
used for services Angular2
Document Name
CONFIDENTIAL
Typescript
Document Name
CONFIDENTIAL
TypeScript v/s JavaScript
Typescript Javascript
Object-oriented programming Prototype based language
language
It has a feature known as Static Not
typing
Supports Interfaces Not
TypeScript always points out the Since JavaScript is an interpreted
compilation errors at the time of language. This advantage is not there.
development (pre-compilation). So,
less run time errors.
TypeScript supports static/strong It is dynamically typed language
typing
Superset of JS with ES6 support, but
able to compile to any lower versions
also for the browser compatibility.
Generally, when we run our In JavaScript types are checked at
TypeScript file, TypeScript compiles run time. That means types are not
our code and at that point it checks checked until the program executes.
the types. Only if everything is ok Document Name
does the program run. CONFIDENTIAL
TypeScript Basics
• Types by Inference
If you don't declare a type at all, but TypeScript infers (guesses) it for you.
• Declaring Types
For declaring a variable just add a colon and its type to the right of whatever
you're declaring.
let name: string = "Anoop";
• Interfaces
It is a mechanism used for creating objects.
interface Person {
name: string;
city: string;
age: number;
}
Document Name
CONFIDENTIAL
TypeScript Basics …
let myData: Person = {
name: "Anoop",
city: "Trivandrum",
age: 40
};
• Conditionals
It is a mechanism, suppose if I want to make a key conditional, allowing it to
be present or not.
interface Person {
name: string;
city: string;
age?: number;
}
Document Name
CONFIDENTIAL
TypeScript Basics …
• Unions
If we want a variable to be able to be assigned more than one different data
type, we can declare so by using unions.
interface Person {
name: string;
city: string;
age: number | string;
}
Document Name
CONFIDENTIAL
TypeScript Basics …
• Arrays
In typing functions, we can type its parameters as well as its return value.
let numbersArray: number[] = [1, 2, 3]; // It only accept
numbers in this array
let numbersAndStringsArray: (number | string)[] = [1,
"two", 3]; // Here it accept numbers and strings.
• Tuples
A tuple is a typed array with a pre-defined length and types for each index.
Tuples are great because they allow each element in the array to be a known
type of value.
// define our tuple
let employee: [number, string, string, number];
// print
console.log(employee);
Document Name
CONFIDENTIAL
Angular Installation
After the installation use the command npm - v which will list the node
version.
Document Name
CONFIDENTIAL
Hello world Angular application
Document Name
CONFIDENTIAL
Hello world Angular application
ng new hello-world
package.json : This is file includes the details about package dependencies of the
project.
main.ts : This file starts the AppModule from app.module.ts, and it can be used to define
global configurations. It describes how the application parts fit together. Every
application has at least one Angular module, the root module by default it is called as the
AppModule.
Document Name
CONFIDENTIAL
Hello world Angular application
In the application app folder, we can be able to see the following files. The below files were
created by default when we created new project using the angular-cli command.
• app.component.spec.ts : This file contains unit tests for the main AppComponent.
• app.component.ts : This is the classes that interact with the .html file of the
component, which gets displayed on the browser.
• app.module.ts : This is the area where we can group the components, directives and
services, which are related to the application.
Document Name
CONFIDENTIAL
Hello world Angular application …
ng serve
Document Name
CONFIDENTIAL
Creating your first component
Components are the most basic UI building block of an Angular app. An Angular app
contains a tree of Angular components. For Eg;
• Metadata − This is used to decorate the class and extend the functionality of the class.
• Template − This is used to define the HTML view which is displayed in the application.
Document Name
CONFIDENTIAL
Creating your first component…
Document Name
CONFIDENTIAL
Creating your first component…
Following files will be created while you create the login component;
• login.component.html : is an HTML file for the component where we will write HTML
for a component.
• login.component.spec.ts : is a test file where we can write unit tests for a component
All the component files in Angular should follow the following format:
<component-name>.component.<file-type>
Document Name
CONFIDENTIAL
Creating your first component…
login.component.ts
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent {
uname:String = "";
pass:String = "";
performLogin() {
if(this.uname==="Anoop" && this.pass==="Tata") {
alert('Login successfull...');
} else {
alert('Login failed!!!');
}
}
}export class LoginComponent {} Document Name
CONFIDENTIAL
Creating your first component…
login.component.html
<div>
User Name: <input [(ngModel)]="uname"><br/>
Password: <input type="password" [(ngModel)]="pass"><br/>
<button (click)="performLogin()">Login</button>
</div>
Since we need to use this component in other components, we use the export keyword
The decorator is the feature of typescript, this is going to attach the metadata with the
class beneath it.
In Angular we have one root component, and all other components needs to live inside
the root component
Document Name
CONFIDENTIAL
Templates
• A template is nothing, but a screen used to interact with the component. It
consists of a TypeScript class, an HTML template, and a CSS style sheet.
• Usually, we can define template in two manner;
1) Using Template:
• In this case we are defining an inline view in component attribute template. For
Eg;
template: '
<div>
<h1>{{appTitle}}</h1>
<div>To Hello World</div>
</div>
‘
Document Name
CONFIDENTIAL
Templates …
2) Using templateURL :
• In this case we are defining an inline view in component attribute template. For
Eg;
templateURL:
viewname.component.html
where, viewname is the name of the app component module. For eg;
app.component.html
Document Name
CONFIDENTIAL
Directives
A directive is a custom HTML element that is used to extend the functionalities of
HTML. Angular has the following directives that get called as part of the
BrowserModule module.
• ngif: The ngif element is used to add elements to the HTML code if it evaluates
to true, else it will not add the elements to the HTML code.
• ngFor: The ngFor element is used to elements based on the condition of the For
loop
<div>
<ul *ngFor = 'let cnt of countryList'>
<li>{{cnt}}</li>
</ul>
</div> .
Document Name
CONFIDENTIAL
Introduction to Angular
Session 2
Document Name
CONFIDENTIAL
Interpolation
Instead of hard coding the data in the html, what would be better is to have a
variable and assign value to it and get the data to the template. This can be
achieved using interpolation.
We can bind the variable value to the view using double curly braces {{}}, What we
need to specify inside the property double curly brace {{}} is called interpolation.
One - Way data binding is from the component property to the view.
app.component.ts
export class AppComponent {
name:string = ‘Ajay Kishan’;
}
app.component.html
Hello user: <b>{{name}}</b>
Document Name
CONFIDENTIAL
Property Data Binding
String Interpolation and Property binding both are used for same purpose i.e. one-
way databinding.
Document Name
CONFIDENTIAL
Interpolation vs Property Data Binding
• When you need to concatenate strings, you must use interpolation instead of property
binding.
• Property Binding is used when you have to set an element property to a non-string data
value.
Document Name
CONFIDENTIAL
Event Binding
Event Binding is the process of bind the events along with the methods.
In data binding the data flows from the component to the view, So when the component
class properties changes the view gets modified.
app.component.ts
import {
Component
} from '@angular/core';
@Component ({
selector: 'my-app',
templateUrl: 'app/app.component.html'
})
export class AppComponent {
Status: boolean = true;
clicked () {
if(this.status==true) {
this.status=false;
} else {
this.status=true;
} Document Name
CONFIDENTIAL
Event Binding…
app.component.html
<div>
{{Status}}
<button (click) = "clicked()">Click</button>
</div>
• We are first just displaying the value of the Status property of our class.
• Then are defining the button html tag with the value of Click. We then ensure that the
click event of the button gets triggered to the clicked event in our class.
Document Name
CONFIDENTIAL
Two-way binding
In angular, When ever we want to use two-way data binding, we use the ngModel
directives.
And the ngModel needs to be wrapped with the [()] for two-way binding.
In two-way binding, when ever the property in component changes the view changes and
whenever the view changes the property in component get change.
Note: Before using ngModel to achieve two-way data binding, It is very important to
import the FormsModule from @angular/forms in app.module.ts
Using Two-way data binding, we can simultaneously change the data property and display
the change in the view.
Document Name
CONFIDENTIAL
Two-way binding …
• Two-way binding combines property binding with event binding:
1) Property binding : Sets a specific element property.
2) Event binding : Listens for an element change event.
Document Name
CONFIDENTIAL
Two-way binding …
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-hello',
template: `
User Name: <input type="text" [(ngModel)]="userName" ><br/>
{{userName}}`
})
export class HelloComponent implements OnInit {
constructor() { }
private _userName: string = “Virat Kohli";
get userName(): string {
return this._userName;
}
set userName(val: string) {
//do some extra work here
this._userName = val;
}
ngOnInit(): void {
}
}
Document Name
CONFIDENTIAL
Structural Directives
• Structural directives are directives which change the DOM layout by adding and
removing DOM elements.
• When structural directives are applied, they generally are prefixed by an asterisk, *, such
as *ngIf.
• Following are some of the commonly used Structural directives in Angular;
• *ngIf : It is used to dynamically add some elements based on certain
attributes/conditions.
<div *ngIf="employee" class="name">{{employee.name}}</div>
• ngFor : The *ngFor directive is used to repeat a portion of HTML template once per
each item from an iterable list (Collection).
<tr *ngFor="let emp of employees;">
<td>{{emp.name}}</td>
</tr>
• ngSwitch : This directive is applied to the inner elements with a match expression.
<div [ngSwitch]="day">
<div *ngSwitchCase="'Sun'">Today is Sunday</div>
<div *ngSwitchCase="'Mon'">Today is Monday</div>
<div *ngSwitchDefault>Invalid Day selected</div>
</div>
Document Name
CONFIDENTIAL
Structural Directives …
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'employee-app',
templateUrl:'./app/app.component.html',
styleUrls:['./app/app.component.css']
})
class Employee {
name: string="";
empId: number=0;
status: string="";
}
export class AppComponent
{
employees : Employee[] = [{name: 'Anoop', empId: 1001, status:
'Active'}, {name: 'Sham', empId: 1002, status: 'Active'}, {name:
'Mohit', empId: 1003, status: 'In Active'},{name: 'Saran', empId:
1004, status: 'Active'}];
}
Document Name
CONFIDENTIAL
Structural Directives …
app.component.html
<table class='table'>
<thead>
<tr>
<th>Employee Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let emp of employees;">
<td>{{emp.empId}}</td>
<td>{{emp.name}}</td>
</tr>
</tbody>
</table>
Document Name
CONFIDENTIAL
Attribute Directives
• Attribute directive changes the behavior of the dom element.
1) ngClass : It is used to dynamically apply multiple classes to the html element.
ngStyle becomes much more useful when the value is dynamic.
For Eg;
<ul *ngFor="let product of stockArray">
<li [ngClass]="{
'text-success':product.status === 'Available',
'text-primary':product.status === 'Reorder',
'text-danger':product.status === 'NA'
}">{{ product.name }}
</li>
</ul>
2) ngStyle : The values in the object literal that we assign to ngStyle can be JavaScript
expressions which are evaluated, and the result of that expression is used as the value
of the CSS property.
Fo Eg;
<span [ngStyle]="{'background-color':emp.status === 'Active' ?
'green' : 'red' }"></<span>
Document Name
CONFIDENTIAL
Attribute Directives …
• Both the NgStyle and NgClass directives can be used to conditionally set the look and
feel of the application.
• But if we want to make changes to multiple properties at once, creating a class which
bundles those properties and adding the class with NgClass makes more sense.
Document Name
CONFIDENTIAL
Template Driven Form
• To get all the features of the form working, we need to import the FormsModule and import
it in the app.module.ts
import { FormsModule } from "@angular/forms";
• Anytime we use the form tag, angular attaches an ngForm directive, which attaches the
form value to it
ngForm
• Gives the form field value
• Indicates whether the form is in valid or in Invalid status, so in the form tag we can create
an ngForm directive and assign a reference to it.
Document Name
CONFIDENTIAL
Template Driven Form…
• The userForm has a property called value, which we are going to pass through the handler.
• We need to specify two things to indicate that it belongs to this form directive, a name
attribute and an ngModel directive
• E.g <input type="text" name="name" ngModel />
• We can also group certain tags using ngModelGroup
<div ngModelGroup="address">
<div>Street : <input type="text" name="street" ngModel /></div>
<div>Postal code : <input type="text" name="postalcode" ngModel /></div>
</div>
registerEmployee(value: any) {
console.log(value);
console.log("Name value is :"+value.name);
}
Document Name
CONFIDENTIAL
Introduction to Angular
Session 3
Document Name
CONFIDENTIAL
Model Driven Form
• In model driven from, as the name suggest a form is represented by a model and this
model is responsible for handling all the user interaction with the form
• We will be using 2 classes to create the model
– 1. FormControl : All input fields defined in HTML template are the instance of
FormControl.
– 2. FormGroup : It is an instance of a set of FormControl is referred as FormGroup
• Simillarly we will use FormGroup, when we have a form that has multiple inputs,
dropdown, radio buttons. All of which you want to create a JSON object to pass in API.
Document Name
CONFIDENTIAL
Model Driven Form …
<form [formGroup]="userForm" (click)=userSubmit()>
<div>
<label>Name</label>
<input type="text" formControlName="name" />
</div>
<div>
<label>Age</label>
<input type="text" formControlName="age"/>
</div>
<div>
<label>City</label>
<input type="text" formControlName="city"/>
</div>
<div>
<label>PostalCode</label>
<input type="text" formControlName="postalCode"/>
</div>
<button type="submit">Submit</button>
Document Name
</form> CONFIDENTIAL
Model Driven Form Validation
• Angular provides a built-in Validator class, which supports the built in validations.
• Based on the error, we can provide a valid error message to the user
Document Name
CONFIDENTIAL
Service
• Service is a piece of reusable code that we will use across multiple components in our
application.
• Usually, components needs to access the data. We can write data access code in each
Component, but this is very inefficient and breaks the rule of single responsibility.
• The Component should focus on presenting the data to the user.
• The task of receiving data from the back-end server should be delegated to another
class called service class because it provides each Component with the data it needs.
• There are 3 steps to implement services in Angular;
– 1) Create a Service
– 2) Register the service
– 3) Declare dependency
Document Name
CONFIDENTIAL
Service …
• Product.ts
export class Product {
constructor(productID:number, name: string , price:number) {
this.productID=productID;
this.name=name;
this.price=price;
}
productID:number ;
name: string ;
price:number;
}
• product.service.ts
import {Product} from './product'
export class ProductService{
public getProducts() {
let products:Product[];
products=[
new Product(1,'Memory Card',500),
new Product(2,'Pen Drive',750),
new Product(3,'Power Bank',100)
] Document Name
CONFIDENTIAL
return products;
Service …
• app.component.ts
import { Component } from '@angular/core';
import { ProductService } from './product.service';
import { Product } from './product';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
})
export class AppComponent
{
products:Product[];
productService;
constructor(){
this.productService=new ProductService();
}
getProducts() {
this.products=this.productService.getProducts();
}
Document Name
} CONFIDENTIAL
Service … (Injecting to the module)
• product.service.ts
import { Injectable } from '@angular/core';
@Injectable(){
providedIn: "root"
}
export class ProductService {
constructor()
{ }
public getProducts() {
let products:Product[];
products=[
new Product(1,'Memory Card',500),
new Product(2,'Pen Drive',750),
new Product(3,'Power Bank',100)
]
return products;
}
};
Document Name
CONFIDENTIAL
Service … (Injecting to the module)
• app.module.ts
Document Name
CONFIDENTIAL
Service … (Injecting to the module)
• app.component.ts
import { Component } from '@angular/core';
import { ProductService } from './productService';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
message: string = "";
constructor(private productService: ProductService ) {}
ngOnInit() {
this.products=this.productService.getProducts();
}
}
Document Name
CONFIDENTIAL
HttpClient
• Angular provides a client HTTP API to communicate with a server over the HTTP
protocol, to download or upload data and access other back-end services.
• The HttpClient service class in @angular/common/http.
• Before you can use HttpClient, you need to import the Angular HttpClientModule. Most
apps do so in the root AppModule. (app.module.ts)
app.module.ts
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [], Document Name
CONFIDENTIAL
HttpClient : Requesting data from a server - GET
• The HttpClient.get() method to fetch data from a server. The asynchronous method sends
an HTTP request and returns an Observable that emits the requested data when the
response is received.
• The get() method takes two arguments;
• the endpoint URL from which to fetch
• an options object that is used to configure the request. (like headers,params,
return type etc.)
loadUsers() {
this.http.get<any>('https://jsonplaceholder.typicode.com/users')
.subscribe({
next: data => {
console.log(data);
this.message=JSON.stringify(data);
},
error: error => {
this.message=error.message;
}
})
}
Document Name
CONFIDENTIAL
HttpClient : Sending data to a server - POST
• The HttpClient.post() sends the HTTP POST request to the endpoint.
• The post method parsed the body of the response as JSON and returns it. This is the
default behavior. If we want any other type, then we need to specify explicitly using the
observe & responseType options.
addPerson(person:Person): Observable<any> {
const headers = { 'content-type': 'application/json'}
const body=JSON.stringify(person);
this.http.post(this.baseURL + 'people',
body,{'headers':headers , observe: 'response'})
.subscribe(
response=> {
console.log("POST completed sucessfully. The response
received "+response);
},
error => {
console.log("Post failed with the errors");
},
() => {
console.log("Post Completed");
}
} Document Name
CONFIDENTIAL
Observables
• Observable in Angular is a feature that provides support for delivering messages
between different parts of a single-page application.
• Angular makes use of observables as an interface to handle a variety of common
asynchronous operations.
• For example: The HTTP module uses observables to handle AJAX requests and
responses. The Router and Forms modules use observables to listen for and respond
to user-input events.
• In Angular to implement Observable, needs to create an instance of a subscriber
function. Whenever a consumer wants to execute the function the subscribe() method
is called. This function defines how to obtain messages and values to be published.
Document Name
CONFIDENTIAL
Routing
• Routing in Angular allows the users to create a single-page application with multiple
views and allows navigation between them.
• Users can switch between these views without losing the application state and
properties.
• Create the navigation links inside the app component and then provide the “routerLink”
directive to each route and pass the route value to “routerLink” directive.
• Then add the routes to the routing.module.ts file and then import the routing.module.ts
into the app.module.ts file.
app.component.html
<span>
<ul>
<li><a routerLink="/" >Home</a></li>
<li><a routerLink="/login" >Login</a></li>
<li><a routerLink="/custlist" >List</a></li>
</ul>
</span>
<router-outlet></router-outlet>
Document Name
CONFIDENTIAL
Routing …
• app-routing.module.ts
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Document Name
CONFIDENTIAL
Happy Learning !