You are on page 1of 40

Angular 7

Introduction
What is Angular ?:

Angular is JavaScript Framework which is used to develop Responsive


and Dynamic Web Applications.

Angular is a platform that makes it easy to build applications with


the web
Angular combines declarative templates, dependency injection,
end to end tooling
integrated best practices to solve development challenges
Angular empowers developers to build applications that live on the
web, mobile, or the desktop
Prerequisites:
Before proceeding with this tutorial, you should have a basic understanding of
• TypeScript/JavaScript,
• text editor
• execution of programs, etc.

Because we are going to develop web-based applications using Angular, it will


be good if you have an understanding of other web technologies such as
• HTML
• CSS
• AJAX
Introducing Angular
• AngularJS was the most popular client-side framework among JavaScript
developers for many years.
• Google introduced AngularJS in 2012.
• It's based on a variation of the very popular Model-View-Controller
pattern which is called MVC
• The AngularJS framework, was built on top of JavaScript with the aim
to decouple the business logic of an application from the low level
DOM manipulation and create dynamic websites.
• Developers could use it to either create full-fledged SPAs and rich web
applications or simply control a portion of a web page which makes it
suitable for different scenarios and developer requirements.
Angular Versioning
Angular 7 Angular JS – 1
2018 Sept/Oct 2010

Angular 6
2018 Mar

Angular 5
2017 Sept/Oct
Complete Rewrite
Angular 4
2017 Mar

Angular 2
2016 Sept

Incremental Improvements, No Rewrites


Before going to angular Lets dive into the
TypeScript which is necessary for Angular 7
Type Script
What is TypeScript?

• By definition, “TypeScript is JavaScript for application-scale


development.”
• TypeScript is a strongly typed, object oriented, compiled
language. It was designed by Anders Hejlsberg (designer of C#) at
Microsoft.
• TypeScript is both a language and a set of tools.
• TypeScript is a typed superset of JavaScript compiled to
JavaScript.
• In other words, TypeScript is JavaScript plus some additional
features.
Installing TypeScript

npm install –g typescript


Basic Program :

greet.ts
function greeter(person)
{
return "Hello, " + person;
}
let user = "Jane User";
document.body.innerHTML = greeter(user);
in CMD -> tsc greet.ts
Index.html
<!DOCTYPE html>
<html>
<head>
<title>TypeScript Greeter</title>
</head>
<body>
<script src="greeter.js"></script>
</body>
</html>
Types In Type Script BUILT-IN DATA TYPE KEYWORD DESCRIPTION

It is used to represent both Integer as


Number number
well as Floating-Point numbers

Boolean boolean Represents true and false

It is used to represent a sequence of


String string
characters

Void void Generally used on function return-types

It is used when an object does not have


Null null
any value

Denotes value given to uninitialized


Undefined undefined
variable

If variable is declared with any data-type

Any any then any type of value can be assigned


The Any type
The any data type is the super type of all types in TypeScript. It denotes a dynamic type.
Using the any type is equivalent to opting out of type checking for a variable.
Syntax for Assigning type to a variable in typescript

let variable_name: type; // declaration


let variable_name: type = value; // assignment
Type Assertions

• In TypeScript, type assertion is a way to tell the compiler what is the type of a
variable.
• Type assertion is used when the type of the target variable might not be
known or the programmer knows better what is the actual type of it.
• Type assertion is like type casting in other languages, but in TypeScript it is
only a compile time feature.
Type assertion syntaxes

Angle-bracket syntax
let x: any = "Gadwal Bidda";
let s = (<string>x).substring(0,3);
console.log(s);
Output
Gad

Using keyword 'as'


let x: any = "Gadwal Bidda";
let s = (x as string).substring(0,3);
console.log(s);
Output
Gad
What is an Arrow Function?
• An Arrow Function as called as Fat Arrow Function, are concise way of
writing a function expression.
• In the following example we have two ways of writing a function in ES5 and
ES6 style of coding.
// ES5
var getResult = function(username, points) {
return username + ' scored ' + points + ' points!';
};
// ES6
var getResult = (username: string, points: number): string =>
{
return `${ username } scored ${ points } points!`;
}
Interfaces in TypeScript
An interface is a syntactical contract that an entity should conform to. In other
words, an interface defines the syntax that any entity must adhere to.
interface interface_name { }
interface IPerson {
firstName:string,
lastName:string,
sayHi: ()=>string
}
var customer:IPerson = {
firstName:"Tom",
lastName:"Hanks",
sayHi: ():string =>{return "Hi there"}
}
console.log("Customer Object ")
console.log(customer.firstName)
console.log(customer.lastName)
console.log(customer.sayHi())
var employee:IPerson = {
firstName:"Jim",
lastName:"Blakes",
sayHi: ():string =>{return "Hello!!!"}
}
console.log("Employee Object "); console.log(employee.firstName);
console.log(employee.lastName);
Classes in TypeScript:
• TypeScript is object oriented JavaScript.
• TypeScript supports object-oriented programming features like classes,
interfaces, etc.
• A class in terms of OOP is a blueprint for creating objects.
• A class encapsulates data for the object.
• Typescript gives built in support for this concept called class.
• JavaScript ES5 or earlier didn’t support classes. Typescript gets this feature
from ES6.

Syntax:

class class_name { //class scope }


Access Modifiers
TypeScript supports access modifiers public, private and protected which
determine the accessibility of a class member as shown below:

accessible on public protected private

class yes yes yes

class children yes yes no

class instances yes no no

If an access modifier is not specified it is implicitly public as that matches


the convenient nature of JavaScript
Access Modifiers in Constructor Parameter
TypeScript supports automatic property creation. Instead of passing the values
using a parameterized constructor and then filling those properties, if you
define the constructor parameters as public/private, TypeScript will do the rest
of the job for you.
class Person {
// parameterized construtor
constructor (public fName: string, public lName: string) { }
// method
getFullName()
{
return `${firstName} ${lastName}`;
}
}
Angular Project Structure
 Starting from the top we have the end-to-end tests using
protractor
 node_modules ( absolute unit ) with all the npm packages and
dependencies
 src which contains our source code:
 app which contains the source code of our angular application
 assets which will contain all the asset files such as logos, images,
videos, media …
 environments for the environment based configurations
 browserlist that lists the rules for the supported browsers
 the favicon.ico, the tiny logo that appears next to the title in the
browser tab
 index.html where everything begins
 all the principal files for karma tester, the main angular file, polyfill
and the main style.sass and the tslint and tsconfig jsons
 angular.json which contains all the relevant configuration for
angular cli in terms of building, and compilation
 package.json which is the list of all the dependencies in the
project
Decorators
• Decorators are features of TypeScript and are implemented as functions.
The name of the decorator starts with @ symbol following by brackets and
arguments, since decorators are just functions in TypeScript.

• Decorators are simply functions that returns function. These functions


supply metadata to angular about a particular class, property, value or
method.

• Decorators are invoked at runtime.

• Decorators allow you to execute functions. For Example, @Component


executes the component function improved from Angular 7.
Here’s the list of decorators available in Angular:
1) @NgModule
2) @Component
3) @Injectable
4) @Directive
5) @Pipe
6) @Input
7) @Output
8) @HostBinding
9) @HostListener
10) @ContentChild
11) @ContentChildren
12) @ViewChild
13) @ViewChildren
Components
An Angular app is a tree structure consisting of all those components that we
create, Components are the most basic UI building block of an Angular app.
An Angular app contains a tree of Angular components

A component contains (mostly) 3 parts:


• Template File— HTML View
• TypeScript File — Model
• Style File — CSS
1. First of all, we import Component from the @ angular/core library, so we
can create an Angular Component
2. The @ Component decorator marks the TS class as a Component and
allows us to add the metadata
@Component:
Usage: //inherited from core/Directive
import { Component } from '@angular/core'; selector?: string
@Component({ inputs?: string[]
changeDetection?: ChangeDetectionStrategy outputs?: string[]
viewProviders?: Provider[] host?: {...}
moduleId?: string providers?: Provider[]
templateUrl?: string exportAs?: string
template?: string queries?: {...}
styleUrls?: string[] })
styles?: string[]
animations?: any[] class ComponentName{}
encapsulation?: ViewEncapsulation
interpolation?: [string, string]
entryComponents?: Array<Type<any> | any[]>
preserveWhitespaces?: boolean
Services
A class with specific purpose

1) Share data
2) Implement Application logic
3) External Interaction

Naming Convention - .service.ts


• Angular services are singleton objects which get instantiated only once
during the lifetime of an application.

• They contain methods that maintain data throughout the life of an


application, i.e. data does not get refreshed and is available all the time.

• The main objective of a service is to organize and share business logic,


models, or data and functions with different components of an
Angular application.

• An example of when to use services would be to transfer data from one


controller to another custom service.
Why Should We Use Services in Angular?

The separation of concerns is the main reason why Angular services


came into existence. An Angular service is a stateless object and
provides some very useful functions. These functions can be invoked
from any component of Angular, like Controllers, Directives, etc. This
helps in dividing the web application into small, different logical units
which can be reused.
Dependency Injection
• Dependency injection (DI) is a design pattern where objects are passed
to another object to complete the tasks.
• In angular a service or component may require other dependent services
to complete a task.
• Angular uses dependency injection design pattern to fulfill these
dependencies.
• The advantage of dependency injection design pattern is to divide the
task among deferent services.
• The client service will not create the dependent object itself rather it will
be created and injected by an Angular injector.
@Injectable(
{providedIn:'root’}
)
Determines which injectors will provide the injectable, by either
associating it with an @NgModule or other InjectorType, or by
specifying that this injectable should be provided in the 'root' injector,
which will be the application-level injector in most apps.
• The responsibility of Angular injector is creating service instances and
injecting them into classes like components and services.
• Angular creates root injector during bootstrap process and then creates
other injectors.
• Angular injectors do not know automatically how to create service
instances, so we need to specify providers for every service otherwise
service instance will not be injected.
• Injector creates singleton object of a service and hence same object is
injected in components and services.
Forms
1) Template Driven Forms
2) Model Driven Forms
3) Model Driven Forms – Form Builder
Http
Browser Server

Emp List

GET Request
Emp
HTTP
Service
Observable Response DB

Emp Details
Observables
Source DB

Convert GET Observable - map

News Paper Company Employee-Service

House 1 House 2 House n EmpList EmpDetails AppComp


Observable
• Observables provide the support for passing the messages between
publishers(Creator of Observables) and subscribers(User of Observables) in
your application.
• Observables are declarative that is, you define the function for publishing
values, but it is not executed until the consumer subscribes to it.
• The observable can deliver the multiple values of any type like literals,
messages, or events, depending on the context.
• As a publisher, you can create an Observable instance that defines
a subscriber function.
• This is a function that is executed when the consumer calls the subscribe()
method.
Observables and Rxjs

1) Make http call from EmpService


2) Receive the observables and map it
3) Subscribe to observable
4) Assign and Emp Data to local variable in view

You might also like