Angular Note Given by R.K Sir
Angular Note Given by R.K Sir
Introduction 1.1
Setting up the environment 1.2
Angular CLI 1.3
TypeScript
TypeScript Fundamentals 2.1
Components
Components 3.1
Working with data 3.2
Event binding 3.3
Built In Directives
Structural Directives 4.1
Attribute Directives 4.2
Pipes
Introduction 6.1
Built In Pipes 6.2
Custom Pipes 6.3
1
2
Introduction
Angular Framework
Attend the demo at Satya technologies. we have week end and regular batches also.
3
Setting up the environment
we are going to use [Link] and npm (node package manager) for tooling purposes. We
need
them for downloading tools, libraries, and packages.
[Link] is a platform built on top of V8, Google's JavaScript runtime, which also powers
the Chrome browser
[Link] is used for developing server-side JavaScript applications
The npm is a package manager for [Link], which makes it quite simple to install
additional tools via packages; it comes bundled with [Link]
Once we install [Link], run the following commands on the command line in Windows or
Terminal in macOS to verify that [Link] and npm are installed and set up properly:
$ node -v
$ npm -v
4
Angular CLI
To write a simple hello world application, we initially had to create a lot of files with
boilerplate code and project configuration. This process is common for both small and large
applications.
For large applications, we create a lot of modules, components, services, directives, and
pipes with boilerplate code and project configuration. This is a very time-consuming process.
Since we want to save time and be productive by focusing on solving business problems
instead of spending time on tedious tasks, tooling comes in handy.
The Angular team created a command-line tool know as Angular CLI. The Angular CLI helps
us in generating Angular projects with required configurations, boilerplate code, and also
downloads the required node packages with one simple command. It also provides
commands for generating components, directives, pipes, services, classes, guards,
interfaces, enums, modules, modules with routing and building, running and testing the
applications locally.
The Angular CLI is available as a node package. First, we need to download and install it
with the following command:
The preceding command will install Angular CLI, we can then access it anywhere via
command line or Terminal.
To generate the Angular project using CLI we can use the ng g new project-name command.
ng new hello-world
This command creates a folder named hello-world, generates Angular project under it with
all the required files and downloads all the node packages.
5
Angular CLI
installing ng2
2 create .editorconfig
3 create [Link]
4 create src/app/[Link]
5 create src/app/[Link]
6 create src/app/[Link]
7 create src/app/[Link]
8 create src/app/[Link]
9 create src/assets/.gitkeep
10 create src/environments/[Link]
11 create src/environments/[Link]
12 create src/[Link]
13 create src/[Link]
14 create src/[Link]
15 create src/[Link]
16 create src/[Link]
17 create src/[Link]
18 create src/[Link]
19 create .[Link]
20 create e2e/[Link]
21 create e2e/[Link]
22 create e2e/[Link]
23 create .gitignore
24 create [Link]
25 create [Link]
26 create [Link]
27 create [Link]
28 Successfully initialized git.
29 Installing packages for tooling via npm.
30 Installed packages for tooling via npm.
To run the application, we need to navigate to the project folder and run the ng serve
command:
$ cd hello-world
$ ng serve
The ng serve command compiles and builds the project, and starts the local web server at
[Link] URL. When we navigate to [Link] URL in the browser, we
see the following output:
6
Angular CLI
7
TypeScript Fundamentals
TypeScript is a superset of JavaScript, which means all the code written in JavaScript is
valid TypeScript code, and TypeScript compiles back to simple standards-based JavaScript
code, which runs on any browser, for any host, on any OS.
All the ECMAScript 5 code is valid in js6. all js6 code is valid TypeScript code.
Installing TypeScript
Once you have [Link] setup, the next step is to install TypeScript. Make sure you install at
least version 2.1 or greater.
The preceding command will install the TypeScript compiler and makes it available globally.
We can compile TypeScript code into JavaScript by invoking the TypeScript compiler using
the following command:
DataTypes
Important data types in TypeScript.
String: -
In TypeScript, we can use either double quotes (") or single quotes (') to surround strings
similar to JavaScript.
Number: -
Boolean: -
8
TypeScript Fundamentals
Array: -
We have two different syntaxes to describe arrays, and the first syntax uses the element
type followed by []:
Any: -
If we need to opt out type-checking in TypeScript to store any value in a variable whose type
is not known right away, we can use any keyword to declare that variable:
eventId = 'event1';
Void: -
The void keyword represents not having any data type. Functions without return keyword do
not return any value, and we use void to represent it.
Functions: -
Functions are the fundamental building blocks of any JavaScript application. In JavaScript,
we declare functions in two ways.
function sum(a, b) {
return a + b;
}
9
TypeScript Fundamentals
Classes: -
In JavaScript ES5 object oriented programming was accomplished by using prototype-based
objects.
To define a class we use the new class keyword and give our class a name and a body:
class Person{
name;
sayHello(){
return 'Hello'+[Link];
}
Properties: -
10
TypeScript Fundamentals
Properties define data attached to an instance of a class. For example, a class named
Person might
have properties like first_name, last_name and age.
Each property in a class can optionally have a type. For example, we could say that the
first_name
and last_name properties are strings and the age property is a number.
class Person {
first_name: string;
last_name: string;
age: number;
}
Methods: -
Methods are functions that run in context of an object. To call a method on an object, we first
have
to have an instance of that object.
To instantiate a class, we use the new keyword. Use new Person() to create a new insta
nce of the Person class.
class Person {
first_name: string;
last_name: string;
age: number;
getFullName(){
return this.first_name+' '+this.last_name;
}
var p: Person;
p = new Person();
11
TypeScript Fundamentals
// give it a first_name
p.first_name = 'Raju';
[Link]();
Constructors: -
A constructor is a special method that is executed when a new instance of the class is being
created.
Constructor methods must be named constructor. They can optionally take parameters but
they can’t return any values, since they are called when the class is being instantiated (i.e.
an instance of the class is being created, no other value can be returned).
class Person {
firstName = "";
lastName = "";
constructor(firstName, lastName) {
[Link] = firstName;
[Link] = lastName;
}
getFullName(){
return [Link]+' '+[Link];
}
Inheritance: -
Inheritance is a way to indicate that a class receives behavior from a parent class. Then we
can override, modify or augment those behaviors on the new class.
Person class:
12
TypeScript Fundamentals
class Person {
firstName = "";
lastName = "";
constructor(firstName, lastName) {
[Link] = firstName;
[Link] = lastName;
}
getFullName(){
return [Link]+' '+[Link];
}
Student class: -
getDetails() {
return `${[Link]()} and i'm studying ${[Link]}`;
}
}
Interfaces: -
Interfaces provides the structure for the data.
interface Human {
firstName: string;
lastName: string;
getFullName?: Function;
}
13
TypeScript Fundamentals
• if you pass more arguments than the number of the parameters, the extra arguments are
ignored
(well, you can still use them with the special arguments variable, to be accurate).
• if you pass less arguments than the number of the parameters, the missing parameter will
be set to
undefined.
here the size and page variables default values are 10 and 1.
Variable hoiting
a variable which declares at the top of the function, even if you declared it later. we have
only two scopes in the JS. function scope and global scope. we dont have block scope. to
solve this problem we use latest variable creation syntax by using let.
let has been introduced to replace var in the long run, so you can pretty much drop the good
old var keyword and start using let instead.
Constants
ES6 introduces const to declare… constants! When you declare a variable with const, it has
to be
initialized and you can’t assign another value later.
As for variables declared with let, constants are not hoisted and are only declared at the
block level.
Arrow functions
One very useful feature in ES6 is the new arrow function syntax, using the 'fat arrow'
operator (⇒). It is SO useful for callbacks and anonymous functions!
14
TypeScript Fundamentals
getUser(login)
.then(function (user) {
return getRights(user); // getRights is returning a promise
})
.then(function (rights) {
return updateMenu(rights);
})
getUser(login)
.then(user => getRights(user))
.then(rights => updateMenu(rights))
Arrows are a great way to cleanup your inline functions. It makes it even easier to use
higher-order
functions in JavaScript.
Template Strings
In ES6 new template strings were introduced. The two great features of template strings are
2. Multi-line strings
Variables in strings
The idea is that you can put variables right in your strings. means we can inject the values
into the string.
15
TypeScript Fundamentals
// interpolate a string
var greeting = `Hello ${firstName} ${lastName}`;
[Link](greeting);
Multiline strings
var template = `
<div>
<h1>Hello</h1>
<p>This is a great website</p>
</div>
`
Multiline strings are a huge help when we want to put strings in our code that are a little long,
like
templates.
1) set
2) get
3) has
4) delete
16
TypeScript Fundamentals
5) clear
[Link]("A");
[Link]([Link]);
[Link]();
[Link]([Link]);
Set also represents the group of values like array. but it wont allow the duplicate values.
17
TypeScript Fundamentals
// Set
let set = new Set();
[Link]('A');
[Link]('B');
[Link]('C');
[Link]([Link]('A'));
[Link]('A');
[Link]([Link]);
[Link]();
[Link]([Link]);
Modules
A standard way to organize functions in namespaces and to dynamically load code in JS has
always
been lacking. NodeJS has been one of the leaders in this. JS6 aims to create a syntax using
the best from both worlds, without caring about the actual
In student_services.js:
18
TypeScript Fundamentals
the new keyword export does a straightforward job and exports the
two functions.
With a wildcard, you have to use an alias, and I kind of like it, because it makes the rest of
the code clearer:
19
Components
Components are a feature of Angular that let us create a new HTML language and they are
how we structure Angular applications.
HTML comes with a bunch of pre-built tags like <input> and <form> which look and behave
a certain way. In Angular we create new custom tags with their own look and behaviour.
An Angular application is therefore just a set of custom tags that interact with each other, we
call these tags Components.
Component is a combination of a view (the template) and some logic (our TS class).
Our application itself is a simple component. To tell Angular that it is a component, we use
the @Component decorator. To be able to use it, we have to import it:
If you’re new to TypeScript then the syntax of this next statement might seem a little foreign:
@Component({
// ...
})
We want to be able to use this component in our markup by using a <student-list> tag.
1 @Component({
2 selector: 'student-list'
3 // ... more here
4 })
The selector property here indicates which DOM element this component is going to use.
20
Components
In this case, any <student-list></student-list> tags that appear within a template will be
compiled using the StudentListComponent class and get any attached functionality.
This means that we will load our template from the file [Link] in the
same directory as our component.
Adding a template
We can define templates two ways, either by using the template key in our @Component
object or by specifying a templateUrl.
@Component({
selector: 'student-list',
template: `
<p>
//logic
</p>
`
})
21
Working with data
In a web application, we need to display data on an HTML page and read the data from
input controls on an HTML page.
Displaying data
we have multiple syntaxes to display the data in the angular.
Interpolation syntax
The double curly braces are the interpolation syntax in Angular. we also call it as
interpolation.
Ex: -
{{message}}
For any property on the class that we need to display on the template, we can use the
property name surrounded by double curly braces. Angular will automatically render the
value of the property in the browser.
template: `
<h1>{{message}}</h1>
<input type="text" value="{{message}}"/>
Notice that the preceding template is a multiline string, and it is surrounded by (backtick)
symbols instead of single or double quotes.
Interpolation syntax is one-way data binding, and data flows from the data source
(Component class) to view (template).
Only the value of the property is updated on the template, it will not happen vice-versa, that
is, changes made to controls on the template will not update the property value.
Property binding
Property binding is another form of data binding syntax in Angular.
22
Working with data
element-property-name: Specifies the property of the corresponding DOM element for the
HTML tag or custom tag property name surrounded by square brackets
template: `
<h1 [textContent]="message"></h1>
<input type="text" [value]="message"/>`
Instead of using interpolation syntax, we are wrapping the textContent property of the <h1>
tag and value property input tag in square braces, and on the right side of this expression,
we are assigning the Component class properties. The output will be the same as when we
are using interpolation syntax.
Property binding syntax is also one-way data binding, data flows from data source
(Component class) to view (template).
Attribute binding
Angular always uses properties to bind the data. But if there is no corresponding property for
the attribute of an element, Angular will bind data to attributes. Attribute binding syntax starts
with the keyword attr followed by the name of the attribute and then assigns it to the property
of the Component class or an expression:
<td [[Link]]="colSpanValue"></td>
23
Event binding
Using event binding syntax, we can bind built-in HTML element events, such as
click,change, blur, and so on, to Component class methods. We can also bind custom
events on components or directives,
Event binding syntax uses parenthesis symbols ().We need to surround the event property
name with parenthesis symbols () on the left side of the expression, on the right side we will
specify one of the Component methods which will be invoked when the event is triggered.
showMessage() {
alert("You pressed a key on keyboard!");
}
We have added a method named showMessage() to the AppComponent class, this method
will be invoked whenever we type a key in the text box.
template: `
<h1>{{message}}</h1>
<input type="text" [value]="message" (keypress)="showMessage()"/> `
We have added a keypress event surrounded by parenthesis symbols on the text box to
bind with the showMessage() method in the AppComponent class.
24
Event binding
@Component({
selector: 'event-binding-app',
template: `
<p>{{message}}</p>
<input type="text" (keypress)="showMessage($event)"/>
`
})
export class AppComponent {
showMessage(onKeyPressEvent) {
[Link] = [Link];
}
To the showMessage method, we are passing a special Angular $event object $event
keyword represents the current DOM event object
On the AppComponent class showMessage method, we are accepting $event passed
from template into the onKeyPressEvent method parameter
Every DOM event object has a target property, which represents the DOM element on
which the current event is raised
We are using the [Link] object, which represents the text box
We are using the [Link] property to access to the text box value
We are assigning the value of the text box to the message property
25
Structural Directives
Angular provides a number of built-in directives, which are attributes we add to our HTML
elements that give us dynamic [Link] comes with very few directives, the
remaining directives in AngularJS 1 are replaced with new concepts of Angular.
Structural Directives
The structural directives allow us to change the DOM structure in a view by adding or
removing elements. In this section, we will explore built-in structural directives, ngIf, ngFor,
and ngSwitch.
ngIf
The ngIf directive is used when you want to display or hide an element based on a
condition. The
condition is determined by the result of the expression that you pass into the
directive.
The ngIf directive is used for adding or removing elements from DOM dynamically:
If the condition is true, Angular will add content to DOM, if the condition is false it will
physically remove that content from DOM:
<div *ngIf="isReady">
<h1>Structural Directives</h1>
<p>They lets us modify DOM structure</p>
</div>
when isReady value is true, the content inside the <div> tag will be rendered on the page,
whenever it is false, both tags inside the <div> tag will be completely removed from DOM.
The asterisk (*) symbol before ngIf is a must.
Scenarios: -
ngSwitch
26
Structural Directives
<div class="container">
<div *ngIf="myVar == 'A'">Var is A</div>
<div *ngIf="myVar == 'B'">Var is B</div>
<div *ngIf="myVar != 'A' && myVar != 'B'">Var is something else</div>
</div>
But as you can see, the scenario where myVar is neither A nor B is verbose when all we’re
trying to express is an else.
Ex:-
ngFor
The ngFor is a repeater directive, it's used for displaying a list of items. We use ngFor mostly
with arrays in JavaScript, but it will work with any iterable object in JavaScript. The ngFor
directive is similar to the for...in statement in JavaScript.
The role of this directive is to repeat a given DOM element (or a collection of DOM
elements) and
pass an element of the array on each iteration.
example:
27
Structural Directives
The framework is an array of frontend framework names. Here is how we can display all of
them using ngFor:
<ul>
<li *ngFor="let framework of frameworks">
{{framework}}
</li>
</ul>
The preceding code uses ngFor to display the list of framework names. Let us understand
each part of the ngFor syntax:
There are multiple segments in the ngFor syntax, which are *ngFor, let framework, and
frameworks. We will now see them in detail:
frameworks: This is a array and data source for the ngFor directive on which it will
iterate.
let framework: let is a keyword used for declaring the template input variable. The
template input variable represents a single item in the list during iteration. We can use a
framework variable inside an ngFor template to refer to the current item of iteration.
*ngFor: ngFor represents the directive itself, the asterisk (*) symbol before ngFor is a
must.
[Link] = [
{ name: 'Ram', age: 35, area: 'AmeerPet' },
{ name: 'Robert', age: 12, area: 'S R Nagar' },
{ name: 'Raheem', age: 22, area: 'Yousuf Guda' }
];
28
Structural Directives
Getting an index: -
There are times that we need the index of each item when we’re iterating an array.
We can get the index by appending the syntax let idx = index to the value of our ngFor
directive, separated by a semi-colon.
1 Ram 35 Ameerpet
2 Robert 12 S R Nagar
29
Structural Directives
30
Attribute Directives
ngStyle
The ngStyle directive is used when we need to apply multiple inline styles dynamically to an
element.
With the NgStyle directive, you can set a given DOM element CSS properties from Angular
expressions.
For example:
<div [[Link]-color]="'yellow'">
Uses fixed yellow background
</div>
This snippet is using the NgStyle directive to set the background-color CSS property to the
literal
string 'yellow'.
Another way to set fixed values is by using the NgStyle attribute and using key value pairs
for each property you want to set.
But the real power of the NgStyle directive comes with using dynamic values.
<p [ngStyle]="getInlineStyles(framework)">{{framework}}</p>
ngClass
31
Attribute Directives
The NgClass directive, represented by a ngClass attribute in your HTML template, allows
you to dynamically set and change the CSS classes for a given DOM element.
Ex: -
.red {
color: red;
text-decoration: underline;
}
.bolder {
font-weight: bold;
}
geClasses(framework) {
let classes = {
red: [Link] > 3,
bolder: [Link] > 4
};
return classes;
}
In the template,
<p [ngClass]="geClasses(framework)">{{framework}}</p>
32
Input properties
The real-world applications will be complex, and they will have multiple components. We are
going to rewrite our application to use multiple components and understand how these
components communicate with each other.
Input Properties
Inputs specify the parameters we expect our component to receive. To designate an input,
we
use the @Input() decoration on a component class property.
Ex1
Now the student property of the StudentDetailsComponent class is available for property
binding.
33
Output properties
When we want to send data from your component to the outside world, we use output
bindings.
34
Introduction
Pipes are used to transform data, when we only need that data transformed in a template.
If we need the data transformed generally we would implement it in our model, for example
we have a number 1234.56 and want to display it as a currency such as $1,234.56.
We could convert the number into a string and store that string in the model but if the only
place we want to show that number is in a view we can use a pipe instead.
We use a pipe with the | syntax in the template, the | character is called the pipe character.
{{ 1234.56 | currency }}
O/P:
USD1,234.56.
A pipe can accept optional parameters to modify the output. To pass parameters to a pipe,
simply add a colon and the parameter value to the end of the pipe expression:
pipeName: parameterValue
Ex:
O/P:
USD1,234.56.
35
Built In Pipes
CurrencyPipe
Its first argument is an abbreviation of the currency type (e.g. "EUR", "USD", and so on).
{{ 1234.56 | currency:'GBP' }}
instead of the abbreviation of GBP we want the currency symbol to be printed out we pass
as a second parameter the boolean true.
{{ 1234.56 | currency:"GBP":true }}
DatePipe
DecimalPipe
36
Built In Pipes
{minIntegerDigits}. {minFractionDigits}-{maxFractionDigits}
Ex:
O/P:
003.14
3.1415
JsonPipe
O/P
[Object Object]
{ "id":1,"name":"RK"}
PercentPipe
37
Built In Pipes
O/P
12.346%
12.35%
012.3456%
SlicePipe
This returns a slice of an array. The first argument is the start index of the slice and the
second argument is the end index.
If either indexes are not provided it assumes the start or the end of the array and we can use
negative indexes to indicate an offset from the end.
O/P
2,3
3,4,5,6
3,4,5
38
Custom Pipes
Angular allows you to create your own custom pipes based on your project requirement.
have the @Pipe decorator with pipe metadata that has a name property. This value will
be used to call this pipe in template expressions. It must be a valid JavaScript identifier.
implement the PipeTransform interface's transform method. This method takes the
value being piped and a variable number of arguments of any type and return a
transformed ("piped") value.
Pipe decorator
To create a pipe we use the @Pipe decorator and annotate a class like so:
The name parameter for the Pipe decorator is how the pipe will be called in templates.
Transform function
The actual logic for the pipe is put in a function called transform on the class.
39
Custom Pipes
Pipes are a way of having a different visual representation for the same piece of data without
storing unnecessary intermediate data on the component.
40