SlideShare ist ein Scribd-Unternehmen logo
1 von 142
TYPESCRIPT
TYPE SCRIPT
• Typescript is a typed superset of JavaScript that compiles to plain
JavaScript.
• Typescript is pure object oriented with classes, interfaces and statically
typed like C# or Java.
• JavaScript framework Angular 2.0 is written in TypeScript.
• TypeScript can help programmers to write object-oriented programs and
have them compiled to JavaScript, both on server side and client side.
• Using Typescript, we can build the faster web applications.
TYPE SCRIPT OVERVIEW
• JavaScript was introduced as a language for the client side.
• The development of Node.js has marked JavaScript as an emerging server-side technology
too.
• As JavaScript code grows, it tends to get messier, making it difficult to maintain and reuse
the code.
• Failure Features like
• OOPS concepts
• Strong type checking and
• compile-time errors
• These reasons prevents JavaScript from succeeding at the enterprise level as a full-fledged
server-side technology.
• TypeScript was presented to bridge this gap.
COMPILE/EXECUTE TYPESCRIPT
PROGRAMS
Syntax :
Typescript Code:
Complied JavaScript code
Output: Hello World
EXECUTION OF TYPESCRIPT CODE
Execution in Command prompt :
tsc first.ts
node first.js
Execution in Sublime : ctrl + b
Execution in vs code : ctrl + ` (tilt symbol)
Multiple files can be compiled at a time.
tsc file1.ts, file2.ts, file3.ts
Single statement execution : tsc file.ts && node file.js
WHAT IS TYPESCRIPT?
• TypeScript is JavaScript for application-scale development.
• TypeScript is a strongly typed, object oriented, compiled language.
• Designed by Anders Hejlsberg (designer of C#) at Microsoft.
• TypeScript is a typed superset of JavaScript compiled to JavaScript.
• In other words, TypeScript is JavaScript plus some additional features.
FEATURES OF TYPESCRIPT
TypeScript is just JavaScript:TypeScript starts with JavaScript and ends with
JavaScript. TypeScript code is converted into its JavaScript for execution.
TypeScript supports other JS libraries: TypeScript-generated JavaScript can
reuse all of the existing JavaScript frameworks, tools, and libraries.
JavaScript is TypeScript: valid .js file can be renamed to .ts and compiled with
other TypeScript files.
TypeScript is portable:TypeScript is portable across browsers, devices, and
operating systems. It can run on any environment that JavaScript runs on.
WHY USE TYPESCRIPT?
• TypeScript is superior to CoffeeScript and Dart programming languages.
• Dart, CoffeeScript etc are new languages and they require language-specific
execution environment.
• Compilation
• Strong Static Typing:JavaScript is not strongly typed.
• supports type definitions:
• supports Object Oriented Programming: like classes, interfaces, inheritance,
etc.
TYPESCRIPT AND OBJECT ORIENTATION
• TypeScript is Object-Oriented JavaScript.
• Object Orientation considers a program as a collection of objects that communicate with
each other via mechanism called methods.
• TypeScript supports these object oriented components too.
• Object − An object is a real time representation of any entity. According to Grady Brooch,
every object must have three features −
• State − described by the attributes of an object
• Behavior − describes how the object will act
• Identity − a unique value that distinguishes an object from a set of similar such objects.
• Class − A class in terms of OOP is a blueprint for creating objects. A class encapsulates
data for the object.
• Method − Methods facilitate communication between objects.
EXAMPLE: TYPESCRIPT AND OBJECT ORIENTATION
TypeScript Code
Complied JavaScript code
Output: Hello World!!!
https://www.tutorialspoint.com/typescript/typescript_basic_syntax.htm
BASIC TYPES
The data type classification is as given below
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.
Built-in types
User-defined Types
• User-defined types include Enumerations (enums), classes, interfaces, arrays, and tuple. These
are discussed in detail in the later chapters.
Data type Keyword Description
Number number Double precision 64-bit floating point values.
It can be used to represent both, integers and
fractions.
String string Represents a sequence of Unicode characters
Boolean Boolean Represents logical values, true and false
Void void Used on function return types to represent
non-returning functions
Null null Represents an intentional absence of an
object value.
Undefine
d
undefined Denotes value given to all uninitialized
variables
VARIABLES
1) Boolean :Basic datatype is the simple true/false value.(Both JS and TS)
Syntax : let isDone: boolean = false;
2) Number:All numbers in TypeScript are floating point values. In addition to hexadecimal and
decimal literals, TypeScript also supports binary and octal literals.
Syntax :
let decimal: number = 6;
let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;
String: It refers to these textual datatype. Like JavaScript, TypeScript also use double quotes (“”)
or single quotes(‘’) to surround string data.
Syntax:
let color: string = "blue";
color = 'red';
3)Array:Array types can be written in one of two ways.
First way : let list: number[] = [1, 2, 3];
Second way : The second way uses a generic array type ,Array<elemType or Datatype>
let list: Array<number> = [1, 2, 3];
var names: Array<string> = [“Ravi", “venkat", “Suresh"];
4) Tuples: Used to store a collection of values of multiple types.
Syntax :
// Declare a tuple type
let x: [string, number];
// Initialize it
x = ["hello", 10]; // OK
// Initialize it incorrectly
x = [10, "hello"]; // Error
When accessing an element with a known index, the correct type is retrieved:
console.log(x[0].substr(1)); // OK
console.log(x[1].substr(1)); // Error, 'number' does not have 'substr‘
5) Enum
Enumeration (or enum) is a user defined data type.
It is mainly used to assign names to integral constants, It make a program easy to read and
maintain.
Syntax :
enum Color {Red, Green, Blue}
let c: Color = Color.Green;
By default, enums begin numbering their members starting at 0. You can change this by manually
setting the value of one of its members.
enum Color {Red = 1, Green, Blue} let c: Color = Color.Green;
Or, even manually set all the values in the enum:
enum Color {Red = 1, Green = 2, Blue = 4}
let c: Color = Color.Green;
enum Color {Red = 1, Green, Blue}
let colorName: string = Color[2];
alert(colorName);
6)Any
The type of variables that we do not know when we are writing an application.
These values may come from dynamic content.
Syntax
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean
Array has a mix of different types of data
let list: any[] = [1, true, "free"];
list[1] = 100;
7)Void
Return type of functions that do not return a value.
Syntax:
Typescript Code
/ /void - when we do not have any return type from a function
function AlertMe(): void {
alert("Hello, how are you?");
}
AlertMe();
JavaScript Code
// void - when we do not have any return type from a function
function AlertMe() {
alert("Hello, how are you?");
}
AlertMe();
INTERFACES
• TypeScript type-checking only checks for the shape of the interfaces. This type of
checking is also called duck typing or structural subtyping.
Syntax:
• Declare the interface with using “interface” keyword.
• It is not mandatory to start with I ,We have to follow the standard naming convention
while declaring interface in other programming languages.
Interface in TypeScript
// declaring interface
interface IPerson {
name: string;
}
// using the interface
function Details1(thisPerson: IPerson) {
alert(thisPerson.name);
}
// calling the function that is using interface
var myDetail1 = { age: 50, name: "Sheo" };
var myDetail11 = { name: "Sheo Narayan", address : "Hyderabad", age
:50 };
Details1(myDetail1);
Details1(myDetail11);
JAVASCRIPT OUTPUT
/ using the interface
function Details1(thisPerson) {
alert(thisPerson.name);
}
// calling the function that is using interface
var myDetail1 = { age: 50, name: "Sheo" };
var myDetail11 = { name: "Sheo Narayan", address: "Hyderabad", age: 50
};
Details1(myDetail1);
Details1(myDetail11);
OPTIONAL PROPERTIES IN THE INTERFACE OF
TYPESCRIPT
interface IPersonOptional {
name: string,
age?: number;
}
// using the interface
function DetailsOptional(personalOptional: IPersonOptional) {
if (personalOptional.age) {
alert("Your name is: " + personalOptional.name + " and age is: " + personalOptional.age);
}
else {
alert("Your name is: " + personalOptional.name);
}
}
// calling the function that is using interface
DetailsOptional({ name: "Sheo" });
DetailsOptional({ name: "Sheo", age: 60 });
JAVASCRIPT OUTPUT
// using the interface
function DetailsOptional(personalOptional) {
if (personalOptional.age) {
alert("Your name is: " + personalOptional.name + " and age is: " + personalOptional.age);
}
else {
alert("Your name is: " + personalOptional.name);
}
}
// calling the function that is using interface
DetailsOptional({ name: "Sheo" });
DetailsOptional({ name: "Sheo", age: 60 });
TYPESCRIPT - CLASSES
• A class in terms of OOP is a blueprint for creating objects.
• A class encapsulates data for the object.
Syntax
class class_name {
//class scope
}
A class definition can include
Fields: Any variable declared in class.
Constructors: Responsible for allocating memory for the objects of the class.
Functions: Functions represent actions an object can take(methods).
class Greeter {
//field
greeting: string;
//constructor
constructor(message: string) {
this.greeting = message;
}
//function or method
greet() {
return "Hello, " + this.greeting; //member access
}
}
let greeter = new Greeter("world");
TYPESCRIPT CLASS INHERITANCE
• Inheritance is the ability of a program to create new classes from an existing class.
• A class inherits from another class using the ‘extends’ keyword.
TYPESCRIPT ACCESS MODIFIERS
There are the 3 types of access modifiers
1) Public
2) Private
3) Protected
there are three types of access modifier is used, called public, private and protected.
TYPESCRIPT PUBLIC MODIFIER
• TypeScript, each member is public by default.
• When a member is marked as public explicitly, it can access from outside of its
containing class.
TYPESCRIPT PRIVATE MODIFIER
• When a member is marked private, it cannot be accessed from outside of its
containing class.
PROTECTED PRIVATE MODIFIER
• When a member is marked protected, it cannot be accessed outside of its containing
class but exception that members declared protected can also be accessed by instances
of deriving classes.
TYPESCRIPT - FUNCTIONS
• Functions are the building blocks of readable, maintainable, and reusable code.
• A function is a set of statements to perform a specific task.
• Functions organize the program into logical blocks of code.
Named function :
function add(x, y)
{ return x + y;}
Anonymous function
let myAdd = function(x, y)
{ return x + y; };
ANGULAR -2
INTRODUCTION
• UI framework for building mobile and Desktop web applications.
• Built with using Typescript(Superscript of JavaScript).
• It is used to develop enterprise scale applications.
• We can build amazing client side applications using HTML, CSS, and
JavaScript.
WHY WE LEARN ANGULAR 2
• Performance : Angular2 is 5 times faster than AngularJS.
• Mobile Support: SPA that works across mobile and desktop devices.
• Component Based Development: In Angualr2, Everything is a component and
components are the building blocks of an angular application.
• More language choices
• ECMAScript 5
• ECMAScript 6 ( ES 2015 )
• TypeScript (Most popular language)
• Dart
• PureScript
• Elm etc.
ECMASCRIPT
• Angular 2 itself, is built using Typescript. Typescript has great
support of ECMAScript 6 standard.
1. What is ECMAScript
• The JavaScript language standard is officially called ECMAScript.
• We have ECMAScript version 1 to ECMAScript version 7.
• Modern browsers available today supported by ECMAScript5.
• The browser support for ECMAScript 6 is still incomplete.
• The process called Transpiration, ECMAScript 6 to ECMAScript 5.
• ECMAScript 6 is officially known as ECMAScript 2015.
• ECMAScript 2015 introduced new features like classes, modules, arrow
functions etc.
2. What is Type Script
a) Typescript is a free and open-source programming language
developed by Microsoft.
b) Superset of JavaScript
c) Transpilation ( Complies Typescript to JavaScript )
Benefits :
1. Intellisense
2. Autocompletion
3. Code navigation
4. Advanced refactoring
5. Strong Typing
6. Supports ES 2015 (also called ES 6) features like classes,
interfaces and inheritance.
QUICK START
Step 1: Set up the Development Environment
Then install the Angular CLI globally.
npm install -g @angular/cli
Step 2: Create a new project
Open a terminal window.
ng new my-app
Step 3: Serve the application
cd my-app
ng serve - -open or (-o)
http://localhost:4200/
Step 4: Edit your first Angular component(src/app/app.component.ts)
export class AppComponent {
title = 'My First Angular App';
}
Open src/app/app.component.css and give the component some style.
h1 {
color: #369;
font-family: Arial, Helvetica, sans-serif;
font-size: 250%;
}
Please refer this link for execution : https://angular.io/guide/quickstart
Create a child components using command prompt
• ng generate component hello (or)
• ng g component hello
UNDERSTANDING THE FILE STRUCTURE
• app/app.component.ts - this is where we define our root component.
• app/app.module.ts - Defines AppModule, the root module that tells
Angular how to assemble the application.The entry Angular Module to
be bootstrapped.
• index.html - this is the page the component will be rendered in.
• app/main.ts - is the glue that combines the component and page
together.
Index.html: This the main HTML page of our site.The CLI automatically adds all JS and CSS
files when building our app.(no need to add <script> or <link> tags manually).
main.ts:The main entry point for your app. Compiles the application with the JIT
compiler and bootstraps the application's root module (AppModule) to run in the browser.
Pollyfills.ts :Different browsers have different levels of support of the web standards. Polyfills
help normalize those differences.
Styles.css :Your global styles go here.
Test.ts :This is the main entry point for your unit tests.
tsconfig.{app|spec}.json : TypeScript compiler configuration for the Angular app.
Package.Json : configuration listing the third party packages your project uses. (Add custom
custom scripts here ).
tscofig.json :TypeScript compiler configuration for your IDE .
tslint.json : A grammar check for computer programs and Linting helps keep your code style
consistent.
ANGULAR 2 TOPICS
• Components.
• Template vs TemplateUrl.
• Nested Components.
• One-way Databinding.
• Interpolation.
• Property Binding
• Attribute Binding
• Class Binding
• Style Binding
• Event Binding
• Two-way data binding.
• HTML Attribute vs DOM property.
• Structural Directives
• *ngIf
• *ngFor
• *ngSwitch
• Pipes
• Custom pipes
• Interfaces
• Component life cycle
• Services (HTTP ,Error Handling)
• Routing
• Dependency Injection
ANGULAR 2 COMPONENTS
What is a component ?
• Components are the most basic building block of an UI in an Angular application. An
Angular application is a tree of Angular components.
• Component in angular is a class with a template and a decorator.
• Component is composed with 3 things.
Class :Defines the user interface. Contains the HTML, directives and bindings.
• Properties contain the data that we want to display in the view template and
methods contain the logic for the view. We use Typescript to create the class.
Template :Contains the code required for template.
Decorator: We use the Component decorator provided by Angular to add metadata to the
class. A class becomes an Angular component, when it is decorated with the Component
decorator.
Class:
The class decorator. The class is defined in TypeScript.
Syntax
Parameters:
• Classname − This is the name to be given to the class.
• Propertyname − This is the name to be given to the property.
• PropertyType − Since TypeScript is strongly typed, you need to give a type to the
property.
• Value − This is the value to be given to the property.
Example:
Template:
The view which needs to be rendered in the application.
Syntax
Parameters
• HTML Code − This is the HTML code which needs to be rendered in the application.
• Class properties − These are the properties of the class which can be referenced in the
template.
Example
Decorator
It is used to decorate Angular class with additional information.
Metadata Properties: https://angular.io/api/core/Component
Note :Selector becomes a directive in any html page where we want to use template.
TEMPLATE VS TEMPLATE URL
Inline Template:
The view template is inline in a pair of backtick characters.
Examples :
1) template: ‘<h1>Hello {{name }}</h1>’
2) template: ”<h1>Hello {{name }}</h1>”
3) template: `<h1>
Hello {{name }}
</h1>`
HTML code is more than one line, then you have to use backticks instead of single or double
quotes
External View Template:
• Instead of using an inline view template, you can have it in a separate HTML file.
• External view template using templateUrl property.
Difference between Inline and External View Template
Inline Template :
• Poor Intellisense, Code-completion and formatting feature.
• TypeScript code is not easier to read and understand.
External Template:
• Intellisense, code-completion and formatting features.
• Not only the code in "app.component.ts" is clean, it is also easier to read and
understand.
NESTED COMPONENTS
• Angular 2 is all about components.
• A component in Angular allows us to create a reusable UI widget.
• A component can be used by any other component.
We have to create two components
• AppComponent :This component is the root component and displays just the page header.
• EmployeeComponent :This component is the child component and displays the Employee details
table. This child component will be nested inside the root AppComponent.
What is AppModule?
AppModule is the root module which bootstraps and launches the angular application. (you can
name it anything what you want)
AppModule Imports 2 system modules
1) BrowserModule
2) NgModule
• BrowserModule - Every application that runs in a browser needs this module.
• NgModule - @component decorator adds metadata to an angular component class, similarly
@NgModule decorator adds metadata to the angular module class.
• A class is decorated @component decorator then that class becomes an angular component.
• Similarly if a a class is decorated with @NgModule decorator then that class becomes an
angular module.
Properties of the @NgModule decorator
• imports - Imports the BrowserModule required for an angular application to run in a web
browser
• declarations - Contains the components registered with this module. ( AppComponent and
EmployeeComponent).
• bootstrap - Contains the root component that Angular creates and inserts into the index.html
host web page.
Program Execution
STYLING ANGULAR 2 COMPONENTS
Option 1: Specify the styles in external stylesheet - styles.css
Advantages :
• Visual Studio editor features (Intellisense, Code completion & formatting) are available.
• Application maintenance is also easy because we only have to change the styles in one
place.
Disadvantages :
• The Stylesheet that contains the styles must be referenced for the component to be
reused.
• Since styles.css is referenced in index.html page, these styles may affect the elements in
other components, and you may or may not want this behavior.
Option 2 : Inline –Styles
Advantages :
• Visual Studio editor features (Intellisense, Code completion & formatting) are available.
• Component can be easily reused as the styles are defined inline.
• Styles specified using this approach are local to the component and don't collide with styles
used elsewhere in the application.
Disadvantages :
• Application maintenance is difficult.
• For example, if we want to change the <td> border color to red we have to change it in several
places.
Option 3 : Specify the styles in the component html file using <style> tag.
Advantages :
• Component can be easily reused as the styles are defined inline with in the component itself
• Application maintenance is also easy as we only have to change the styles in one place.
• Visual Studio editor features (Intellisense, Code completion & formatting) are available
• Styles specified using this approach are local to the component and don't collide with styles used
elsewhere in the application.
Option 4 : Specify the styles in the component TypeScript file using the @component decorator styles
property.
Advantages :
• Component can be easily reused as the styles are defined inline with in the component itself
• Application maintenance is also easy as we only have to change the styles in one place for this
component if we need to change them for any reason.
• Styles specified using this approach are local to the component and don't collide with styles used
elsewhere in the application.
Disadvantages :
• Visual Studio editor features (Intellisense, Code completion & formatting) are not available.
Option 5 : Specify the styles using the @component decorator styleUrls property. The
styleUrls property is an array of strings containing stylesheet URLs.
Advantages :
• Component can be easily reused as both the stylesheet itself and it's path are included
with in the component
• Application maintenance is also easy as we only have to change the styles in one place
• Visual Studio editor features (Intellisense, Code completion & formatting) are available
• Styles specified using this approach are local to the component and don't collide with
styles used elsewhere in the application.
ANGULAR INTERPOLATION
• Interpolation is all about data binding.
• Data binding classified into 3 categories.
One way data-binding - From Component to View Template
• To display read-only data on a view template we use one-way data binding.
• The component property name in the view template, enclosed in double curly braces:
{{propertyName}}.
• Program Execution (Interpolation).
Data Binding Description
One way data-binding From Component to View Template
One way data-binding From View Template to Component
Two way data-binding
From Component to View Template &
From View template to Component
Example :<h1>{{'Name = ' + firstName}}</h1>
Output : Name = Tom
We can specify any valid expression in double curly braces like
<h1>{{ 20 + 30 + 50 }}</h1>
Output :100
• Ternary Operator to display heading and No heading.
Example :<h1>{{firstName ? firstName : 'No Heading'}}</h1>
• Image Display using Interpolation and Property Bidning
• Creating methods and Functions (app.component.ts)
// create a method
fname:string='Angular2';
lname:string='Programming';
//create a function
getfullname(){
return this.fname+' '+this.lname;
app.component.html
<p>{{getfullname()}}</p>
Output : Angular2 Programming.
interpolation to set <img> src
• HTML :<img src={{imagepath}}><!--Interpolation-->
• TS Code :imagepath: string='https://blog.addthiscdn.com/wp-
content/uploads/2015/11/logo-facebook.png';
PROPERTY BINDING
• Interpolation to bind component class properties to view template.
• Another option to achieve exactly the same thing is by using Property
binding.
• we have bound imagePath property of the component class to <img> element
src property using interpolation.
• <img src={{imagepath}}>
• The <img> element src property is in a pair of square brackets, and the
component class property is in quotes.
• <img [src]="imagepath">
DIFFERENCE BETWEEN INTERPOLATION
AND PROPERTY BINDING
• Both Interpolation and Property binding flows a value in one direction, i.e from a
component's data property into a target element property.
• Interpolation is a special syntax that Angular converts into a property binding.
• Interpolation is just a convenient alternative to property binding.
• In some cases to concatenate strings ,we have to use interpolation instead of property
binding
• <img src="https://angular.io/{{imglink}}">
• When setting an element property to a non-string data value, you must use property
binding.
• <button [disabled]='isDisabled'>Click me!</button>
• If we use interpolation instead of property binding, the button is always disabled
irrespective of isDisabled class property value.
• <button disabled='{{isDisabled}}'>Click me!</button>
• Important points about Property Binding
• Enclose the property name with a pair of square brackets.
• If you omit the brackets, Angular treats the string as a constant and initializes the
target property with that string.
• Alternate syntax with bind- prefix instead of property binding is known as canonical
form
• <button bind-disabled='isDisabled'>Click me</button>
HTML ATTRIBUTE VS DOM PROPERTY
What is DOM?
• DOM stands for Document Object Model. When a browser loads a web page, the
browser creates a Document Object Model of that page.
• The browser creates a Document Object Model of that page as shown below
• DOM is an API for HTML.
• Programming languages like JavaScript or JavaScript frameworks like Angular to access
and manipulate the HTML using their corresponding DOM objects.
• In other words DOM contains the HTML elements as objects, their properties, methods and
events and it is a standard for accessing, modifying, adding or deleting HTML elements.
Interpolation example
<button disabled='{{isDisabled}}'>Click Me</button>
Property binding example
<button [disabled]='isDisabled'>Click Me</button>
• In above two examples, we are binding to the Button's disabled attribute. (Not true)
• We are actually binding to the disabled property of the button object.
• Angular data-binding is all about binding to DOM object properties and not HTML
element attributes.
What is the difference between HTML element attribute and DOM property
• Attributes are defined by HTML, where as properties are defined by the DOM.
• Attributes initialize DOM properties. Once the initialization complete, the attributes
job is done.
• Property values can change, where as attribute values can't.
Example :
<input id="inputId" type="text" value="Angular">
The web page and in the textbox ,We will see ‘Angular' as the value.
Launch the browser developer tools (F12)
On the 'Console' tab, use the getattribute() method and value property
of the input element to get the attribute and property values.
• inputId.getAttribute('value')
"Angular“
• inputId.value
• “Angular“
Change the value in the textbox to ”Programming”
• inputId.getAttribute('value')
"Angular“
• inputId.value
"Programming“
When we query for the attribute and property values, the
attribute value is still “Angular” but the property value is
“Programming”.
So it is important to keep in mind that,
• HTML attributes and the DOM properties are different
things.
• Angular binding works with properties and events, and not
attributes.
• The role of attributes is to initialize element properties and
their job is done.
ATTRIBUTE BINDING
• Interpolation and Property binding that deal with binding Component
class properties to HTML element properties and not Attributes.
• But not all the HTML elements having this properties.For
example, colspan attribute does not have corresponding property.
• In this case we want to bind HTML element attributes.
• With attribute binding we can set the value of an attribute directly.
• Use attribute binding only when there is no corresponding element
property to bind.
Program syntax:
• colspan attribute value to 2 in the HTML.
• If we use interpolation to bind columnSpan property of the component class to colspan
attribute of the <th> element we get the error - Can't bind to 'colspan' since it isn't a
known property of 'th‘
• <th colspan="{{columnSpan}}">
• We get the same error if we use Property Binding <th [colspan]="columnSpan">
• This error is because we do not have a corresponding property in the DOM for colspan
attribute.
• To fix this we have to use attribute-binding in Angular (colspan attribute). To tell angular
framework that we are setting an attribute value we have to prefix the attribute name
with attr and a DOT <th [attr.colspan]="columnSpan">
• The same is true when using interpolation
<th attr.colspan="{{columnSpan}}">
CLASS BINDING
• Add and remove CSS class names from an element's class attribute with a Class binding.
• Create CSS styles like
.boldClass{
font-weight:bold;
}
.italicsClass{
font-style:italic;
}
.colorClass{
color:red;
}
• Create a button in HTML page
<button class="colorClass">Submit</button>
the 'colorClass' is added to the button
• Replace all the existing css classes with one or more classes.
Example 1:
• HTML Code :<button class='colorClass' [class]='classesToApply'>My
Button</button>
• TS Code :classesToApply: string = 'italicsClass boldClass';
Example 2:
• HTML Code : <button class='colorClass' [class.boldClass]='applyBoldClass'>My
Button</button>
• TS Code : applyBoldClass: boolean = false;
• Adding or removing a single class :Include the prefix 'class' in a pair of square brackets,
followed by a DOT and then the name of the class that you want to add or remove.
• In the example adds boldClass to the button element. Notice it does not remove the
existing colorClass already added using the class attribute.
• If you change applyBoldClass property to false or remove the property.
ADD OR REMOVE MULTIPLE CLASSES USE NGCLASS DIRECTIVE
• ngClass is binded to addClasses() method.
• addClasses() method returns an object with 2 key/value pairs. The key is
a CSS class name. The value can be true or false. True to add the class
and false to remove the class.
• Since both the keys (boldClass & italicsClass) are set to true, both
classes will be added to the button element
STYLE BINDING
• Style binding syntax resembles property binding.
• style property name can be written in either dash-case or camelCase.
• For example, font-weight style can also be written using camel case -
fontWeight.
NgStyle directive
• ngStyle is binded to addStyles() method.
• addStyles() method returns an object with 2 key/value pairs. The key
is a style name, and the value is a value for the respective style
property or an expression that returns the style value.
EVENT BINDING
• The following bindings flow data in one direction i.e from a component class property to
an HTML element property.
1. Interpolation
2. Property Binding
3. Attribute Binding
4. Class Binding
5. Style Binding
• Flow data in Opposite direction i.e from an HTML element to a component.
• User actions like clicking on a button, hovering over an element, selecting from a
dropdownlist, typing in a textbox etc, then the corresponding event for that action is
raised.
• We need to know when user performs these actions. We can use angular event binding to
get notified when these events occur.
CLICK EVENT OF A BUTTON
• Within parentheses we have the target event, (click).
• onClick() method of the component class is called when the click event occurs.
• HTML Code: <button (click)="onClick()">Click me</button>
• TS Code : onClick(): void {
console.log('Button Clicked');
• Event binding is use of on- prefix alternative is known as canonical form.
• HTML Code: <button on-click="onClick()">Click me</button>
• Every time we click the button, 'Button Clicked' message is logged to the console.
EVENT BINDING EXAMPLE
• When we click "Show Details" button, we want to display "Gender" and "Age“.
• The text on the button should be changed to "Hide Details“.
• When we click "Hide Details" button, "Gender" and "Age" should be hidden and the button
text should be changed to "Show Details".
• To achieve this by using one of the structural directives "ngIf" in angular.
• "showDetails" boolean property. The default value is false, so when the page first loads.
• we will have "Gender" and "Age" hidden. We also have a method, toggleDetails(), which
toggles the value of showDetails.
• TS Syntax:
columnSpan: number = 2;
firstName: string = 'Suresh';
lastName: string = 'Babu';
gender: string = 'Male';
age: number = 20;
showDetails: boolean = false;
toggleDetails(): void {
this.showDetails = !this.showDetails;
}
Program Explanation :
• click event of the button is binded to toggleDetails() method.
• To dynamicall change the text on the button, we are using ternary operator -
{{showDetails ? 'Hide' : 'Show'}} Details.
• Use the ngIf structural directive on "Gender" and "Age" <tr> elements.
• The * prefix before a directive indicates, it is a structural directive.
• The ngIf directive adds or removes content from the DOM based on expression is
true or false.
• If "showDetails" is true, "Gender" and "Age" <tr> elements are added to the DOM,
else removed.
TWO-WAY DATA BINDING
• Name : <input [value]='name'>-Binds component class "name" property to the
input element’s value property.
• You entered : {{name}} - Interpolation displays the value we have in "name" property
on the web page
• when we change the value in the textbox, that changed value is not reflected in the
browser.
• Binding to the input event of the input control as shown below.
• Name :<input [value]='firstname' (input)='firstname =
$event.target.value'>
• You entered : {{firstname}}
PROGRAM EXPLANATION
• [value]=‘firstname’-This property binding flows data from the component class to
element property .
• (input)='firstname = $event.target.value: Event binding flows data in the
opposite direction i.e from the element to component class property "name“
• $event - event binding, and contains the event data.
• name = $event.target.value - This expression updates the value in the name property
in the component class.
• {{name}} - This interpolation expression will display the value on the web page.
• two-way data binding in Angular is a combination of both Property Binding and
Event Binding.
NGMODEL DIRECTIVE
• Two-way data binding angular has provided ngModel directive.
• Name : <input [(ngModel)]='name'>
• You will get the following error
Template parse errors:
Can't bind to 'ngModel' since it isn't a known property of 'input‘.
• ngModel directive is, in an Angular system module called FormsModule.
• we have to import FormsModule in our root module.
• Steps to import FormsModule into our AppModule
1. Open app.module.ts file.
2. Include the following import statement in it
import { FormsModule } from '@angular/forms';
3. Also, include FormsModule in the 'imports' array of @NgModule
imports: [BrowserModule,FormsModule],
POINTS TO REMEMBER
• The square brackets on the outside for property binding
• The parentheses on the inside for event binding
• To easily remember this syntax, compare it to a banana in a box [( )]
(Banana box).
ANGULAR NGFOR DIRECTIVE
• we want display employees in a table on a web page as shown below.
Take an array of Employee objects.
export class NgForComponent {
employees: any[] = [
{ ID: 'LAKSHYA121', name: 'Sowmya', gender: 'Female', annualSalary: 15500, dateOfBirth:
'25/06/1996' },
{ ID: 'LAKSHYA122', name: 'Ravi', gender: 'Male', annualSalary: 18700.95, dateOfBirth:
'9/06/1990' },
{ ID: 'LAKSHYA123', name: 'Vasundhara', gender: 'Female', annualSalary: 22000, dateOfBirth:
'12/08/1988' },
{ ID: 'LAKSHYA124', name: 'Venkat Reddy', gender: 'Male', annualSalary: 16500.123, dateOfBirth:
'14/10/1992'},
{ ID: 'LAKSHYA125', name: 'Venkatesh', gender: 'Male', annualSalary: 20000.826, dateOfBirth:
'14/06/1989'},
];
}
<tr *ngFor='let employee of employees'>
<td>{{employee.ID}}</td>
<td>{{employee.name}}</td>
<td>{{employee.gender}}</td>
<td>{{employee.annualSalary}}</td>
<td>{{employee.dateOfBirth}}</td>
</tr>
Explanation:
• ngFor is used to display an array of items.
• ngFor is a structural directive (prefixed with *)
• *ngFor=‘let employee of employees.’
• ngFor can repeat items for any iterable object.
ANGULAR NGFOR TRACKBY
1.Usage of trackyBy with ngFor directive
2.Get the index of an item in a collection
3. Identifying the first and the last elements in a collection
4. Identifying even and odd elements in a collection
Using trackyBy with ngFor directive :
• ngFor directive may perform poorly with large lists
• A small change to the list like, adding a new item or removing an existing item may
trigger a cascade of DOM manipulations
• The employees array initializes the employees property with 5 employee objects
getEmployees() method returns another list of 7 employee objects ( 2 new new employee
objects)
• the moment we are not using trackBy with ngFor directive
When the page initially loads we see the 5 employees
• When we click "Refresh Employees" button we see the sixth and seventh employees as
well.
• It looks like it just added the additional row for the sixth and seventh employees. That's
not true, it effectively teared down all the <tr> and <td> elements of all the employees
and recreated them.
• To confirm this launch browser developer tools by pressing F12.
• Click on the "Elements" tab and expand the <table> and then <tbody> elements
• At this point click the "Refresh Employees" button and you will notice all
the <tr>elements are briefly highlighted indicating they are teared down and recreated.
• This happens because Angular by default keeps track of objects using the object
references.
• When we click "Refresh Employees" button we get different object references and as a
result and all the old DOM elements and insert the new DOM elements.
• Angular can avoid this with trackBy.
• The trackBy function takes the index and the current item as arguments and returns the
unique identifier by which that item should be tracked.(Employee Code)
• trackByEmpCode(index: number, employee: any): string {
return employee.code;
• <tr *ngFor='let employee of employees trackBy:trackByEmpCode'>
• At this point, run the application and launch developer tools. When you click "Refresh
Employees" first time, only the the rows of the sixth and seventh employees is highlighted
indicating only that<tr> element is added.
INDEX OF AN ITEM IN A COLLECTION
• let i=index
It is used to display the index of an element.
• let isFirst = first;
• let isLast = last’
Used to display the Boolean properties for first and last elements.
• let isEven = even;
• let isOdd = odd‘
Used to display the Boolean properties for even and odd elements.
PIPES
• Transform data before display.
• A pipe takes in data as input and transforms it to a desired output.
• Built in pipes include lowercase, uppercase, decimal, date, percent,
currency etc.
Pipe URL
Date https://angular.io/api/common/DatePipe
Decimal https://angular.io/api/common/DecimalPipe
Currency https://angular.io/api/common/CurrencyPipe
Percent https://angular.io/api/common/PercentPipe
EXAMPLES
• Lower case filter
• {{product.ProductID|lowercase}}
• Upper case filter
• {{product.ProductName|uppercase}}
• Currency Filter
• {{product.ProductPrice|currency:"INR"}}
• Date filter
• {{product.ReleaseDate|date :'fullDate'}}
Parameterizing a pipe
• If the pipe accepts multiple parameters, separate the values with
colons
• {{appValue|Pipe1: parameter1: parameter2 }}
Chaining pipes
• We can chain multiple pipes together.
• Apply the pipes one after another
CUSTOM PIPES
We can write your own custom pipes.
Steps to create Custom Pipes :
1) Create a pipe file, (i.e custompipe.pipe.ts)
2) Every pipe component will have to import the pipe from the Angular core.
3) Apply the @pipe decorator, Which imports form the core angular library.
4) Define the pipe metadata i.e A pipe is a class decorated with pipe metadata.
5) Create the Component class. It should have the transform function, which holds the
business logic of what the pipe should do.
The Pipe Transform interface
The transform method is the essential to a pipe. The Pipe Transform interface defines that
method guides both tooling and the compiler.
Note :You must include your pipe in the declarations array of the AppModule.
PURE AND IMPURE PIPES
• There are two categories of pipes: pure and impure.
• Pipes are pure by default. You make a pipe impure by setting its pure flag to false.
Pure Pipe
• Angular executes a pure pipe only when it detects a pure change to the input value.
• It will not remember or trace any of the previous values or states.
• A pure change is either a change to a primitive input value (String, Number,
Boolean, symbol) or a changed object reference (Date, Array, Function, Object).
• Angular ignores changes within (composite) objects. It won't call a pure pipe if you
change an input month, add to an input array, or update an input object property.
Impure pipes
• Angular executes an impure pipe during every component change detection cycle.
• An impure pipe is called often, as often as every keystroke or mouse-move.
pure :false
COMPONENT INTERACTION/COMPONENT COMMUNICATION
It can be done by two ways
1) Pass data to child component
2) Pass data to parent component
• In Angular Parent Component can communicate with the child component by setting its
Property.
• To do that the Child component must expose its properties to the parent component.
• The Child Component does this by using the @Input decorator.
The Child Component
• Import the @Input module from @angular/Core Library
• Mark those property, which you need data from parent as input property using @Input
decorator
The Parent Component
• Bind the Child component property in the Parent Component when instantiating the Child
@INPUT
• The @Input Decorator is used to configure the input properties of the
component.
• When you mark a property as input property, then the Angular injects
values into the component property using Property Binding.
• The Binding Target (Property of the child component) is placed inside the
square brackets.
@Input example
• A counter which is incremented by the Parent Component.
• The Parent Component then passes this counter to the child component
for display.
THE CHILD COMPONENT WITH @INPUT DECORATOR
Create the ChildComponent.
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-childcomponent',
template: `<h2>Child Component</h2>
current count is {{ count }}`,
styleUrls: ['./childcomponent.component.css']
})
export class ChildcomponentComponent {
@Input() count: number;
}
Step 1 : import the @Input decorator from @angular/core
import { Component, Input } from '@angular/core';
Step 2 :Define the inline template for the child component, where it displays the current
count.
Component({
selector: 'app-childcomponent',
template: `<h2>Child Component</h2>
current count is {{ count }}`,
Step 3 :The Child Component expects the count to come from the Parent Component.
ChildComponent decorate the count property with @Input decorator.
export class ChildcomponentComponent {
@Input() count: number;
}
Bind to Child Property in Parent Component
Now, time to pass the Count values to the Child Component from the Parent.
import { Component, OnInit } from '@angular/core';
import { ChildcomponentComponent } from
"./childcomponent/childcomponent.component";
@Component({
selector: 'app-componentinteraction',
template: `<h1>Welcome to {{title}}!</h1>
<button (click)="increment()">Increment</button>
<button (click)="decrement()">decrement</button>
<app-childcomponent [count]=Counter></app-childcomponent>` ,
styleUrls: ['./componentinteraction.component.css']
})
export class ComponentinteractionComponent {
title = 'Component Interaction';
Counter = 5;
increment() {
this.Counter++;
}
decrement() {
this.Counter--;
}
}
The inline template in the Parent Component has two buttons. The Buttons Increments/decrements the counter.
<button (click)="increment()">Increment</button>
<button (click)="decrement()">decrement</button>
we are using count property, which is a property of the child Component inside the square bracket. We bind it to
Counter property of the Parent Component.
<app-childcomponent [count]=Counter></app-childcomponent>
Finally, we will add counter in Parent component and set it to 5 as shown below.
export class ComponentinteractionComponent {
title = 'Component Interaction';
Counter = 5;
increment() {
this.Counter++;
}
decrement() {
this.Counter--;
}
}
PASS DATA TO PARENT COMPONENT
• we will learn how to Pass data to Parent Component from Child
Component in Angular.
• The Child can send data to Parent by raising an event, Parent can interact
with the child via local variable or Parent can call @ViewChild on the
child.
Pass data to parent component
• There are three ways in which parent component can interact with the
child component.
• Parent Listens to Child Event.
• Parent uses Local Variable to access the child.
• Parent uses a @ViewChild to get reference to the child component.
Parent listens for child event
• The Child Component exposes an EventEmitter Property. This Property is
adorned with the @Output decorator.
• When Child Component needs to communicate with the parent it raises the
event. The Parent Component listens to that event and reacts to it.
EventEmitter Property
• To Raise an event, the component must declare an EventEmmitter Property.
The Event can be emitted by calling the .emit() method.
Example :
@Output() countChanged: EventEmitter<number> = new EventEmitter();
• Then call emit method passing the whatever the data you want to send.
this.countChanged.emit(this.count);
@OUTPUT DECORATOR
• Using the EventEmitter Property gives the components ability to raise an event.
• But the event accessible from parent component, you must decorate the property with
@Output decorator.
How to Pass data to parent component using @Output
In the child component
1.Declare a property of type EventEmitter and initiate it.
2.Mark it with a @Output annotation.
3.Raise the event passing it with the desired data.
In the Parent Component
1.Bind to the Child Component using Event Binding and listen to the child events
2.Define the event handler function.
Example Explanation: (Passing data to parent component Via Events (Example)).
• we built a counter in the parent component.
• We assigned the initial value to the counter and added increment/decrement methods.
• In the child Component, we used the @Input decorator to bind count property to the parent
component.
• Whenever parent count is changed in the parent the child component is updated and
displayed the count.
• we will move the counter to the child component. We will raise an event in the child
component whenever the count is increased or decreased.
• We then bind to that event in the parent component and display the count in the parent
component.
PARENT USES LOCAL VARIABLE TO ACCESS THE CHILD IN TEMPLATE
• Parent Template can access the child component properties and methods by creating the template reference variable.
Child component
import { Component} from '@angular/core';
@Component({
selector: 'child-component',
template: `<h2>Child Component</h2>
current count is {{ count }} `
})
export class ChildComponent {
count = 0;
increment() {
this.count++;
}
decrement() {
this.count--;
}
}
• We have removed the input, output & eventemiitter.
• Our component is now have property count and two methods to increment and decrement it
Parent Component
import { Component} from '@angular/core';
@Component({
selector: 'app-root',
template: `
<h1>{{title}}!</h1>
<p> current count is {{child.count}} </p>
<button (click)="child.increment()">Increment</button>
<button (click)="child.decrement()">decrement</button>
<child-component #child></child-component>` ,
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Parent interacts with child via local variable';
}
PARENT USES A @VIEWCHILD() TO GET REFERENCE TO THE CHILD
COMPONENT
• Injecting an instance of the child component into the parent as a @ViewChild is the
another technique used by the parent to access the property and method of the child
component.
• The @ViewChild decorator takes the name of the component/directive as its input. It
is then used to decorate a property.
• The Angular then injects the reference of the component to the Property.
Child Component
• There is no change in the child component
Parent Component
import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from './child.component';
Parent Component :
@Component({
selector: 'app-root',
template: `
<h1>{{title}}</h1>
<p> current count is {{child.count}} </p>
<button (click)="increment()">Increment</button>
<button (click)="decrement()">decrement</button>
<child-component></child-component>` ,
})
export class AppComponent {
title = 'Parent calls an @ViewChild()';
@ViewChild(ChildComponent) child: ChildComponent;
increment() {
this.child.increment();
}
decrement() {
this.child.decrement();
}
} https://www.tektutorialshub.com/angular-pass-data-to-parent-component/
COMPONENT LIFE CYCLE HOOKS
• The life cycle hooks are the methods that angular invokes on directives and components
as it creates, changes, and destroys them.
• Using life-cycle hooks we can fine tune the behavior of our components during creation,
update, and destruction.
What is Angular Component lifecycle hooks
• When the angular application starts it creates and renders the root component. Then
creates and renders it’s Children.
• For each loaded component, it checks when its data bound properties change and updates
them. It destroys the component and removes it from the DOM when no longer in use.
• The Angular life cycle hooks are nothing but callback function, which angular invokes
when a certain event occurs during the component’s life cycle.
For example
• When component is initialized, Angular invokes ngOnInit
• When a component’s input properties change, Angular invokes ngOnChanges
• When a component is destroyed, Angular invokes ngOnDestroy
Angular lifecycle hooks
Here is the complete list of life cylce hooks provided by the Angular
• ngOnChanges - called when an input binding value changes.
• ngOnInit - after the first ngOnChanges.
• ngDoCheck - after every run of change detection.
• ngAfterContentInit - after component content initialized.
• ngAfterContentChecked - after every check of component content.
• ngAfterViewInit - after component's view(s) are initialized.
• ngAfterViewChecked - after every check of a component's view(s).
• ngOnDestroy - just before the component is destroyed.
1) ngOnChanges :The Angular invokes this life cycle hook whenever any data-bound
property of the component or directive changes.
Example :Passing data to child component.
2) ngOnInit:when the component is created for the first time and called after the
constructor and first ngOnChanges hook.
Initialisation logic for your component.
ngOnChanges hook is fired before ngOnInit. Which means all the input properties are
available to use when the ngOnInit is hook is called.
This hook is fired only once
3) ngDoCheck: after the ngOnInit.
On every change made to the component properties, the event is raised or change in
value of properties.
This hook is executed for every change detection in cycles even there is no properties
change.
4) ngAfterContentInit :This Life cycle hook is called after the Component’s content has
been fully initialized.
5) ngAfterContentChecked:called after the Components Content is checked by the
Angular’s Change detection module.
It is called immediately after ngAfterContentInit and after every subsequent
ngDoCheck().
6) ngAfterViewInit :Similar to ngAfterContentInit, but invoked after Angular
initializes the component’s views and all its child views. This is Called once after the
first ngAfterContentChecked.
7) ngAfterViewChecked:The Angular fires this hook after it checks the component’s
views and child views.
This event is fired after the ngAfterViewInit and after that for every subsequent
ngAfterContentChecked hook.
8) ngOnDestroy:This hook is called just before the Component/Directive instance is
destroyed by Angular.
Perform any cleanup logic for the Component.
This is the correct place to Unsubscribe Observables and detach event handlers to
avoid memory leaks.
How to Use Lifecycle Hooks
• Import Hook interfaces
• Declare that Component/directive Implements lifecycle hook interface
• Create the hook method (e.g. ngOnOnChanges)
Read more : https://angular.io/guide/lifecycle-hooks
DEPENDENCY INJECTION
• Dependency Injection (DI) is a technique in which we provide an instance of an object to
another object, which depends on it. This is technique is also known as “Inversion of
Control” (IoC)
• Dependency Injection(DI) is a coding pattern in which a class receives dependencies
rather than creating them itself.
Why we absolutely need DI:
• DI is a software design pattern in which a class receives its dependencies rather than
creating the object itself.
• DI creates and delivers objects, which are required dynamically just-in-time
• We can consider the injectables as our application's reusable repository
• DI allows independent development of dependency modules for remote development
teams.
SERVICES
• services or factories helps to achieve reusability in code and enables us to share the
application-specific logic across the application blocks, such as components,
directives, and so on.
What services are user for
• Features that are independent of components such a logging services.
• Share logic across components
• Encapsulate external interactions like data access
Advantageous of Service
• Services are easier Test.
• Services are easier to Debug.
• You can reuse the service.
How to create a Service in Angular 2
• An Angular 2 service is simply a javascript function means create a class and add methods &
properties.
• We can then create an instance of this class in our component and call its methods.
• One of the best uses of services is to get the data from the data source.
Example explanation :
Step 1 ) Product ( create product.ts file)
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;
}
Step 2) Product Service ( Create 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',1000),
]
return products;
}
}
Step 3) Invoking the ProductService(Open the app.componet.ts)
import { ProductService } from "./product.service";
import { Product } from "./product";
@Component({
selector: 'app-service',
templateUrl: './service.component.html',
})
export class ServiceComponent {
products:Product[];
productService;
constructor(){
this.productService=new ProductService();
}
getProducts() {
this.products=this.productService.getProducts();
}
}
Step 4) Template(Open the app.component.html file )
<div class="container">
<h1 class="heading"><strong>Services </strong>Demo</h1>
<button type="button" class="btn btn-outline-primary"
(click)="getProducts()">Get Products</button>
<br> <br>
<div class='table-responsive'>
<table class='table'>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let product of products;">
<td>{{product.productID}}</td>
<td>{{product.name}}</td>
<td>{{product.price | currency:"INR":true}}</td>
</tr>
</tbody>
</table>
</div>
</div>
ROUTING
What is Routing
Routing allows you to move from one part of the application to another part or one View to
another View.
The Angular Router Module
The Router is a separate module in Angular. It is in its own library package, @angular/router.
Routing allows you to:
• Maintain the state of the application
• Implement modular applications
• Implement the application based on the roles (certain roles have access to certain URLs)
CONFIGURING ROUTES
Base URL Tag
• The Base URL tag must be set within the <head> tag of index.html:<base href="/">
Route Definition Object
The Routes type is an array of routes that defines the routing for the application.
• Each route can have different attributes; some of the common attributes are:
• path - URL to be shown in the browser when application is on the specific route
• component - component to be rendered when the application is on the specific route
• redirectTo - redirect route if needed; each route can have either component or redirect
attribute defined in the route (covered later in this chapter)
• pathMatch - optional property that defaults to 'prefix'; determines whether to match full
URLs or just the beginning. When defining a route with empty path string set pathMatch to
'full', otherwise it will match all paths.
• children - array of route definitions objects representing the child routes of this route
(covered later in this chapter).
• To use Routes, create an array of route configurations.
export const routes: Routes = [
{ path: '', redirectTo : '/',pathMatch : 'full'},
{ path: 'componentOne', component : ComponentOne},
{ path: 'componentTwo', component : ComponentTwo}
];
RouterModule
RouterModule.forRoot takes the Routes array as an argument and returns a
configured router module
• export const routing = RouterModule.forRoot(routes);
• We then import our routing configuration in the root of our application.
Open app.module.ts
1) import { routing } from './app.routes';
2) Imports include ‘routing’
Redirecting the Router to Another Route
When your application starts, it navigates to the empty route by default. We can configure the
router to redirect to a named route by default:
{ path: '', redirectTo : '/',pathMatch : 'full'},
Defining Links Between Routes
Add links to routes using the routerLink Directive.
<nav>
<a routerLink = '/componentOne'> Component One</a>
<a routerLink = '/componentTwo'> Component Two</a>
</nav>
DYNAMICALLY ADDING ROUTE COMPONENTS
• Angular dynamically adds the component for the route being activated into the
<router-outlet></router-outlet> element.
• router-outlet which serves as a component placeholder.
https://angular-2-training-book.rangle.io/handout/routing/why_routing.html
FORMS FUNDAMENTALS & CONCEPTS
• Forms are used to collect the data from the user.It can contain large no of
input fields, Spanning multiple tabs.
• Forms may also contain complex validation logic interdependent on
multiple fields.
Forms are expected to do
• Initialise the forms fields and present it to the user
• Capture the data from the user
• Track changes made to the fields
• Validate the inputs
• Display helpful errors to the user
ANGULAR 2 FORMS MODULE
• Froms module the two-way data binding & event binding bind the form field to
the Angular 2 component class.
• It tracks changes made to the form fields so that we can respond accordingly.
• Angular forms provide the built-in validators to validate the inputs and we can create
your own custom validators.
• Finally, it encapsulates all the input fields into an object structure when the user
submits the form.
Angular 2 takes two approaches to building the forms.
1) Template driven forms
2) Model driven forms
1) Template driven forms approach: Easiest way to build the Angular 2 forms. The logic
of the form is placed in the template. (Angular 1).
2) Model-driven forms approach: The logic of the form is placed in the component. The
Model driven approach has more benefits as it makes the testing of the component
easier.
Building Blocks of Angular 2 Forms
1) FormControl :A FormControl represents a single input field in an Angular form.
2) FormGroup :FormGroup is a group of FormControl instances.
3) FormArray :The FormArray‘s are array of FormControl’s.
The FormArray’s are very much similar to FormGroups. Here FormControls are
represented as an array of objects.
TEMPLATE DRIVEN FORMS
• we will add few input fields in our Form and bind it to Angular Forms Module
using ngModel directive.
• Then, we will submit the data to the OnSubmit method in the Component class.
What is a Template Driven Forms
• Angular 2 Template driven forms are similar to the forms are built in Angular 1.
• We used directives like ngModel in our templates and let Angular handle everything
(Angular 1).
• We also used HTML5 validation attributes like required, maxlength or built our own
custom directives to achieve validations.
Angular 2 template-driven forms, we need to tell our @NgModule to use the FormsModule from @angular/forms. In the app.module.ts file.
Building the Template
<div class="container">
<form #contactForm="ngForm" (ngSubmit)="onSubmit(contactForm)" >
<div class="form-group">
<label for="firstname">First Name</label>
<input type="text" class="form-control" name="firstname" ngModel>
</div>
<div class="form-group">
<label for="lastname">Last Name</label>
<input type="text" class="form-control" name="lastname" ngModel>
</div>
<div class="form-group">
<button type="submit">Submit</button>
</div>
<h2> <pre>{{contactForm.value | json }} </pre> </h2>
</form>
</div>
ngForm Directive
• The ngForm directive makes the Angular 2 Template driven Forms work.(no need to
add it explicitly).
• When we include FormsModule, the Angular is going to look out for any <form>tag
in our HTML template.
• Angular does this via ngForm directive.
• ngForm directive automatically detects the <form> tag and automatically binds to
it.
• ngForm directive creates a top-level FormGroup instance and binds it to the form to
track aggregate form value and validation status.
FormControl
ngModel will use the name attribute to create the FormControl instance for each of
the Form Field it is attached.
FormGroup
• The FormGroup is a collection of FormControl.
• ngForm directive by assigning it to the Local Template Variable (#contactForm).
<form #contactForm ="ngForm">
Submit data to Component
<form #contactForm="ngForm" (ngSubmit)="onSubmit(contactForm)" >
• The Form data is submitted to the Component using the Angular directive
named ngSubmit.
• We are using event binding (parentheses) to bind ngSubmit to OnSubmit method in
the component class.
• We have a submit button in our form. The ngSubmit will fire when the user clicks on
the submit button.
• We are passing the Local Template Variable contactForm in onSubmit method.
contactForm holds the reference the ngForm directive.
• We can use this in our component class to extract the Data from the Form Fields.
• we have added {{contactForm.value | json }} at the end.
• we can see the value exposed by the contactForm.value method as you input into
the form fields.
Receive the data in Component class
• onSubmit method receives the reference to the ngForm directive, which we named is
as contactForm.
• The contactForm exposes the value method which returns the form fields as Json
object.
• use log it to the console using the console.log(contactForm.value);
VALIDATION IN TEMPLATE DRIVEN FORMS
The Angular forms architecture supports two ways to validate the Form.
1) Built-in validation
2) Custom validation
1) Built-in Validators
• The Angular Built-in validators use the HTML5 validation attributes
like required, minlength, maxlength & pattern.
• Angular 2 interprets these validation attributes and add the validator functions to
FormControl.
HOW TO ADD BUILT-IN VALIDATORS
Disabling the Browser validation
• <form #contactForm="ngForm" (ngSubmit)="onSubmit(contactForm)" >
Adding Required Validator
• <input type="text" class="form-control" name="firstname" ngModel
#firstname="ngModel" required minlength="4" >
• We will notice that clicking on the Submit button submits the form. We need to tell
angular not to submit the form unless the form is valid.
Disable Submit button
• We need to disable the submit button if our form is not valid.
Displaying the Validation/Error messages
<div *ngIf="!firstname?.valid && (firstname?.dirty ||firstname?.touched)"
class="alert alert-danger">
<div [hidden]="!firstname.errors.required">
First Name is required
</div>
MODEL DRIVEN FORMS
• Model Driven Forms are also known as reactive forms.
• The form is built in the component class, unlike Template Driven Model where
the model is built in templates.
Advantages of Angular 2 Model Driven Forms
• Used to enable us to test our forms without being required to rely on end-to-end tests.
• The model driven Forms allows you to have an ability to setup validation rules in code
rather than as directive in Template.
• We can subscribe to field value changes in your code. Since everything happens in
Component class, you can easily write unit Tests.
HOW TO CREATE ANGULAR 2 MODEL DRIVEN FORMS
Enabling Model Driven Forms
• We need to import ReactiveFormsModule instead of FormModule to make use of Model
Driven Forms.
• We should also add the ReactiveormsModule to the imports metadata property array.
import { ReactiveFormsModule } from '@angular/forms';
Building the Model
• In the Template driven approach, we used ngModel & ngModelGroup directive on the
HTML elements, which created the FormGroup & FormControl instances behind the
scene.
• In the Model Driven approach, it is our responsibility to create the FormGroup
and FormControl
• FormControl encapsulates the state of a single form element in our form. It stores the
value and state of the form element and helps us to interact with them using properties
& methods.
• FormGroup represents a collection of FormControls. In fact, an angular form is
a FormGroup.
• First, we need to import FormGroup, FormControl & Validator from the angular/forms.
import { FormGroup, FormControl,FormBuilder,Validators } from
'@angular/forms';
FormGroup
contactForm = new FormGroup({})
The FormGroup takes 3 arguments. a collection of child FormControl, a validator, and an
asynchronous validator. The Validators are optional.
FormControl
FormGroup is the collection of child FormControl.
contactForm = new FormGroup({
firstname: new FormControl(),
lastname: new FormControl(),
})
Binding the template to the model
<form [formGroup]="contactForm">
We have used the square bracket (one-way binding) around FormGroup directive and
set that equal the model.
Submitting the form
<form [formGroup]="contactForm" (ngSubmit)="onSubmit()">
MODEL DRIVEN FORMS VALIDATION
1) Built-in Validators
2) Adding Required Validator
this.contactForm = this.fb.group({
firstname: ['',[ Validators.required,Validators.minLength(10)]],
lastname: ['',[ Validators.required,Validators.minLength(5)]],
address: this.fb.group({
city:[],
street: [],
pincode: [ ]
})
});
Disable Submit button
<button type="submit" [disabled]="!contactForm.valid">Submit</button>
Displaying the Validation/Error messages
• Angular creates a FormControl for each and every field, which has ngModel directive
applied. The FormControl exposes the state of form element like valid, dirty, touched
etc.
Adding Minlength Validator
Let us make the minimum length of the First Name to 10.
<div [hidden]="!contactForm.controls.firstname.errors.minlength">
First Name Minimum Length is
{{contactForm.controls.firstname.errors.minlength?.requiredLength}}
</div>

Weitere ähnliche Inhalte

Was ist angesagt?

JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...Edureka!
 
Angular components
Angular componentsAngular components
Angular componentsSultan Ahmed
 
Selenium IDE Tutorial For Beginners | Selenium IDE Tutorial | What Is Seleniu...
Selenium IDE Tutorial For Beginners | Selenium IDE Tutorial | What Is Seleniu...Selenium IDE Tutorial For Beginners | Selenium IDE Tutorial | What Is Seleniu...
Selenium IDE Tutorial For Beginners | Selenium IDE Tutorial | What Is Seleniu...Simplilearn
 
An overview of selenium webdriver
An overview of selenium webdriverAn overview of selenium webdriver
An overview of selenium webdriverAnuraj S.L
 
Angular - Chapter 1 - Introduction
 Angular - Chapter 1 - Introduction Angular - Chapter 1 - Introduction
Angular - Chapter 1 - IntroductionWebStackAcademy
 
Testing of React JS app
Testing of React JS appTesting of React JS app
Testing of React JS appAleks Zinevych
 
Angular Advanced Routing
Angular Advanced RoutingAngular Advanced Routing
Angular Advanced RoutingLaurent Duveau
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets Hitesh-Java
 
Angular 10 course_content
Angular 10 course_contentAngular 10 course_content
Angular 10 course_contentNAVEENSAGGAM1
 
Automation - web testing with selenium
Automation - web testing with seleniumAutomation - web testing with selenium
Automation - web testing with seleniumTzirla Rozental
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced JavascriptAdieu
 
Introduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectIntroduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectJadson Santos
 
Building blocks of Angular
Building blocks of AngularBuilding blocks of Angular
Building blocks of AngularKnoldus Inc.
 

Was ist angesagt? (20)

JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
 
Angular components
Angular componentsAngular components
Angular components
 
Angular
AngularAngular
Angular
 
Selenium IDE LOCATORS
Selenium IDE LOCATORSSelenium IDE LOCATORS
Selenium IDE LOCATORS
 
Selenium IDE Tutorial For Beginners | Selenium IDE Tutorial | What Is Seleniu...
Selenium IDE Tutorial For Beginners | Selenium IDE Tutorial | What Is Seleniu...Selenium IDE Tutorial For Beginners | Selenium IDE Tutorial | What Is Seleniu...
Selenium IDE Tutorial For Beginners | Selenium IDE Tutorial | What Is Seleniu...
 
An overview of selenium webdriver
An overview of selenium webdriverAn overview of selenium webdriver
An overview of selenium webdriver
 
Angular - Chapter 1 - Introduction
 Angular - Chapter 1 - Introduction Angular - Chapter 1 - Introduction
Angular - Chapter 1 - Introduction
 
TypeScript
TypeScriptTypeScript
TypeScript
 
Testing of React JS app
Testing of React JS appTesting of React JS app
Testing of React JS app
 
Angular Advanced Routing
Angular Advanced RoutingAngular Advanced Routing
Angular Advanced Routing
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
 
Angular 10 course_content
Angular 10 course_contentAngular 10 course_content
Angular 10 course_content
 
Java collection
Java collectionJava collection
Java collection
 
Automation - web testing with selenium
Automation - web testing with seleniumAutomation - web testing with selenium
Automation - web testing with selenium
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Angular Observables & RxJS Introduction
Angular Observables & RxJS IntroductionAngular Observables & RxJS Introduction
Angular Observables & RxJS Introduction
 
Selenium WebDriver
Selenium WebDriverSelenium WebDriver
Selenium WebDriver
 
Introduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectIntroduction to angular with a simple but complete project
Introduction to angular with a simple but complete project
 
Building blocks of Angular
Building blocks of AngularBuilding blocks of Angular
Building blocks of Angular
 
C# in depth
C# in depthC# in depth
C# in depth
 

Ähnlich wie Complete Notes on Angular 2 and TypeScript

Ähnlich wie Complete Notes on Angular 2 and TypeScript (20)

C#
C#C#
C#
 
2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)
 
Presentation 2nd
Presentation 2ndPresentation 2nd
Presentation 2nd
 
Typescript language extension of java script
Typescript language extension of java scriptTypescript language extension of java script
Typescript language extension of java script
 
Introduction of C# BY Adarsh Singh
Introduction of C# BY Adarsh SinghIntroduction of C# BY Adarsh Singh
Introduction of C# BY Adarsh Singh
 
C#ppt
C#pptC#ppt
C#ppt
 
Introduction to TypeScript by Winston Levi
Introduction to TypeScript by Winston LeviIntroduction to TypeScript by Winston Levi
Introduction to TypeScript by Winston Levi
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 
Java Fx
Java FxJava Fx
Java Fx
 
Objective c slide I
Objective c slide IObjective c slide I
Objective c slide I
 
Java script basic
Java script basicJava script basic
Java script basic
 
Getting started with typescript
Getting started with typescriptGetting started with typescript
Getting started with typescript
 
Unit 1 question and answer
Unit 1 question and answerUnit 1 question and answer
Unit 1 question and answer
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programming
 
Structured Languages
Structured LanguagesStructured Languages
Structured Languages
 
Understanding linq
Understanding linqUnderstanding linq
Understanding linq
 
JavaScript.pptx
JavaScript.pptxJavaScript.pptx
JavaScript.pptx
 
DITEC - Programming with C#.NET
DITEC - Programming with C#.NETDITEC - Programming with C#.NET
DITEC - Programming with C#.NET
 
TypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation GuideTypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation Guide
 
js.pptx
js.pptxjs.pptx
js.pptx
 

Mehr von EPAM Systems

Css Complete Notes
Css Complete NotesCss Complete Notes
Css Complete NotesEPAM Systems
 
Css3 Complete Reference
Css3 Complete ReferenceCss3 Complete Reference
Css3 Complete ReferenceEPAM Systems
 
HTML 5 Complete Reference
HTML 5 Complete ReferenceHTML 5 Complete Reference
HTML 5 Complete ReferenceEPAM Systems
 
Jquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript BasicsJquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript BasicsEPAM Systems
 
Bootstrap PPT Part - 2
Bootstrap PPT Part - 2Bootstrap PPT Part - 2
Bootstrap PPT Part - 2EPAM Systems
 
Bootstrap Part - 1
Bootstrap Part - 1Bootstrap Part - 1
Bootstrap Part - 1EPAM Systems
 
Angular Js Get Started - Complete Course
Angular Js Get Started - Complete CourseAngular Js Get Started - Complete Course
Angular Js Get Started - Complete CourseEPAM Systems
 
Angular Js Advantages - Complete Reference
Angular Js Advantages - Complete ReferenceAngular Js Advantages - Complete Reference
Angular Js Advantages - Complete ReferenceEPAM Systems
 

Mehr von EPAM Systems (10)

Css Complete Notes
Css Complete NotesCss Complete Notes
Css Complete Notes
 
Css3 Complete Reference
Css3 Complete ReferenceCss3 Complete Reference
Css3 Complete Reference
 
Bootstrap 4 ppt
Bootstrap 4 pptBootstrap 4 ppt
Bootstrap 4 ppt
 
HTML 5 Complete Reference
HTML 5 Complete ReferenceHTML 5 Complete Reference
HTML 5 Complete Reference
 
Jquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript BasicsJquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript Basics
 
Bootstrap PPT Part - 2
Bootstrap PPT Part - 2Bootstrap PPT Part - 2
Bootstrap PPT Part - 2
 
Bootstrap Part - 1
Bootstrap Part - 1Bootstrap Part - 1
Bootstrap Part - 1
 
Angular Js Get Started - Complete Course
Angular Js Get Started - Complete CourseAngular Js Get Started - Complete Course
Angular Js Get Started - Complete Course
 
Angular Js Advantages - Complete Reference
Angular Js Advantages - Complete ReferenceAngular Js Advantages - Complete Reference
Angular Js Advantages - Complete Reference
 
Html
HtmlHtml
Html
 

Kürzlich hochgeladen

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 

Kürzlich hochgeladen (20)

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 

Complete Notes on Angular 2 and TypeScript

  • 2. TYPE SCRIPT • Typescript is a typed superset of JavaScript that compiles to plain JavaScript. • Typescript is pure object oriented with classes, interfaces and statically typed like C# or Java. • JavaScript framework Angular 2.0 is written in TypeScript. • TypeScript can help programmers to write object-oriented programs and have them compiled to JavaScript, both on server side and client side. • Using Typescript, we can build the faster web applications.
  • 3. TYPE SCRIPT OVERVIEW • JavaScript was introduced as a language for the client side. • The development of Node.js has marked JavaScript as an emerging server-side technology too. • As JavaScript code grows, it tends to get messier, making it difficult to maintain and reuse the code. • Failure Features like • OOPS concepts • Strong type checking and • compile-time errors • These reasons prevents JavaScript from succeeding at the enterprise level as a full-fledged server-side technology. • TypeScript was presented to bridge this gap.
  • 4. COMPILE/EXECUTE TYPESCRIPT PROGRAMS Syntax : Typescript Code: Complied JavaScript code Output: Hello World
  • 5. EXECUTION OF TYPESCRIPT CODE Execution in Command prompt : tsc first.ts node first.js Execution in Sublime : ctrl + b Execution in vs code : ctrl + ` (tilt symbol) Multiple files can be compiled at a time. tsc file1.ts, file2.ts, file3.ts Single statement execution : tsc file.ts && node file.js
  • 6. WHAT IS TYPESCRIPT? • TypeScript is JavaScript for application-scale development. • TypeScript is a strongly typed, object oriented, compiled language. • Designed by Anders Hejlsberg (designer of C#) at Microsoft. • TypeScript is a typed superset of JavaScript compiled to JavaScript. • In other words, TypeScript is JavaScript plus some additional features.
  • 7. FEATURES OF TYPESCRIPT TypeScript is just JavaScript:TypeScript starts with JavaScript and ends with JavaScript. TypeScript code is converted into its JavaScript for execution. TypeScript supports other JS libraries: TypeScript-generated JavaScript can reuse all of the existing JavaScript frameworks, tools, and libraries. JavaScript is TypeScript: valid .js file can be renamed to .ts and compiled with other TypeScript files. TypeScript is portable:TypeScript is portable across browsers, devices, and operating systems. It can run on any environment that JavaScript runs on.
  • 8. WHY USE TYPESCRIPT? • TypeScript is superior to CoffeeScript and Dart programming languages. • Dart, CoffeeScript etc are new languages and they require language-specific execution environment. • Compilation • Strong Static Typing:JavaScript is not strongly typed. • supports type definitions: • supports Object Oriented Programming: like classes, interfaces, inheritance, etc.
  • 9. TYPESCRIPT AND OBJECT ORIENTATION • TypeScript is Object-Oriented JavaScript. • Object Orientation considers a program as a collection of objects that communicate with each other via mechanism called methods. • TypeScript supports these object oriented components too. • Object − An object is a real time representation of any entity. According to Grady Brooch, every object must have three features − • State − described by the attributes of an object • Behavior − describes how the object will act • Identity − a unique value that distinguishes an object from a set of similar such objects. • Class − A class in terms of OOP is a blueprint for creating objects. A class encapsulates data for the object. • Method − Methods facilitate communication between objects.
  • 10. EXAMPLE: TYPESCRIPT AND OBJECT ORIENTATION TypeScript Code Complied JavaScript code Output: Hello World!!! https://www.tutorialspoint.com/typescript/typescript_basic_syntax.htm
  • 11. BASIC TYPES The data type classification is as given below 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.
  • 12. Built-in types User-defined Types • User-defined types include Enumerations (enums), classes, interfaces, arrays, and tuple. These are discussed in detail in the later chapters. Data type Keyword Description Number number Double precision 64-bit floating point values. It can be used to represent both, integers and fractions. String string Represents a sequence of Unicode characters Boolean Boolean Represents logical values, true and false Void void Used on function return types to represent non-returning functions Null null Represents an intentional absence of an object value. Undefine d undefined Denotes value given to all uninitialized variables
  • 13. VARIABLES 1) Boolean :Basic datatype is the simple true/false value.(Both JS and TS) Syntax : let isDone: boolean = false; 2) Number:All numbers in TypeScript are floating point values. In addition to hexadecimal and decimal literals, TypeScript also supports binary and octal literals. Syntax : let decimal: number = 6; let hex: number = 0xf00d; let binary: number = 0b1010; let octal: number = 0o744; String: It refers to these textual datatype. Like JavaScript, TypeScript also use double quotes (“”) or single quotes(‘’) to surround string data. Syntax: let color: string = "blue"; color = 'red';
  • 14. 3)Array:Array types can be written in one of two ways. First way : let list: number[] = [1, 2, 3]; Second way : The second way uses a generic array type ,Array<elemType or Datatype> let list: Array<number> = [1, 2, 3]; var names: Array<string> = [“Ravi", “venkat", “Suresh"]; 4) Tuples: Used to store a collection of values of multiple types. Syntax : // Declare a tuple type let x: [string, number]; // Initialize it x = ["hello", 10]; // OK // Initialize it incorrectly x = [10, "hello"]; // Error
  • 15. When accessing an element with a known index, the correct type is retrieved: console.log(x[0].substr(1)); // OK console.log(x[1].substr(1)); // Error, 'number' does not have 'substr‘ 5) Enum Enumeration (or enum) is a user defined data type. It is mainly used to assign names to integral constants, It make a program easy to read and maintain. Syntax : enum Color {Red, Green, Blue} let c: Color = Color.Green; By default, enums begin numbering their members starting at 0. You can change this by manually setting the value of one of its members. enum Color {Red = 1, Green, Blue} let c: Color = Color.Green; Or, even manually set all the values in the enum: enum Color {Red = 1, Green = 2, Blue = 4} let c: Color = Color.Green;
  • 16. enum Color {Red = 1, Green, Blue} let colorName: string = Color[2]; alert(colorName); 6)Any The type of variables that we do not know when we are writing an application. These values may come from dynamic content. Syntax let notSure: any = 4; notSure = "maybe a string instead"; notSure = false; // okay, definitely a boolean Array has a mix of different types of data let list: any[] = [1, true, "free"]; list[1] = 100;
  • 17. 7)Void Return type of functions that do not return a value. Syntax: Typescript Code / /void - when we do not have any return type from a function function AlertMe(): void { alert("Hello, how are you?"); } AlertMe(); JavaScript Code // void - when we do not have any return type from a function function AlertMe() { alert("Hello, how are you?"); } AlertMe();
  • 18. INTERFACES • TypeScript type-checking only checks for the shape of the interfaces. This type of checking is also called duck typing or structural subtyping. Syntax: • Declare the interface with using “interface” keyword. • It is not mandatory to start with I ,We have to follow the standard naming convention while declaring interface in other programming languages.
  • 19. Interface in TypeScript // declaring interface interface IPerson { name: string; } // using the interface function Details1(thisPerson: IPerson) { alert(thisPerson.name); } // calling the function that is using interface var myDetail1 = { age: 50, name: "Sheo" }; var myDetail11 = { name: "Sheo Narayan", address : "Hyderabad", age :50 }; Details1(myDetail1); Details1(myDetail11);
  • 20. JAVASCRIPT OUTPUT / using the interface function Details1(thisPerson) { alert(thisPerson.name); } // calling the function that is using interface var myDetail1 = { age: 50, name: "Sheo" }; var myDetail11 = { name: "Sheo Narayan", address: "Hyderabad", age: 50 }; Details1(myDetail1); Details1(myDetail11);
  • 21. OPTIONAL PROPERTIES IN THE INTERFACE OF TYPESCRIPT interface IPersonOptional { name: string, age?: number; } // using the interface function DetailsOptional(personalOptional: IPersonOptional) { if (personalOptional.age) { alert("Your name is: " + personalOptional.name + " and age is: " + personalOptional.age); } else { alert("Your name is: " + personalOptional.name); } } // calling the function that is using interface DetailsOptional({ name: "Sheo" }); DetailsOptional({ name: "Sheo", age: 60 });
  • 22. JAVASCRIPT OUTPUT // using the interface function DetailsOptional(personalOptional) { if (personalOptional.age) { alert("Your name is: " + personalOptional.name + " and age is: " + personalOptional.age); } else { alert("Your name is: " + personalOptional.name); } } // calling the function that is using interface DetailsOptional({ name: "Sheo" }); DetailsOptional({ name: "Sheo", age: 60 });
  • 23. TYPESCRIPT - CLASSES • A class in terms of OOP is a blueprint for creating objects. • A class encapsulates data for the object. Syntax class class_name { //class scope } A class definition can include Fields: Any variable declared in class. Constructors: Responsible for allocating memory for the objects of the class. Functions: Functions represent actions an object can take(methods).
  • 24. class Greeter { //field greeting: string; //constructor constructor(message: string) { this.greeting = message; } //function or method greet() { return "Hello, " + this.greeting; //member access } } let greeter = new Greeter("world");
  • 25. TYPESCRIPT CLASS INHERITANCE • Inheritance is the ability of a program to create new classes from an existing class. • A class inherits from another class using the ‘extends’ keyword.
  • 26. TYPESCRIPT ACCESS MODIFIERS There are the 3 types of access modifiers 1) Public 2) Private 3) Protected there are three types of access modifier is used, called public, private and protected.
  • 27. TYPESCRIPT PUBLIC MODIFIER • TypeScript, each member is public by default. • When a member is marked as public explicitly, it can access from outside of its containing class.
  • 28. TYPESCRIPT PRIVATE MODIFIER • When a member is marked private, it cannot be accessed from outside of its containing class.
  • 29. PROTECTED PRIVATE MODIFIER • When a member is marked protected, it cannot be accessed outside of its containing class but exception that members declared protected can also be accessed by instances of deriving classes.
  • 30. TYPESCRIPT - FUNCTIONS • Functions are the building blocks of readable, maintainable, and reusable code. • A function is a set of statements to perform a specific task. • Functions organize the program into logical blocks of code. Named function : function add(x, y) { return x + y;} Anonymous function let myAdd = function(x, y) { return x + y; };
  • 32. INTRODUCTION • UI framework for building mobile and Desktop web applications. • Built with using Typescript(Superscript of JavaScript). • It is used to develop enterprise scale applications. • We can build amazing client side applications using HTML, CSS, and JavaScript.
  • 33. WHY WE LEARN ANGULAR 2 • Performance : Angular2 is 5 times faster than AngularJS. • Mobile Support: SPA that works across mobile and desktop devices. • Component Based Development: In Angualr2, Everything is a component and components are the building blocks of an angular application. • More language choices • ECMAScript 5 • ECMAScript 6 ( ES 2015 ) • TypeScript (Most popular language) • Dart • PureScript • Elm etc.
  • 34. ECMASCRIPT • Angular 2 itself, is built using Typescript. Typescript has great support of ECMAScript 6 standard. 1. What is ECMAScript • The JavaScript language standard is officially called ECMAScript. • We have ECMAScript version 1 to ECMAScript version 7. • Modern browsers available today supported by ECMAScript5. • The browser support for ECMAScript 6 is still incomplete. • The process called Transpiration, ECMAScript 6 to ECMAScript 5. • ECMAScript 6 is officially known as ECMAScript 2015. • ECMAScript 2015 introduced new features like classes, modules, arrow functions etc.
  • 35. 2. What is Type Script a) Typescript is a free and open-source programming language developed by Microsoft. b) Superset of JavaScript c) Transpilation ( Complies Typescript to JavaScript ) Benefits : 1. Intellisense 2. Autocompletion 3. Code navigation 4. Advanced refactoring 5. Strong Typing 6. Supports ES 2015 (also called ES 6) features like classes, interfaces and inheritance.
  • 36. QUICK START Step 1: Set up the Development Environment Then install the Angular CLI globally. npm install -g @angular/cli Step 2: Create a new project Open a terminal window. ng new my-app Step 3: Serve the application cd my-app ng serve - -open or (-o) http://localhost:4200/
  • 37. Step 4: Edit your first Angular component(src/app/app.component.ts) export class AppComponent { title = 'My First Angular App'; } Open src/app/app.component.css and give the component some style. h1 { color: #369; font-family: Arial, Helvetica, sans-serif; font-size: 250%; } Please refer this link for execution : https://angular.io/guide/quickstart Create a child components using command prompt • ng generate component hello (or) • ng g component hello
  • 38. UNDERSTANDING THE FILE STRUCTURE • app/app.component.ts - this is where we define our root component. • app/app.module.ts - Defines AppModule, the root module that tells Angular how to assemble the application.The entry Angular Module to be bootstrapped. • index.html - this is the page the component will be rendered in. • app/main.ts - is the glue that combines the component and page together.
  • 39. Index.html: This the main HTML page of our site.The CLI automatically adds all JS and CSS files when building our app.(no need to add <script> or <link> tags manually). main.ts:The main entry point for your app. Compiles the application with the JIT compiler and bootstraps the application's root module (AppModule) to run in the browser. Pollyfills.ts :Different browsers have different levels of support of the web standards. Polyfills help normalize those differences. Styles.css :Your global styles go here. Test.ts :This is the main entry point for your unit tests. tsconfig.{app|spec}.json : TypeScript compiler configuration for the Angular app. Package.Json : configuration listing the third party packages your project uses. (Add custom custom scripts here ). tscofig.json :TypeScript compiler configuration for your IDE . tslint.json : A grammar check for computer programs and Linting helps keep your code style consistent.
  • 40. ANGULAR 2 TOPICS • Components. • Template vs TemplateUrl. • Nested Components. • One-way Databinding. • Interpolation. • Property Binding • Attribute Binding • Class Binding • Style Binding • Event Binding
  • 41. • Two-way data binding. • HTML Attribute vs DOM property. • Structural Directives • *ngIf • *ngFor • *ngSwitch • Pipes • Custom pipes • Interfaces • Component life cycle • Services (HTTP ,Error Handling) • Routing • Dependency Injection
  • 42. ANGULAR 2 COMPONENTS What is a component ? • Components are the most basic building block of an UI in an Angular application. An Angular application is a tree of Angular components. • Component in angular is a class with a template and a decorator. • Component is composed with 3 things. Class :Defines the user interface. Contains the HTML, directives and bindings. • Properties contain the data that we want to display in the view template and methods contain the logic for the view. We use Typescript to create the class. Template :Contains the code required for template. Decorator: We use the Component decorator provided by Angular to add metadata to the class. A class becomes an Angular component, when it is decorated with the Component decorator.
  • 43. Class: The class decorator. The class is defined in TypeScript. Syntax Parameters: • Classname − This is the name to be given to the class. • Propertyname − This is the name to be given to the property. • PropertyType − Since TypeScript is strongly typed, you need to give a type to the property. • Value − This is the value to be given to the property. Example:
  • 44. Template: The view which needs to be rendered in the application. Syntax Parameters • HTML Code − This is the HTML code which needs to be rendered in the application. • Class properties − These are the properties of the class which can be referenced in the template. Example
  • 45. Decorator It is used to decorate Angular class with additional information. Metadata Properties: https://angular.io/api/core/Component Note :Selector becomes a directive in any html page where we want to use template.
  • 46. TEMPLATE VS TEMPLATE URL Inline Template: The view template is inline in a pair of backtick characters. Examples : 1) template: ‘<h1>Hello {{name }}</h1>’ 2) template: ”<h1>Hello {{name }}</h1>” 3) template: `<h1> Hello {{name }} </h1>` HTML code is more than one line, then you have to use backticks instead of single or double quotes
  • 47. External View Template: • Instead of using an inline view template, you can have it in a separate HTML file. • External view template using templateUrl property. Difference between Inline and External View Template Inline Template : • Poor Intellisense, Code-completion and formatting feature. • TypeScript code is not easier to read and understand. External Template: • Intellisense, code-completion and formatting features. • Not only the code in "app.component.ts" is clean, it is also easier to read and understand.
  • 48. NESTED COMPONENTS • Angular 2 is all about components. • A component in Angular allows us to create a reusable UI widget. • A component can be used by any other component. We have to create two components • AppComponent :This component is the root component and displays just the page header. • EmployeeComponent :This component is the child component and displays the Employee details table. This child component will be nested inside the root AppComponent. What is AppModule? AppModule is the root module which bootstraps and launches the angular application. (you can name it anything what you want) AppModule Imports 2 system modules 1) BrowserModule 2) NgModule
  • 49. • BrowserModule - Every application that runs in a browser needs this module. • NgModule - @component decorator adds metadata to an angular component class, similarly @NgModule decorator adds metadata to the angular module class. • A class is decorated @component decorator then that class becomes an angular component. • Similarly if a a class is decorated with @NgModule decorator then that class becomes an angular module. Properties of the @NgModule decorator • imports - Imports the BrowserModule required for an angular application to run in a web browser • declarations - Contains the components registered with this module. ( AppComponent and EmployeeComponent). • bootstrap - Contains the root component that Angular creates and inserts into the index.html host web page. Program Execution
  • 50. STYLING ANGULAR 2 COMPONENTS Option 1: Specify the styles in external stylesheet - styles.css Advantages : • Visual Studio editor features (Intellisense, Code completion & formatting) are available. • Application maintenance is also easy because we only have to change the styles in one place. Disadvantages : • The Stylesheet that contains the styles must be referenced for the component to be reused. • Since styles.css is referenced in index.html page, these styles may affect the elements in other components, and you may or may not want this behavior.
  • 51. Option 2 : Inline –Styles Advantages : • Visual Studio editor features (Intellisense, Code completion & formatting) are available. • Component can be easily reused as the styles are defined inline. • Styles specified using this approach are local to the component and don't collide with styles used elsewhere in the application. Disadvantages : • Application maintenance is difficult. • For example, if we want to change the <td> border color to red we have to change it in several places.
  • 52. Option 3 : Specify the styles in the component html file using <style> tag. Advantages : • Component can be easily reused as the styles are defined inline with in the component itself • Application maintenance is also easy as we only have to change the styles in one place. • Visual Studio editor features (Intellisense, Code completion & formatting) are available • Styles specified using this approach are local to the component and don't collide with styles used elsewhere in the application. Option 4 : Specify the styles in the component TypeScript file using the @component decorator styles property. Advantages : • Component can be easily reused as the styles are defined inline with in the component itself • Application maintenance is also easy as we only have to change the styles in one place for this component if we need to change them for any reason. • Styles specified using this approach are local to the component and don't collide with styles used elsewhere in the application. Disadvantages : • Visual Studio editor features (Intellisense, Code completion & formatting) are not available.
  • 53. Option 5 : Specify the styles using the @component decorator styleUrls property. The styleUrls property is an array of strings containing stylesheet URLs. Advantages : • Component can be easily reused as both the stylesheet itself and it's path are included with in the component • Application maintenance is also easy as we only have to change the styles in one place • Visual Studio editor features (Intellisense, Code completion & formatting) are available • Styles specified using this approach are local to the component and don't collide with styles used elsewhere in the application.
  • 54. ANGULAR INTERPOLATION • Interpolation is all about data binding. • Data binding classified into 3 categories. One way data-binding - From Component to View Template • To display read-only data on a view template we use one-way data binding. • The component property name in the view template, enclosed in double curly braces: {{propertyName}}. • Program Execution (Interpolation). Data Binding Description One way data-binding From Component to View Template One way data-binding From View Template to Component Two way data-binding From Component to View Template & From View template to Component
  • 55. Example :<h1>{{'Name = ' + firstName}}</h1> Output : Name = Tom We can specify any valid expression in double curly braces like <h1>{{ 20 + 30 + 50 }}</h1> Output :100
  • 56. • Ternary Operator to display heading and No heading. Example :<h1>{{firstName ? firstName : 'No Heading'}}</h1> • Image Display using Interpolation and Property Bidning • Creating methods and Functions (app.component.ts) // create a method fname:string='Angular2'; lname:string='Programming'; //create a function getfullname(){ return this.fname+' '+this.lname; app.component.html <p>{{getfullname()}}</p> Output : Angular2 Programming.
  • 57. interpolation to set <img> src • HTML :<img src={{imagepath}}><!--Interpolation--> • TS Code :imagepath: string='https://blog.addthiscdn.com/wp- content/uploads/2015/11/logo-facebook.png';
  • 58. PROPERTY BINDING • Interpolation to bind component class properties to view template. • Another option to achieve exactly the same thing is by using Property binding. • we have bound imagePath property of the component class to <img> element src property using interpolation. • <img src={{imagepath}}> • The <img> element src property is in a pair of square brackets, and the component class property is in quotes. • <img [src]="imagepath">
  • 59. DIFFERENCE BETWEEN INTERPOLATION AND PROPERTY BINDING • Both Interpolation and Property binding flows a value in one direction, i.e from a component's data property into a target element property. • Interpolation is a special syntax that Angular converts into a property binding. • Interpolation is just a convenient alternative to property binding. • In some cases to concatenate strings ,we have to use interpolation instead of property binding • <img src="https://angular.io/{{imglink}}"> • When setting an element property to a non-string data value, you must use property binding. • <button [disabled]='isDisabled'>Click me!</button>
  • 60. • If we use interpolation instead of property binding, the button is always disabled irrespective of isDisabled class property value. • <button disabled='{{isDisabled}}'>Click me!</button> • Important points about Property Binding • Enclose the property name with a pair of square brackets. • If you omit the brackets, Angular treats the string as a constant and initializes the target property with that string. • Alternate syntax with bind- prefix instead of property binding is known as canonical form • <button bind-disabled='isDisabled'>Click me</button>
  • 61. HTML ATTRIBUTE VS DOM PROPERTY What is DOM? • DOM stands for Document Object Model. When a browser loads a web page, the browser creates a Document Object Model of that page.
  • 62. • The browser creates a Document Object Model of that page as shown below • DOM is an API for HTML. • Programming languages like JavaScript or JavaScript frameworks like Angular to access and manipulate the HTML using their corresponding DOM objects. • In other words DOM contains the HTML elements as objects, their properties, methods and events and it is a standard for accessing, modifying, adding or deleting HTML elements.
  • 63. Interpolation example <button disabled='{{isDisabled}}'>Click Me</button> Property binding example <button [disabled]='isDisabled'>Click Me</button> • In above two examples, we are binding to the Button's disabled attribute. (Not true) • We are actually binding to the disabled property of the button object. • Angular data-binding is all about binding to DOM object properties and not HTML element attributes. What is the difference between HTML element attribute and DOM property • Attributes are defined by HTML, where as properties are defined by the DOM. • Attributes initialize DOM properties. Once the initialization complete, the attributes job is done. • Property values can change, where as attribute values can't.
  • 64. Example : <input id="inputId" type="text" value="Angular"> The web page and in the textbox ,We will see ‘Angular' as the value. Launch the browser developer tools (F12) On the 'Console' tab, use the getattribute() method and value property of the input element to get the attribute and property values. • inputId.getAttribute('value') "Angular“ • inputId.value • “Angular“
  • 65. Change the value in the textbox to ”Programming” • inputId.getAttribute('value') "Angular“ • inputId.value "Programming“ When we query for the attribute and property values, the attribute value is still “Angular” but the property value is “Programming”.
  • 66. So it is important to keep in mind that, • HTML attributes and the DOM properties are different things. • Angular binding works with properties and events, and not attributes. • The role of attributes is to initialize element properties and their job is done.
  • 67. ATTRIBUTE BINDING • Interpolation and Property binding that deal with binding Component class properties to HTML element properties and not Attributes. • But not all the HTML elements having this properties.For example, colspan attribute does not have corresponding property. • In this case we want to bind HTML element attributes. • With attribute binding we can set the value of an attribute directly. • Use attribute binding only when there is no corresponding element property to bind.
  • 68. Program syntax: • colspan attribute value to 2 in the HTML. • If we use interpolation to bind columnSpan property of the component class to colspan attribute of the <th> element we get the error - Can't bind to 'colspan' since it isn't a known property of 'th‘ • <th colspan="{{columnSpan}}"> • We get the same error if we use Property Binding <th [colspan]="columnSpan"> • This error is because we do not have a corresponding property in the DOM for colspan attribute. • To fix this we have to use attribute-binding in Angular (colspan attribute). To tell angular framework that we are setting an attribute value we have to prefix the attribute name with attr and a DOT <th [attr.colspan]="columnSpan"> • The same is true when using interpolation <th attr.colspan="{{columnSpan}}">
  • 69. CLASS BINDING • Add and remove CSS class names from an element's class attribute with a Class binding. • Create CSS styles like .boldClass{ font-weight:bold; } .italicsClass{ font-style:italic; } .colorClass{ color:red; } • Create a button in HTML page <button class="colorClass">Submit</button> the 'colorClass' is added to the button
  • 70. • Replace all the existing css classes with one or more classes. Example 1: • HTML Code :<button class='colorClass' [class]='classesToApply'>My Button</button> • TS Code :classesToApply: string = 'italicsClass boldClass'; Example 2: • HTML Code : <button class='colorClass' [class.boldClass]='applyBoldClass'>My Button</button> • TS Code : applyBoldClass: boolean = false; • Adding or removing a single class :Include the prefix 'class' in a pair of square brackets, followed by a DOT and then the name of the class that you want to add or remove. • In the example adds boldClass to the button element. Notice it does not remove the existing colorClass already added using the class attribute. • If you change applyBoldClass property to false or remove the property.
  • 71. ADD OR REMOVE MULTIPLE CLASSES USE NGCLASS DIRECTIVE • ngClass is binded to addClasses() method. • addClasses() method returns an object with 2 key/value pairs. The key is a CSS class name. The value can be true or false. True to add the class and false to remove the class. • Since both the keys (boldClass & italicsClass) are set to true, both classes will be added to the button element
  • 72. STYLE BINDING • Style binding syntax resembles property binding. • style property name can be written in either dash-case or camelCase. • For example, font-weight style can also be written using camel case - fontWeight. NgStyle directive • ngStyle is binded to addStyles() method. • addStyles() method returns an object with 2 key/value pairs. The key is a style name, and the value is a value for the respective style property or an expression that returns the style value.
  • 73. EVENT BINDING • The following bindings flow data in one direction i.e from a component class property to an HTML element property. 1. Interpolation 2. Property Binding 3. Attribute Binding 4. Class Binding 5. Style Binding • Flow data in Opposite direction i.e from an HTML element to a component. • User actions like clicking on a button, hovering over an element, selecting from a dropdownlist, typing in a textbox etc, then the corresponding event for that action is raised. • We need to know when user performs these actions. We can use angular event binding to get notified when these events occur.
  • 74. CLICK EVENT OF A BUTTON • Within parentheses we have the target event, (click). • onClick() method of the component class is called when the click event occurs. • HTML Code: <button (click)="onClick()">Click me</button> • TS Code : onClick(): void { console.log('Button Clicked'); • Event binding is use of on- prefix alternative is known as canonical form. • HTML Code: <button on-click="onClick()">Click me</button> • Every time we click the button, 'Button Clicked' message is logged to the console.
  • 75. EVENT BINDING EXAMPLE • When we click "Show Details" button, we want to display "Gender" and "Age“. • The text on the button should be changed to "Hide Details“.
  • 76. • When we click "Hide Details" button, "Gender" and "Age" should be hidden and the button text should be changed to "Show Details". • To achieve this by using one of the structural directives "ngIf" in angular. • "showDetails" boolean property. The default value is false, so when the page first loads. • we will have "Gender" and "Age" hidden. We also have a method, toggleDetails(), which toggles the value of showDetails. • TS Syntax: columnSpan: number = 2; firstName: string = 'Suresh'; lastName: string = 'Babu'; gender: string = 'Male'; age: number = 20; showDetails: boolean = false; toggleDetails(): void { this.showDetails = !this.showDetails; }
  • 77. Program Explanation : • click event of the button is binded to toggleDetails() method. • To dynamicall change the text on the button, we are using ternary operator - {{showDetails ? 'Hide' : 'Show'}} Details. • Use the ngIf structural directive on "Gender" and "Age" <tr> elements. • The * prefix before a directive indicates, it is a structural directive. • The ngIf directive adds or removes content from the DOM based on expression is true or false. • If "showDetails" is true, "Gender" and "Age" <tr> elements are added to the DOM, else removed.
  • 78. TWO-WAY DATA BINDING • Name : <input [value]='name'>-Binds component class "name" property to the input element’s value property. • You entered : {{name}} - Interpolation displays the value we have in "name" property on the web page • when we change the value in the textbox, that changed value is not reflected in the browser. • Binding to the input event of the input control as shown below. • Name :<input [value]='firstname' (input)='firstname = $event.target.value'> • You entered : {{firstname}}
  • 79. PROGRAM EXPLANATION • [value]=‘firstname’-This property binding flows data from the component class to element property . • (input)='firstname = $event.target.value: Event binding flows data in the opposite direction i.e from the element to component class property "name“ • $event - event binding, and contains the event data. • name = $event.target.value - This expression updates the value in the name property in the component class. • {{name}} - This interpolation expression will display the value on the web page. • two-way data binding in Angular is a combination of both Property Binding and Event Binding.
  • 80. NGMODEL DIRECTIVE • Two-way data binding angular has provided ngModel directive. • Name : <input [(ngModel)]='name'> • You will get the following error Template parse errors: Can't bind to 'ngModel' since it isn't a known property of 'input‘. • ngModel directive is, in an Angular system module called FormsModule. • we have to import FormsModule in our root module. • Steps to import FormsModule into our AppModule 1. Open app.module.ts file. 2. Include the following import statement in it import { FormsModule } from '@angular/forms'; 3. Also, include FormsModule in the 'imports' array of @NgModule imports: [BrowserModule,FormsModule],
  • 81. POINTS TO REMEMBER • The square brackets on the outside for property binding • The parentheses on the inside for event binding • To easily remember this syntax, compare it to a banana in a box [( )] (Banana box).
  • 82. ANGULAR NGFOR DIRECTIVE • we want display employees in a table on a web page as shown below.
  • 83. Take an array of Employee objects. export class NgForComponent { employees: any[] = [ { ID: 'LAKSHYA121', name: 'Sowmya', gender: 'Female', annualSalary: 15500, dateOfBirth: '25/06/1996' }, { ID: 'LAKSHYA122', name: 'Ravi', gender: 'Male', annualSalary: 18700.95, dateOfBirth: '9/06/1990' }, { ID: 'LAKSHYA123', name: 'Vasundhara', gender: 'Female', annualSalary: 22000, dateOfBirth: '12/08/1988' }, { ID: 'LAKSHYA124', name: 'Venkat Reddy', gender: 'Male', annualSalary: 16500.123, dateOfBirth: '14/10/1992'}, { ID: 'LAKSHYA125', name: 'Venkatesh', gender: 'Male', annualSalary: 20000.826, dateOfBirth: '14/06/1989'}, ]; }
  • 84. <tr *ngFor='let employee of employees'> <td>{{employee.ID}}</td> <td>{{employee.name}}</td> <td>{{employee.gender}}</td> <td>{{employee.annualSalary}}</td> <td>{{employee.dateOfBirth}}</td> </tr> Explanation: • ngFor is used to display an array of items. • ngFor is a structural directive (prefixed with *) • *ngFor=‘let employee of employees.’ • ngFor can repeat items for any iterable object.
  • 85. ANGULAR NGFOR TRACKBY 1.Usage of trackyBy with ngFor directive 2.Get the index of an item in a collection 3. Identifying the first and the last elements in a collection 4. Identifying even and odd elements in a collection Using trackyBy with ngFor directive : • ngFor directive may perform poorly with large lists • A small change to the list like, adding a new item or removing an existing item may trigger a cascade of DOM manipulations
  • 86. • The employees array initializes the employees property with 5 employee objects getEmployees() method returns another list of 7 employee objects ( 2 new new employee objects) • the moment we are not using trackBy with ngFor directive When the page initially loads we see the 5 employees • When we click "Refresh Employees" button we see the sixth and seventh employees as well. • It looks like it just added the additional row for the sixth and seventh employees. That's not true, it effectively teared down all the <tr> and <td> elements of all the employees and recreated them. • To confirm this launch browser developer tools by pressing F12. • Click on the "Elements" tab and expand the <table> and then <tbody> elements • At this point click the "Refresh Employees" button and you will notice all the <tr>elements are briefly highlighted indicating they are teared down and recreated.
  • 87. • This happens because Angular by default keeps track of objects using the object references. • When we click "Refresh Employees" button we get different object references and as a result and all the old DOM elements and insert the new DOM elements. • Angular can avoid this with trackBy. • The trackBy function takes the index and the current item as arguments and returns the unique identifier by which that item should be tracked.(Employee Code) • trackByEmpCode(index: number, employee: any): string { return employee.code; • <tr *ngFor='let employee of employees trackBy:trackByEmpCode'> • At this point, run the application and launch developer tools. When you click "Refresh Employees" first time, only the the rows of the sixth and seventh employees is highlighted indicating only that<tr> element is added.
  • 88. INDEX OF AN ITEM IN A COLLECTION • let i=index It is used to display the index of an element. • let isFirst = first; • let isLast = last’ Used to display the Boolean properties for first and last elements. • let isEven = even; • let isOdd = odd‘ Used to display the Boolean properties for even and odd elements.
  • 89. PIPES • Transform data before display. • A pipe takes in data as input and transforms it to a desired output. • Built in pipes include lowercase, uppercase, decimal, date, percent, currency etc. Pipe URL Date https://angular.io/api/common/DatePipe Decimal https://angular.io/api/common/DecimalPipe Currency https://angular.io/api/common/CurrencyPipe Percent https://angular.io/api/common/PercentPipe
  • 90. EXAMPLES • Lower case filter • {{product.ProductID|lowercase}} • Upper case filter • {{product.ProductName|uppercase}} • Currency Filter • {{product.ProductPrice|currency:"INR"}} • Date filter • {{product.ReleaseDate|date :'fullDate'}}
  • 91. Parameterizing a pipe • If the pipe accepts multiple parameters, separate the values with colons • {{appValue|Pipe1: parameter1: parameter2 }} Chaining pipes • We can chain multiple pipes together. • Apply the pipes one after another
  • 92. CUSTOM PIPES We can write your own custom pipes. Steps to create Custom Pipes : 1) Create a pipe file, (i.e custompipe.pipe.ts) 2) Every pipe component will have to import the pipe from the Angular core. 3) Apply the @pipe decorator, Which imports form the core angular library. 4) Define the pipe metadata i.e A pipe is a class decorated with pipe metadata. 5) Create the Component class. It should have the transform function, which holds the business logic of what the pipe should do. The Pipe Transform interface The transform method is the essential to a pipe. The Pipe Transform interface defines that method guides both tooling and the compiler. Note :You must include your pipe in the declarations array of the AppModule.
  • 93. PURE AND IMPURE PIPES • There are two categories of pipes: pure and impure. • Pipes are pure by default. You make a pipe impure by setting its pure flag to false. Pure Pipe • Angular executes a pure pipe only when it detects a pure change to the input value. • It will not remember or trace any of the previous values or states. • A pure change is either a change to a primitive input value (String, Number, Boolean, symbol) or a changed object reference (Date, Array, Function, Object). • Angular ignores changes within (composite) objects. It won't call a pure pipe if you change an input month, add to an input array, or update an input object property.
  • 94. Impure pipes • Angular executes an impure pipe during every component change detection cycle. • An impure pipe is called often, as often as every keystroke or mouse-move. pure :false
  • 95. COMPONENT INTERACTION/COMPONENT COMMUNICATION It can be done by two ways 1) Pass data to child component 2) Pass data to parent component • In Angular Parent Component can communicate with the child component by setting its Property. • To do that the Child component must expose its properties to the parent component. • The Child Component does this by using the @Input decorator. The Child Component • Import the @Input module from @angular/Core Library • Mark those property, which you need data from parent as input property using @Input decorator The Parent Component • Bind the Child component property in the Parent Component when instantiating the Child
  • 96. @INPUT • The @Input Decorator is used to configure the input properties of the component. • When you mark a property as input property, then the Angular injects values into the component property using Property Binding. • The Binding Target (Property of the child component) is placed inside the square brackets. @Input example • A counter which is incremented by the Parent Component. • The Parent Component then passes this counter to the child component for display.
  • 97. THE CHILD COMPONENT WITH @INPUT DECORATOR Create the ChildComponent. import { Component, Input } from '@angular/core'; @Component({ selector: 'app-childcomponent', template: `<h2>Child Component</h2> current count is {{ count }}`, styleUrls: ['./childcomponent.component.css'] }) export class ChildcomponentComponent { @Input() count: number; }
  • 98. Step 1 : import the @Input decorator from @angular/core import { Component, Input } from '@angular/core'; Step 2 :Define the inline template for the child component, where it displays the current count. Component({ selector: 'app-childcomponent', template: `<h2>Child Component</h2> current count is {{ count }}`, Step 3 :The Child Component expects the count to come from the Parent Component. ChildComponent decorate the count property with @Input decorator. export class ChildcomponentComponent { @Input() count: number; }
  • 99. Bind to Child Property in Parent Component Now, time to pass the Count values to the Child Component from the Parent. import { Component, OnInit } from '@angular/core'; import { ChildcomponentComponent } from "./childcomponent/childcomponent.component"; @Component({ selector: 'app-componentinteraction', template: `<h1>Welcome to {{title}}!</h1> <button (click)="increment()">Increment</button> <button (click)="decrement()">decrement</button> <app-childcomponent [count]=Counter></app-childcomponent>` , styleUrls: ['./componentinteraction.component.css'] })
  • 100. export class ComponentinteractionComponent { title = 'Component Interaction'; Counter = 5; increment() { this.Counter++; } decrement() { this.Counter--; } }
  • 101. The inline template in the Parent Component has two buttons. The Buttons Increments/decrements the counter. <button (click)="increment()">Increment</button> <button (click)="decrement()">decrement</button> we are using count property, which is a property of the child Component inside the square bracket. We bind it to Counter property of the Parent Component. <app-childcomponent [count]=Counter></app-childcomponent> Finally, we will add counter in Parent component and set it to 5 as shown below. export class ComponentinteractionComponent { title = 'Component Interaction'; Counter = 5; increment() { this.Counter++; } decrement() { this.Counter--; } }
  • 102. PASS DATA TO PARENT COMPONENT • we will learn how to Pass data to Parent Component from Child Component in Angular. • The Child can send data to Parent by raising an event, Parent can interact with the child via local variable or Parent can call @ViewChild on the child. Pass data to parent component • There are three ways in which parent component can interact with the child component. • Parent Listens to Child Event. • Parent uses Local Variable to access the child. • Parent uses a @ViewChild to get reference to the child component.
  • 103. Parent listens for child event • The Child Component exposes an EventEmitter Property. This Property is adorned with the @Output decorator. • When Child Component needs to communicate with the parent it raises the event. The Parent Component listens to that event and reacts to it. EventEmitter Property • To Raise an event, the component must declare an EventEmmitter Property. The Event can be emitted by calling the .emit() method. Example : @Output() countChanged: EventEmitter<number> = new EventEmitter(); • Then call emit method passing the whatever the data you want to send. this.countChanged.emit(this.count);
  • 104. @OUTPUT DECORATOR • Using the EventEmitter Property gives the components ability to raise an event. • But the event accessible from parent component, you must decorate the property with @Output decorator. How to Pass data to parent component using @Output In the child component 1.Declare a property of type EventEmitter and initiate it. 2.Mark it with a @Output annotation. 3.Raise the event passing it with the desired data. In the Parent Component 1.Bind to the Child Component using Event Binding and listen to the child events 2.Define the event handler function.
  • 105. Example Explanation: (Passing data to parent component Via Events (Example)). • we built a counter in the parent component. • We assigned the initial value to the counter and added increment/decrement methods. • In the child Component, we used the @Input decorator to bind count property to the parent component. • Whenever parent count is changed in the parent the child component is updated and displayed the count. • we will move the counter to the child component. We will raise an event in the child component whenever the count is increased or decreased. • We then bind to that event in the parent component and display the count in the parent component.
  • 106. PARENT USES LOCAL VARIABLE TO ACCESS THE CHILD IN TEMPLATE • Parent Template can access the child component properties and methods by creating the template reference variable. Child component import { Component} from '@angular/core'; @Component({ selector: 'child-component', template: `<h2>Child Component</h2> current count is {{ count }} ` }) export class ChildComponent { count = 0; increment() { this.count++; } decrement() { this.count--; } }
  • 107. • We have removed the input, output & eventemiitter. • Our component is now have property count and two methods to increment and decrement it Parent Component import { Component} from '@angular/core'; @Component({ selector: 'app-root', template: ` <h1>{{title}}!</h1> <p> current count is {{child.count}} </p> <button (click)="child.increment()">Increment</button> <button (click)="child.decrement()">decrement</button> <child-component #child></child-component>` , styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Parent interacts with child via local variable'; }
  • 108. PARENT USES A @VIEWCHILD() TO GET REFERENCE TO THE CHILD COMPONENT • Injecting an instance of the child component into the parent as a @ViewChild is the another technique used by the parent to access the property and method of the child component. • The @ViewChild decorator takes the name of the component/directive as its input. It is then used to decorate a property. • The Angular then injects the reference of the component to the Property. Child Component • There is no change in the child component Parent Component import { Component, ViewChild } from '@angular/core'; import { ChildComponent } from './child.component';
  • 109. Parent Component : @Component({ selector: 'app-root', template: ` <h1>{{title}}</h1> <p> current count is {{child.count}} </p> <button (click)="increment()">Increment</button> <button (click)="decrement()">decrement</button> <child-component></child-component>` , }) export class AppComponent { title = 'Parent calls an @ViewChild()'; @ViewChild(ChildComponent) child: ChildComponent; increment() { this.child.increment(); } decrement() { this.child.decrement(); } } https://www.tektutorialshub.com/angular-pass-data-to-parent-component/
  • 110. COMPONENT LIFE CYCLE HOOKS • The life cycle hooks are the methods that angular invokes on directives and components as it creates, changes, and destroys them. • Using life-cycle hooks we can fine tune the behavior of our components during creation, update, and destruction. What is Angular Component lifecycle hooks • When the angular application starts it creates and renders the root component. Then creates and renders it’s Children. • For each loaded component, it checks when its data bound properties change and updates them. It destroys the component and removes it from the DOM when no longer in use. • The Angular life cycle hooks are nothing but callback function, which angular invokes when a certain event occurs during the component’s life cycle.
  • 111. For example • When component is initialized, Angular invokes ngOnInit • When a component’s input properties change, Angular invokes ngOnChanges • When a component is destroyed, Angular invokes ngOnDestroy Angular lifecycle hooks Here is the complete list of life cylce hooks provided by the Angular • ngOnChanges - called when an input binding value changes. • ngOnInit - after the first ngOnChanges. • ngDoCheck - after every run of change detection. • ngAfterContentInit - after component content initialized. • ngAfterContentChecked - after every check of component content. • ngAfterViewInit - after component's view(s) are initialized. • ngAfterViewChecked - after every check of a component's view(s). • ngOnDestroy - just before the component is destroyed.
  • 112. 1) ngOnChanges :The Angular invokes this life cycle hook whenever any data-bound property of the component or directive changes. Example :Passing data to child component. 2) ngOnInit:when the component is created for the first time and called after the constructor and first ngOnChanges hook. Initialisation logic for your component. ngOnChanges hook is fired before ngOnInit. Which means all the input properties are available to use when the ngOnInit is hook is called. This hook is fired only once 3) ngDoCheck: after the ngOnInit. On every change made to the component properties, the event is raised or change in value of properties. This hook is executed for every change detection in cycles even there is no properties change.
  • 113. 4) ngAfterContentInit :This Life cycle hook is called after the Component’s content has been fully initialized. 5) ngAfterContentChecked:called after the Components Content is checked by the Angular’s Change detection module. It is called immediately after ngAfterContentInit and after every subsequent ngDoCheck(). 6) ngAfterViewInit :Similar to ngAfterContentInit, but invoked after Angular initializes the component’s views and all its child views. This is Called once after the first ngAfterContentChecked. 7) ngAfterViewChecked:The Angular fires this hook after it checks the component’s views and child views. This event is fired after the ngAfterViewInit and after that for every subsequent ngAfterContentChecked hook.
  • 114. 8) ngOnDestroy:This hook is called just before the Component/Directive instance is destroyed by Angular. Perform any cleanup logic for the Component. This is the correct place to Unsubscribe Observables and detach event handlers to avoid memory leaks. How to Use Lifecycle Hooks • Import Hook interfaces • Declare that Component/directive Implements lifecycle hook interface • Create the hook method (e.g. ngOnOnChanges) Read more : https://angular.io/guide/lifecycle-hooks
  • 115. DEPENDENCY INJECTION • Dependency Injection (DI) is a technique in which we provide an instance of an object to another object, which depends on it. This is technique is also known as “Inversion of Control” (IoC) • Dependency Injection(DI) is a coding pattern in which a class receives dependencies rather than creating them itself. Why we absolutely need DI: • DI is a software design pattern in which a class receives its dependencies rather than creating the object itself. • DI creates and delivers objects, which are required dynamically just-in-time • We can consider the injectables as our application's reusable repository • DI allows independent development of dependency modules for remote development teams.
  • 116. SERVICES • services or factories helps to achieve reusability in code and enables us to share the application-specific logic across the application blocks, such as components, directives, and so on. What services are user for • Features that are independent of components such a logging services. • Share logic across components • Encapsulate external interactions like data access Advantageous of Service • Services are easier Test. • Services are easier to Debug. • You can reuse the service.
  • 117. How to create a Service in Angular 2 • An Angular 2 service is simply a javascript function means create a class and add methods & properties. • We can then create an instance of this class in our component and call its methods. • One of the best uses of services is to get the data from the data source. Example explanation : Step 1 ) Product ( create product.ts file) 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; }
  • 118. Step 2) Product Service ( Create 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',1000), ] return products; } }
  • 119. Step 3) Invoking the ProductService(Open the app.componet.ts) import { ProductService } from "./product.service"; import { Product } from "./product"; @Component({ selector: 'app-service', templateUrl: './service.component.html', }) export class ServiceComponent { products:Product[]; productService; constructor(){ this.productService=new ProductService(); } getProducts() { this.products=this.productService.getProducts(); } }
  • 120. Step 4) Template(Open the app.component.html file ) <div class="container"> <h1 class="heading"><strong>Services </strong>Demo</h1> <button type="button" class="btn btn-outline-primary" (click)="getProducts()">Get Products</button> <br> <br> <div class='table-responsive'> <table class='table'> <thead> <tr> <th>ID</th> <th>Name</th> <th>Price</th> </tr> </thead>
  • 121. <tbody> <tr *ngFor="let product of products;"> <td>{{product.productID}}</td> <td>{{product.name}}</td> <td>{{product.price | currency:"INR":true}}</td> </tr> </tbody> </table> </div> </div>
  • 122. ROUTING What is Routing Routing allows you to move from one part of the application to another part or one View to another View. The Angular Router Module The Router is a separate module in Angular. It is in its own library package, @angular/router. Routing allows you to: • Maintain the state of the application • Implement modular applications • Implement the application based on the roles (certain roles have access to certain URLs)
  • 123. CONFIGURING ROUTES Base URL Tag • The Base URL tag must be set within the <head> tag of index.html:<base href="/"> Route Definition Object The Routes type is an array of routes that defines the routing for the application. • Each route can have different attributes; some of the common attributes are: • path - URL to be shown in the browser when application is on the specific route • component - component to be rendered when the application is on the specific route • redirectTo - redirect route if needed; each route can have either component or redirect attribute defined in the route (covered later in this chapter) • pathMatch - optional property that defaults to 'prefix'; determines whether to match full URLs or just the beginning. When defining a route with empty path string set pathMatch to 'full', otherwise it will match all paths. • children - array of route definitions objects representing the child routes of this route (covered later in this chapter).
  • 124. • To use Routes, create an array of route configurations. export const routes: Routes = [ { path: '', redirectTo : '/',pathMatch : 'full'}, { path: 'componentOne', component : ComponentOne}, { path: 'componentTwo', component : ComponentTwo} ]; RouterModule RouterModule.forRoot takes the Routes array as an argument and returns a configured router module • export const routing = RouterModule.forRoot(routes);
  • 125. • We then import our routing configuration in the root of our application. Open app.module.ts 1) import { routing } from './app.routes'; 2) Imports include ‘routing’ Redirecting the Router to Another Route When your application starts, it navigates to the empty route by default. We can configure the router to redirect to a named route by default: { path: '', redirectTo : '/',pathMatch : 'full'}, Defining Links Between Routes Add links to routes using the routerLink Directive. <nav> <a routerLink = '/componentOne'> Component One</a> <a routerLink = '/componentTwo'> Component Two</a> </nav>
  • 126. DYNAMICALLY ADDING ROUTE COMPONENTS • Angular dynamically adds the component for the route being activated into the <router-outlet></router-outlet> element. • router-outlet which serves as a component placeholder. https://angular-2-training-book.rangle.io/handout/routing/why_routing.html
  • 127. FORMS FUNDAMENTALS & CONCEPTS • Forms are used to collect the data from the user.It can contain large no of input fields, Spanning multiple tabs. • Forms may also contain complex validation logic interdependent on multiple fields. Forms are expected to do • Initialise the forms fields and present it to the user • Capture the data from the user • Track changes made to the fields • Validate the inputs • Display helpful errors to the user
  • 128. ANGULAR 2 FORMS MODULE • Froms module the two-way data binding & event binding bind the form field to the Angular 2 component class. • It tracks changes made to the form fields so that we can respond accordingly. • Angular forms provide the built-in validators to validate the inputs and we can create your own custom validators. • Finally, it encapsulates all the input fields into an object structure when the user submits the form. Angular 2 takes two approaches to building the forms. 1) Template driven forms 2) Model driven forms
  • 129. 1) Template driven forms approach: Easiest way to build the Angular 2 forms. The logic of the form is placed in the template. (Angular 1). 2) Model-driven forms approach: The logic of the form is placed in the component. The Model driven approach has more benefits as it makes the testing of the component easier. Building Blocks of Angular 2 Forms 1) FormControl :A FormControl represents a single input field in an Angular form. 2) FormGroup :FormGroup is a group of FormControl instances. 3) FormArray :The FormArray‘s are array of FormControl’s. The FormArray’s are very much similar to FormGroups. Here FormControls are represented as an array of objects.
  • 130. TEMPLATE DRIVEN FORMS • we will add few input fields in our Form and bind it to Angular Forms Module using ngModel directive. • Then, we will submit the data to the OnSubmit method in the Component class. What is a Template Driven Forms • Angular 2 Template driven forms are similar to the forms are built in Angular 1. • We used directives like ngModel in our templates and let Angular handle everything (Angular 1). • We also used HTML5 validation attributes like required, maxlength or built our own custom directives to achieve validations.
  • 131. Angular 2 template-driven forms, we need to tell our @NgModule to use the FormsModule from @angular/forms. In the app.module.ts file. Building the Template <div class="container"> <form #contactForm="ngForm" (ngSubmit)="onSubmit(contactForm)" > <div class="form-group"> <label for="firstname">First Name</label> <input type="text" class="form-control" name="firstname" ngModel> </div> <div class="form-group"> <label for="lastname">Last Name</label> <input type="text" class="form-control" name="lastname" ngModel> </div> <div class="form-group"> <button type="submit">Submit</button> </div> <h2> <pre>{{contactForm.value | json }} </pre> </h2> </form> </div>
  • 132. ngForm Directive • The ngForm directive makes the Angular 2 Template driven Forms work.(no need to add it explicitly). • When we include FormsModule, the Angular is going to look out for any <form>tag in our HTML template. • Angular does this via ngForm directive. • ngForm directive automatically detects the <form> tag and automatically binds to it. • ngForm directive creates a top-level FormGroup instance and binds it to the form to track aggregate form value and validation status. FormControl ngModel will use the name attribute to create the FormControl instance for each of the Form Field it is attached.
  • 133. FormGroup • The FormGroup is a collection of FormControl. • ngForm directive by assigning it to the Local Template Variable (#contactForm). <form #contactForm ="ngForm"> Submit data to Component <form #contactForm="ngForm" (ngSubmit)="onSubmit(contactForm)" > • The Form data is submitted to the Component using the Angular directive named ngSubmit. • We are using event binding (parentheses) to bind ngSubmit to OnSubmit method in the component class. • We have a submit button in our form. The ngSubmit will fire when the user clicks on the submit button. • We are passing the Local Template Variable contactForm in onSubmit method. contactForm holds the reference the ngForm directive. • We can use this in our component class to extract the Data from the Form Fields.
  • 134. • we have added {{contactForm.value | json }} at the end. • we can see the value exposed by the contactForm.value method as you input into the form fields. Receive the data in Component class • onSubmit method receives the reference to the ngForm directive, which we named is as contactForm. • The contactForm exposes the value method which returns the form fields as Json object. • use log it to the console using the console.log(contactForm.value);
  • 135. VALIDATION IN TEMPLATE DRIVEN FORMS The Angular forms architecture supports two ways to validate the Form. 1) Built-in validation 2) Custom validation 1) Built-in Validators • The Angular Built-in validators use the HTML5 validation attributes like required, minlength, maxlength & pattern. • Angular 2 interprets these validation attributes and add the validator functions to FormControl.
  • 136. HOW TO ADD BUILT-IN VALIDATORS Disabling the Browser validation • <form #contactForm="ngForm" (ngSubmit)="onSubmit(contactForm)" > Adding Required Validator • <input type="text" class="form-control" name="firstname" ngModel #firstname="ngModel" required minlength="4" > • We will notice that clicking on the Submit button submits the form. We need to tell angular not to submit the form unless the form is valid. Disable Submit button • We need to disable the submit button if our form is not valid. Displaying the Validation/Error messages <div *ngIf="!firstname?.valid && (firstname?.dirty ||firstname?.touched)" class="alert alert-danger"> <div [hidden]="!firstname.errors.required"> First Name is required </div>
  • 137. MODEL DRIVEN FORMS • Model Driven Forms are also known as reactive forms. • The form is built in the component class, unlike Template Driven Model where the model is built in templates. Advantages of Angular 2 Model Driven Forms • Used to enable us to test our forms without being required to rely on end-to-end tests. • The model driven Forms allows you to have an ability to setup validation rules in code rather than as directive in Template. • We can subscribe to field value changes in your code. Since everything happens in Component class, you can easily write unit Tests.
  • 138. HOW TO CREATE ANGULAR 2 MODEL DRIVEN FORMS Enabling Model Driven Forms • We need to import ReactiveFormsModule instead of FormModule to make use of Model Driven Forms. • We should also add the ReactiveormsModule to the imports metadata property array. import { ReactiveFormsModule } from '@angular/forms'; Building the Model • In the Template driven approach, we used ngModel & ngModelGroup directive on the HTML elements, which created the FormGroup & FormControl instances behind the scene. • In the Model Driven approach, it is our responsibility to create the FormGroup and FormControl
  • 139. • FormControl encapsulates the state of a single form element in our form. It stores the value and state of the form element and helps us to interact with them using properties & methods. • FormGroup represents a collection of FormControls. In fact, an angular form is a FormGroup. • First, we need to import FormGroup, FormControl & Validator from the angular/forms. import { FormGroup, FormControl,FormBuilder,Validators } from '@angular/forms'; FormGroup contactForm = new FormGroup({}) The FormGroup takes 3 arguments. a collection of child FormControl, a validator, and an asynchronous validator. The Validators are optional.
  • 140. FormControl FormGroup is the collection of child FormControl. contactForm = new FormGroup({ firstname: new FormControl(), lastname: new FormControl(), }) Binding the template to the model <form [formGroup]="contactForm"> We have used the square bracket (one-way binding) around FormGroup directive and set that equal the model. Submitting the form <form [formGroup]="contactForm" (ngSubmit)="onSubmit()">
  • 141. MODEL DRIVEN FORMS VALIDATION 1) Built-in Validators 2) Adding Required Validator this.contactForm = this.fb.group({ firstname: ['',[ Validators.required,Validators.minLength(10)]], lastname: ['',[ Validators.required,Validators.minLength(5)]], address: this.fb.group({ city:[], street: [], pincode: [ ] }) });
  • 142. Disable Submit button <button type="submit" [disabled]="!contactForm.valid">Submit</button> Displaying the Validation/Error messages • Angular creates a FormControl for each and every field, which has ngModel directive applied. The FormControl exposes the state of form element like valid, dirty, touched etc. Adding Minlength Validator Let us make the minimum length of the First Name to 10. <div [hidden]="!contactForm.controls.firstname.errors.minlength"> First Name Minimum Length is {{contactForm.controls.firstname.errors.minlength?.requiredLength}} </div>