0% found this document useful (0 votes)
115 views

Angular

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
115 views

Angular

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Angular

What is Angular CLI ?


The Angular CLI helps us to quickly create an Angular application with
all the configuration files and packages in one single command. It also
helps us to add features (components, directives, services, etc) to
existing Angular applications.

The Angular CLI creates the Angular Application and uses Typescript,
Webpack ( for Module bundling), Karma ( for unit testing), Protractor (
for end to end testing).

Creating a new Angular Application


The creation of your First Project Angular has become very simple
using Angular CLI. All you need to run the command from the Prompt.

ng new GettingStarted

The above command will create a folder GettingStarted and copies all
the required dependencies and configuration settings.

1. Creates a new directory GettingStarted is created


2. Sets up the folder structure for the application
3. Downloads and installs Angular libraries and any other
dependencies
4. Installs and configures TypeScript
5. Installs and configures Karma & Protractor for testing
Running your new Angular Project
To run your application all you need to do is type the following
command.
ng serve
● The above command compiles the Angular application and invokes the
Webpack development server. The server keeps a watch on our project
folder. If you make any changes in the code, it compiles the project
again.
● You can also use npm start.
● The Webpack Development server listens on HTTP Port 4200. Hence
open the browser and type http://localhost:4200/ and you will see the
GettingStarted app is running displayed on the browser.
Angular project Folder structure

The root folder application contains subfolders e2e, node_modules


and src. It also contains a few configuration files.
❖ .editorconfig: This is the configuration file for the Visual Studio
code editor. You can visit http://editorconfig.org for more
information.
❖ .gitignore: Git configuration to make sure auto generated files are
not committed to source control.
❖ angular.json: This is the configuration file for Angular CLI. The
older versions of Angular used the file angular-cli.json.
❖ karma.conf.js: The Configuration file for the karma test runner.
❖ package.json: The package json is an npm configuration file that
lists the third-party packages that your project depends on. We
also have package-lock.json.
❖ README.md: The README.md file.
❖ tsconfig.json, tsconfig.app.json & tsconfig.spec.json are
Typescript configuration files. The tsconfig.json is the Typescript
compiler configuration file. This file specifies the compiler
options required for the Typescript to compile (transpile) the
project. The tsconfig.app.json is used for compiling the code,
while tsconfig.spec.json for compiling the tests.
❖ tslint.json: tslint is a static code analysis tool. We use this to
check Typescript code quality. To check if TypeScript source
code complies with coding rules. TSLint checks your TypeScript
code for readability, maintainability, and functionality errors.

e2e
This folder contains the files required for end to end tests by
protractor.
node_modules
All our external dependencies are downloaded and copied here by
NPM Package Manager.

src
This is where our application lives.

app folder
The Angular CLI has created a simple application, which works out of the box.
It creates the root component, a root module, a unit test class to test the
component. Now let us see each component of the application one at a time.

The Component
The app.component.ts is the component that is added to the project by Angular
CLI. You will find it under the folder app/src.

The component class is the most important part of our application. It consists
of three main parts i.e. a class, a class decorator, and an import statement
Import statement
import { Component } from '@angular/core';
The import statement is used to import the libraries that are used in our
component class. Our Component is decorated with the @Component
decorator, which is part of the @angular/core module. Hence we need to refer it
in our class.

Component class

The component is a simple class. We define it using the export keyword. The
other parts of the app can import it and use it. The above component class
has one property title. This title is displayed when the application is run.

The component class can have many methods and properties. The main
purpose of the component is to supply logic to our view.

@Component decorator
The AppComponent class is decorated with @Component decorator. The
@Component (called class decorator) provides Metadata about our component.
The Angular uses this Metadata to create the view.

The @component Metadata above has three fields. The selector, templateURL &
styleUrls
templateUrl

The templateUrl contains the path to the HTML template file. Angular uses this
HTML file to render the view. In the above example, it points to the
app.component.html file.

styleUrls

The styleUrls is an array of Style Sheets that Angular uses to style our HTML
file. In the above example, it points towards the app.component.css style
sheet.

The app.component.css file is in the same folder as the AppComponent. The file is
empty. You can create styles for the component and put it here

selector

The selector tells angular, where to display the template. In the above example,
selector is app-root. The Angular whenever it encounters the above tag in the
HTML file it replaces it with the template (app.component.html)

The app-root selector is used in index.html.

Root Module
Angular organizes the application code as Angular Modules.Every application
must have at least one module.
The Module, which loads first is the Root Module. This Module is our root
module.
The root module is called app.module.ts. (under src/app folder). It contains the
following code.
The structure of the Angular module is similar to the component class. Like
Components, it consists of three parts. A class, class decorator and import
statement.

Module class
export class AppModule { }

Similar to the component, the Module class is defined with the export
keyword. Exporting the class ensures that you can use this module in
other modules.
@NgModule class decorator

We used @component decorator to define our component. The


Angular Modules require a @ngModule decorator. @ngModue
decorator passes the metadata about the module.

The @ngModule Metadata above has four fields. The declarations,


imports, providers, & bootstrap.

Imports Metadata tells the angular list of other modules used by this
module. We are importing BrowserModule and AppRoutingModule.

The BrowserModule is the core angular module, which contains


critical services,directives, and pipes, etc.

The AppRoutingModule defines the application Routes.

Declaration Metadata lists the component, directives, pipes that are


part of this module.
Providers are the services that are part of this module, which can be
used by other modules.

Bootstrap Metadata identifies the root component of the module.


When Angular loads the appModule it looks for bootstrap Metadata
and loads all the components listed here. We want our module to load
AppComponent , hence we have listed it here.

App Routing Module

The AppRoutingModule in the file app-routing.module.ts defines the


Routes of the application. These Routes tells Angular how to move
from one part of the application to another part or one View to another
View.

The Routes defined in the constant const routes: Routes = [];, which is
empty
This Module is defined as a separate Module and is imported in
AppModule.
Bootstrapping our root module
The app.component.html is the file, which we need to show to the user. It is
bound to the AppComponent component. We indicated that the AppComponent
is to be bootstrapped when AppModule is loaded

Now we need to ask Angular to load the AppModule when the application is
loaded. This is done in main.ts files.

Index.html
Index.html is the entry point of our application.

The selector app-root, which we defined in our component metadata, is used as


an HTML tag. The Angular scans the HTML page and when it finds the tag
<app-root><app-root> replaces the entire content with content of
app.component.html

Assets
A folder where you can put images and other things.
Environments
The environment folder is where we define environment variables for various
build setups. The build setups can be development, production, testing &
staging. Angular has created two build environments out of the box. One is
development, which is the default and the other one in Production. The two
files environment.ts is the default for development and the environment.prod.ts is
for the production build.

polyfills.ts
Different browsers have different levels of support of the web
standards. Polyfills help normalize those differences.

styles.css
Your Angular global styles go here. Most of the time you’ll want to
have local styles in your components for easier maintenance, but
styles that affect all of your apps need to be in a central place.

test.ts
This is the main entry point for your unit tests. It has some custom
configuration that might be unfamiliar, but it’s not something you’ll
need to edit.

Summary
To create a new project in Angular, we must install angular/cli first. We
use ng new <name> to create new projects. The Angular CLI does an
excellent job of downloading all the required libraries and configuring
the app. We use ng serve to run our application, which starts the
Webpack development server at port 4200. In the subsequent
tutorials, we learn more about Angular.
Bootstrap
What is Bootstrap ?
● Bootstrap is the most popular HTML, CSS and JavaScript framework for
developing a responsive and mobile friendly website.

● It is absolutely free to download and use.

● It is a front-end framework used for easier and faster web development.

● It includes HTML and CSS based design templates for typography, forms,
buttons, tables, navigation, modals, image carousels and many others.

● It facilitates you to create responsive design

What is a responsive website?


A website is called a responsive website which can automatically adjust itself to look
good on all devices, from smartphones to desktops etc.

We can install the Bootstrap CSS file in one of the following ways.

1. Add Bootstrap using CDN.


2. Install the bootstrap npm package.

npm i [email protected]
npm i [email protected]

What is Angular Data Binding


Data binding is a technique, where the data stays in sync between the
component class and the view. Whenever the user updates the data in the
view, Angular updates the component. When the component gets new data,
the Angular updates the view.
There are many uses of data binding. You can show tables to the user
dynamically, Change element style on the basis of some condition, respond to
user events, etc.

Data Binding in Angular


The data binding in Angular can be broadly classified into two groups. One
way binding or two-way binding

One way binding


In one way binding data flows from one direction. Either from view to
component class or from component class to view.

From Component to View


To bind data from component to view, we make use of Interpolation &
Property Binding.

From View to Component


Event Binding
It is one way from view to component. By tracking the user events in the
view and responding to it, we can keep our component in sync with the view.

Two Way binding


Two-way binding means that changes made to our model in the component
are propagated to the view and that any changes made in the view are
immediately updated in the underlying component
Two-way binding is useful in data entry forms. Whenever a user makes
changes to a form field, we would like to update our model. Similarly, when
we update the model with new data, we would like to update the view as well

The two-way binding uses the special syntax known as a banana in a box [()]

Interpolation:
It is one way data binding as the data flows from the component to view.
Interpolation syntax

The Angular uses the {{ }} (double curly braces) in the template to denote the
interpolation. The syntax is as shown below.

{{ templateExpression }}

Invoke a method in the component

We can invoke the component’s methods using interpolation.

1
2 //Template
3
4 {{getTitle()}}
5
6
7 //Component
8 title = 'Angular Interpolation Example';
9 getTitle(): string {
10 return this.title;
11 }
12

Perform some mathematical operations


1
2 <h2>Mathematical Operations</h2>
3
4 <p>100x80 = {{100*80}}</p>
5 <p>Largest: {{max(100, 200)}}</p>
6
7 //Component
8 max(first: number, second: number): number {
9 return Math.max(first, second);
10 }
11

Bind to an element property

We can use it to bind to a property of the HTML element, a component, or a


directive. in the following code, we bind to the style.color property of the <p>
element. We can bind to any property that accepts a string.

1
2 <p>Show me <span class = "{{giveMeRed}}">red</span></p>
3 <p style.color={{giveMeRed}}>This is red</p>
4

Bind to an image source

1
2 <div><img src="{{itemImageUrl}}"></div>
3

href

1
2
3 <a href="/product/{{productID}}">{{productName}}</a>
NgNonBindable

Use ngNonBindable to tell Angular not to compile or bind the contents of the
current DOM element. I.e any expression is not evaluated but shown as it is.

<p>Evaluate: {{variable}}</p>
<p ngNonBindable>Do not evaluate: {{variable}}</p>

List of Pipes
Decimal Pipes
DatePipe
DecimalPipe
JsonPipe
LowerCasePipe
UpperCasePipe
SlicePipe

Decimal Pipes
This pipe is used for transformation of decimal numbers.

The first argument is a format string of the form ”{minIntegerDigits}.


{minFractionDigits}-{maxFractionDigits}”, like so:
<p ngNonBindable>{{ 3.14159265 | number: '1.1-2' }}</p>
<p>{{ 3.14159265 | number: '1.1-2' }}</p>
<p ngNonBindable>{{ 3.14159265 | number: '1.4-4' }}</p>
<p>{{ 3.14159265 | number: '1.4-4' }}</p>

DatePipe
This pipe is used for the transformation of dates. The first argument is a
format string, like so:

<p ngNonBindable>{{ dateVal | date: 'shortTime' }}</p> (1)

<p>{{ dateVal | date: 'shortTime' }}</p>

<p ngNonBindable>{{ dateVal | date:'fullDate' }}</p>

<p>{{ dateVal | date: 'fullDate' }}</p>

<p ngNonBindable>{{ dateVal | date: 'd/M/y' }}</p>

<p>{{ dateVal | date: 'd/M/y' }}</p>

dateVal is an instance of new Date().

This transforms a JavaScript object into a JSON string, like so:

<p ngNonBindable>{{ jsonVal }}</p> (1)

<p>{{ jsonVal }}</p>

<p ngNonBindable>{{ jsonVal | json }}</p>

<p>{{ jsonVal | json }}</p>

jsonVal is an object declared as { moo: 'foo', goo: { too: 'new' }}.

LowerCasePipe

This transforms a string to lowercase, like so:


<p>{{ 'ASIM' | lowercase }}</p>

UpperCasePipe

This transforms a string to uppercase, like so:


<p ngNonBindable>{{ 'asim' | uppercase }}</p>

<p>{{ 'asim' | uppercase }}</p>

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, like so:

<p ngNonBindable>{{ [1,2,3,4,5,6] | slice:1:3 }}</p>

<p>{{ [1,2,3,4,5,6] | slice:1:3 }}</p>

<p ngNonBindable>{{ [1,2,3,4,5,6] | slice:2 }}</p>

<p>{{ [1,2,3,4,5,6] | slice:2 }}</p>

<p ngNonBindable>{{ [1,2,3,4,5,6] | slice:2:-1 }}</p>


<p>{{ [1,2,3,4,5,6] | slice:2:-1 }}</p>

innerText
disabled
textContent

Property Binding
● Property binding is one way from component to view.
● You can set the properties such as class, href, src, textContent, etc using
property binding.

Property Binding Syntax


The Property Binding uses the following Syntax

[binding-target]=”binding-source”

The binding-target (or target property) is enclosed in a square bracket [].


Binding-source is enclosed in quotes and we assign it to the binding-target.
It can be property in the component, method in component, a template
reference variable or an expression containing all of them.

Whenever the value of Binding-source changes, the view is updated by the


Angular.

<h1 [innerText]="title"></h1>

<h2>Example 1</h2>
<button [disabled]="isDisabled">I am disabled</button>

<p [innerHTML]="text1"></p>
<div [innerHTML]="text2"></div>
<img [src]="itemImageUrl" height=’300px’ width=’300px’>

4
//Component
itemImageUrl="https://angular.io/assets/images/logos/angular/[email protected]"
<input type="text" (input)="handleInput($event)">
<p>You have entered {{value}}</p>

<h1 style="text-align:center" (copy)="copyEvent()" (cut)="cutEvent()"


>Events Demo</h1><br>
<div class="alert alert-primary m-b-2" role="alert">
<button class="btn btn-primary" (click)="clickEvent()">Click
Event</button>
</div>
<div class="alert alert-primary m-b-2" role="alert">
<button class="btn btn-info" (dblclick)="dblclickEvent()">Double
Click</button>
</div>

<div class="alert alert-primary m-b-2" role="alert">

<input type="text" (blur)="blurEvent()" (cut)="cutEvent()"


(paste)="pasteEvent()" value="Blur event ">
</div>

https://www.eduforbetterment.com/lists-of-useful-events-types-for-event-bi
nding-in-angular/

=======================================================================
ngModel

Angular uses the ngModel directive to achieve the two-way binding on HTML
Form elements. It binds to a form element like input, select, selectarea. Etc

The ngModel directive is not part of the Angular Core library. It is part of the
@angular/forms. You need to import the FormsModule package into your
Angular module.

import { FormsModule } from '@angular/forms';

Then you can use it using the two-way binding syntax as shown below
<input type="text" name="value" [(ngModel)]="value">

<input type="text" name="value" [(ngModel)]="value">

When you bind to a ngModel directive, behind the scenes it sets up property
binding & event binding. It binds to the value property of the element using
property binding. It then uses the ngModelChange event to set up the event
binding to listen to the changes to the value.

<input [ngModel]="email" (ngModelChange)="email = $event">


Directive
The Angular directive helps us to manipulate the DOM. You can change the
appearance, behavior, or layout of a DOM element using the Directives. They
help you to extend HTML
There are three kinds of directives in Angular:
1. Component Directive
2. Structural directives
3. Attribute directives

Structural Directives
Structural directives can change the DOM layout by adding and removing DOM
elements. All structural Directives are preceded by Asterix symbol.

Commonly used structural directives

ngFor

The ngFor is an Angular structural directive, which repeats a portion of the


HTML template once per each item from an iterable list (Collection).

Example of ngFor

Angular ngFor directive iterates over a collection of data like an array, list, etc,
and creates an HTML element for each of the items from an HTML template.
It helps us to build lists or tables to display tabular data in a nice way.

The ngFor also exports several local variables like Index, First, Last, odd, even &
trackby.etc.
Syntax of ngFor
The syntax for the ngFor is as shown below
1
<html-element *ngFor="let <item> of <items>;”>
<html-Template></html-Template>
</html-element>

<html-element>:
is the element on which we apply ngFor directive. it repeats the
<html-element> .. </html-element> for each item of the collection.

The scope of the item is within the <html-element>..</html-element>. You can


access it anywhere within that, but not outside of it.

We use the ul to display the movies. The li element displays a single movie.
We need to repeat the li for each movie. Hence we apply the ngFor on the li
element.

Example 1:-

<!-- Example 1 -->

<h1> {{title}} </h1>


<ul>
<li *ngFor="let movie of movies">
{{ movie.title }} - {{movie.director}}
</li>
</ul>
movies: Movie[] =[
{title:'Zootopia',director:'Byron Howard, Rich Moore',cast:'Idris
Elba, Ginnifer Goodwin, Jason Bateman',releaseDate:'March 4, 2016'},
{title:'Batman v Superman: Dawn of Justice',director:'Zack
Snyder',cast:'Ben Affleck, Henry Cavill, Amy Adams',releaseDate:'March
25, 2016'},
{title:'Captain American: Civil War',director:'Anthony Russo, Joe
Russo',cast:'Scarlett Johansson, Elizabeth Olsen, Chris
Evans',releaseDate:'May 6, 2016'},
{title:'X-Men: Apocalypse',director:'Bryan Singer',cast:'Jennifer
Lawrence, Olivia Munn, Oscar Isaac',releaseDate:'May 27, 2016'},
{title:'Warcraft',director:'Duncan Jones',cast:'Travis Fimmel,
Robert Kazinsky, Ben Foster',releaseDate:'June 10, 2016'},
]

class Movie {
title : string;
director : string;
cast : string;
releaseDate : string;
}

Similarly, you can use the table element to display the movies as shown
below. Here we need to repeat the tr element for each movie. Hence apply
the directive on tr.

<div class='panel panel-primary'>


<div class='panel-heading'>
{{title}}
</div>

<div class='panel-body'>
<div class='table-responsive'>
<table class='table'>
<thead>
<tr>
<th>Title</th>
<th>Director</th>
<th>Cast</th>
<th>Release Date</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let movie of movies;">
<td>{{movie.title}}</td>
<td>{{movie.director}}</td>
<td>{{movie.cast}}</td>
<td>{{movie.releaseDate}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>

Nested Array
employees = [
{
name: "Rahul", email: "[email protected]",
skills: [{ skill: 'Angular', exp: '2' },{ skill: 'Javascript', exp: '7' },{ skill:
'TypeScript', exp: '3' }
]
},
{
name: "Sachin", email: "[email protected]",
skills: [{ skill: 'Angular', exp: '1' },{ skill: 'Android', exp: '3' },{ skill:
'React', exp: '2' }
]
},
{
name: "Laxmna", email: "[email protected]",
skills: [{ skill: 'HTML', exp: '2' },{ skill: 'CSS', exp: '2' },{ skill:
'Javascript', exp: '1' }
]
}
]

Inside the main loop, use the local variable employee to get the list of skills
and loop through it using *ngFor="let skill of employee.skills;"

<div class='card'>
<div class='card-header'>
<p>Nested Array</p>
</div>

<div class='table-responsive'>
<table class='table table-bordered table-sm '>
<thead class="thead-dark">
<tr>
<th>Name</th>
<th>Mail ID</th>
<th>Skills</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let employee of employees;">
<td>{{employee.name}}</td>
<td>{{employee.email}}</td>
<td>
<table class='table table-sm '>
<tbody>
<tr *ngFor="let skill of employee.skills;">
<td>{{skill.skill}}</td>
<td>{{skill.exp}}</td>
</tr>
</tbody>
</table>

</td>
</tr>
</tbody>
</table>
</div>
</div>
Local Variables

ngFor exposes several values, which help us to fine-tune display. We assign


these values to the local variable and use it in our template

The list of exported values provided by ngFor directive

● index: number: The zero-based index of the current element in


the collection.
● count: number: The total no of items in the collection
● first: boolean: True when the item is the first item in the
collection.
● last: boolean: Is set to True, when the item is the last item in the
collection.
● even: boolean: True when the item has an even index in the
collection.
● odd: boolean: is set to True when the item has an odd index in
the collection

Finding the Index

To Find the index, we create another local variable i and use the let to make
it equal to index.

let i=index;

<tr *ngFor="let movie of movies; let i=index;">


<td> {{i}} </td>
<td>{{movie.title}}</td>
<td>{{movie.director}}</td>
<td>{{movie.cast}}</td>
<td>{{movie.releaseDate}}</td>
</tr>
Formatting odd & even rows
We can use the odd & even values to format the odd & even rows
alternatively. To do that create two local variables o & e. Assign the
values of odd & even values to these variables using the let
statement. Then use the ngClass to change the class name to
either odd or even. The example code is shown below

<tr *ngFor="let movie of movies; let i=index; let o= odd; let e=even;"
[ngClass]="{ odd: o, even: e }">
<td> {{i}} </td>
<td>{{movie.title}}</td>
<td>{{movie.director}}</td>
<td>{{movie.cast}}</td>
<td>{{movie.releaseDate}}</td>
</tr>

.even { background-color: azure; }


.odd { background-color: floralwhite; }

let first= first; let last=last;


ngIf directive
The ngIf Directives is used to add or remove HTML elements based on an
expression. The expression must return a boolean value. If the expression
is false then the element is removed, else the element is inserted.

Example of ngIf

<div *ngIf="condition">
This is shown if condition is true
</div>

Angular's <ng-template> element defines a template that is not rendered by


default.

ngIf is a structural directive, which means that you can add it to any
element like div, p, h1, component selector, etc. Like all structural directive ,
it is prefixed with * asterisk.

Hidden attribute Vs ngIf

<p [hidden]="condition">
content to render, when the condition is true
</p>

The above achieves the same thing, with one vital difference.

ngIf does not hide the DOM element. It removes the entire element along
with its subtree from the DOM. It also removes the corresponding state
freeing up the resources attached to the element

hidden attribute does not remove the element from the DOM. But just
hides it.
By using the Logical NOT (!), you can mimic the else condition as shown
here.

<p *ngIf="!condition">

content to render, when the condition is false

</p>

Condition
The condition can be anything. It can be a property of the component
class. It can be a method in the component class. But it must evaluate to
true/false. The ngIf directive tries to coerce the value to Boolean.

ngIf else
The ngIf allows us to define optional else block using the ng-template.

<div *ngIf="condition; else elseBlock">


content to render, when the condition is true
</div>

<ng-template #elseBlock>
content to render, when the condition is false
</ng-template>

Next, we have else clause bound to a template named elseBlock. The


template can be defined anywhere using the ng-template. Place it right after
ngIf for readability.

When the condition evaluates to false, then the ng-template with the name
#elseBlock is rendered by the ngIf Directive.

ngIf then else


You can also define then else block using the ng-template.

<div *ngIf="condition; then thenBlock else elseBlock">


This content is not shown
</div>

<ng-template #thenBlock>
content to render when the condition is true.
</ng-template>

<ng-template #elseBlock>
content to render when condition is false.
</ng-template>

Here, we have then clause followed by a template named thenBlock.

When the condition is true, the template thenBlock is rendered. If false, then
the template elseBlock is rendered.

ngSwitch

The ngSwitch directive lets you add/remove HTML elements depending on


a match expression. ngSwitch directive used along with ngSwitchCase
and ngSwitchDefault

<container_element [ngSwitch]="switch_expression">
<inner_element
*ngSwitchCase="match_expresson_1">...</inner_element>
<inner_element
*ngSwitchCase="match_expresson_2">...</inner_element>
<inner_element
*ngSwitchCase="match_expresson_3">...</inner_element>
<inner_element *ngSwitchDefault>...</element>
</container_element>

ngSwitch is bound to container_element like div etc. We assign a


switch-expression to the ngSwitch via PropertyBinding syntax. Angular
evaluates the switch_expression at runtime and based on its value displays
or removes the elements from the DOM.
num: number= 0;

<div class='card'>
<div class='card-header'>
ngSwitch Example
</div>
<div class="card-body">
Input string : <input type='text' [(ngModel)]="num" />

<div [ngSwitch]="num">
<div *ngSwitchCase="'1'">One</div>
<div *ngSwitchCase="'2'">Two</div>
<div *ngSwitchCase="'3'">Three</div>
<div *ngSwitchCase="'4'">Four</div>
<div *ngSwitchCase="'5'">Five</div>
<div *ngSwitchDefault>This is Default</div>
</div>
</div>
</div>

Attribute Directives
An Attribute or style directive can change the appearance or behavior of an
element.

Commonly used Attribute directives


ngModel
The ngModel directive is used the achieve the two way data binding.
ngClass

The Angular ngClass Directive is anAngular attribute directive, which


allows us to add or remove CSS classes to an HTML element. Using
ngClass you can create dynamic styles in angular components by using
conditional expressions.

Syntax

<element [ngClass]="expression">...</element>

Where

element is the DOM element to which class is being applied

expression is evaluated and the resulting classes are added/removed from


the element. The expression can be in various formats like string, array or
an object. Let us explore all of them with example

NgClass with a String

You can use the String as expression and bind it to directly to the ngClass
attribute. If you want to assign multiple classes, then separate each class
with space as shown below.

Syntax

<element [ngClass]="'cssClass1 cssClass2'">...</element>

.red { color: red; }


.size20 { font-size: 20px; }

<div [ngClass]="red size20"> Red Text with Size 20px </div>


NgClass with Array

You can achieve the same result by using an array instead of a string as
shown below. The syntax for ngClass array syntax is as shown below.

<element [ngClass]="['cssClass1', 'cssClass2']">...</element>

<div [ngClass]="['red','size20']">Red Text with Size 20px </div>

NgClass with Object

You can also bind the ngClass to an object. Each property name of the
object acts as a class name and is applied to the element if it is true. The
syntax is as shown below.

<element [ngClass]="{'cssClass1': true, 'cssClass2': true}">...</element>

<div class="row">
<div [ngClass]="{'red':true,'size20':true}">Red Text with Size 20px</div>
</div>

NgStyle
The Angular ngStyle directive allows us to set the many inline style of a
HTML element using an expression. The expression can be evaluated at
run time allowing us to dynamically change the style of our HTML
element.

<element [ngStyle]="{'styleNames': styleExp}">...</element>


Where

element is the DOM element to which style is being applied

styleNames are style names ( ex: ‘font-size’, ‘color’ etc).


<p [ngStyle]="{'color': 'purple',
'font-size': '20px',
'font-weight': 'bold'}">
Multiple styles
</p>

<input [(ngModel)]="color" />

<div [ngStyle]="{'color': color}">Change my color</div>

Specifying CSS Units in ngStyle

CSS has several units for expressing a length, size etc. The units can be
em, ex, %, px, cm, mm, in, pt, PC etc. We prefix the units to the StyleName as
shown below.

<input [(ngModel)]="size" />


<div [ngStyle]="{'font-size.px': size}">Change my size</div>

Angular Forms
The Angular forms are used to collect the data from the user.
Some things forms are expected to do

● Initialize 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 Forms Module

Angular forms module provides all the above services out of the box. It
binds the form field to the Angular component class. It tracks changes
made to the form fields so that we can respond accordingly.The Angular
forms provide the built-in-validators to validate the inputs. You can create
your own custom-validator.It presents the validation errors to the user.
Finally, it encapsulates all the input fields into an object structure when the
user submits the form.

Angular takes two approaches to build the forms. One is Template-driven


forms approach and another one is Reactive- forms or model-driven forms
approach

Template-driven forms approach

The Template-driven approach is the easiest way to build the Angular


forms. The logic of the form is placed in the template.

Model-driven forms approach

In Reactive Forms or Model-Driven approach, the logic of the form is


defined in the component as an object. The Model-driven approach has
more benefits as it makes the testing of the component easier.
In this approach, the representation of the form is created in the
component class. This form model is then bound to the HTML elements. It
is done using the special markups.

Building Blocks of Angular Forms

The Angular Forms module consists of three Building blocks, irrespective


of whether you are using Template-driven or Reactive-forms approach.

FormControl

A Form Control represents a single input field in an Angular form.

Consider a simple Text input box.

First Name : <input type="text" name="firstname" />

As a developer, you would like to know the current value in the Text
box. You would also like to know if the value is valid or not. You would
like to be notified when the user changes value.

The FormControl is an object that encapsulates all this information


related to the single input element. It Tracks the value and validation
status of each of these control
The FormControl is just a class. A FormControlis created for each form
field. We can refer them in our component class and inspect its
properties and methods

You can use FormControl to set the value of the Form field, find the
status of form field like (valid/invalid, pristine/dirty, touched/untouched
) etc & add validation rules to it.

FormGroup

FormGroup is a collection of FormControl . Each FormControl is a


property in a FormGroup . with the control name as the key.

Often forms have more than one field. It is helpful to have a simple way to
manage the Form controls together.

city : <input type="text" name="city" >


Street : <input type="text" name="street" >
PinCode : <input type="text" name="pincode" >

Angular Template-driven Forms is one of the two ways of building forms


in Angular.we build a simple HTML form using a few form elements. The
ngForm directive will convert it to the Template-driven form and create the
top-level FormGroup control.Next, we use the ngModel directive to create the
FormControl instance for each of the HTML form elements. Later, we will
learn how to submit the form data to the component class. We will also
learn how to initialize or reset the form data and use the data binding to
access the data in the component class.
The Template-driven forms

1. The form is set up using ngForm directive


2. controls are set up using the ngModel directive
3. ngModel also provides the two-way data binding
4. The Validations are configured in the template via directives.

Template-driven forms are

1. Contains little code in the component class


2. Easier to set up

While they are

1. Difficult to add controls dynamically


2. Unit testing is a challenge

Create the Example Application

Use ng new to create a new application.

ng new tdf --routing=true --style=css

To work with Template-driven forms, we must import the FormsModule.

The FormsModule contains all the form directives for working with
Template-Driven forms.

The first task is to build the template. The following is a regular HTML
form. We enclose it in a <form> tag. We have included two text input
(FirstName & LastName), a email (email), a radio button (gender), a
checkbox (isMarried), and a select list (country). These are form
elements.\
<form>

<p>
<label for="firstname">First Name</label>
<input type="text" id="firstname" name="firstname">
</p>

<p>
<label for="lastname">Last Name</label>
<input type="text" id="lastname" name="lastname">
</p>

<p>
<label for="email">Email </label>
<input type="text" id="email" name="email">
</p>

<p>
<label for="gender">Geneder</label>
<input type="radio" value="male" id="gender" name="gender"> Male
<input type="radio" value="female" id="gender" name="gender"> Female
</p>

<p>
<label for="isMarried">Married</label>
<input type="checkbox" id="isMarried" name="isMarried">
</p>

<p>
<label for="country">country </label>
<select name="country" id="country">
<option selected="" value=""></option>
<option [ngValue]="c.id" *ngFor="let c of countryList">
{{c.name}}
</option>
</select>
</p>

<p>
<button type="submit">Submit</button>
</p>
export class country {
id:string;
name:string;

constructor(id:string, name:string) {
this.id=id;
this.name=name;
}

countryList:country[] = [
new country("1", "India"),
new country('2', 'USA'),
new country('3', 'England')
];

We can export the ngForm instance into a local template variable using
ngForm as the key (ex: #contactForm="ngForm"). This allows us to access the
many properties and methods of ngForm using the template variable
contactForm.

<form #contactForm="ngForm">

We have six form elements in our HTML template. They are firstName,
lastname, email, gender, isMarried & country. We need to bind them to
FormControl instance. We do this by using the ngModel directive. Add the
ngModel directive to each control as shown below.

<input type="text" name="firstname" ngModel>

ngModel will use the name attribute to create the FormControl instance for
each of the Form field it is attached.
Submit Form

Now have the template ready, except for the final piece i.e submitting data
to the component.

We use the ngSubmit event, to submit the form data to the component
class. We use the event binding(parentheses) to bind ngSubmit to OnSubmit
method in the component class. When the user clicks on the submit
button, the ngSubmit event will fire

We are passing the local template variable contactForm in onSubmit method.


contactForm holds the reference to the ngForm directive. We can use this in
our component class to extract the data from the form fields.

ngForm

We have access to the ngForm instance via the local template variable
#contactForm

<form #contactForm="ngForm" (ngSubmit)="onSubmit(contactForm)">

<pre>Value : {{contactForm.value | json }} </pre>


<pre>Valid : {{contactForm.valid}} </pre>
<pre>Touched : {{contactForm.touched }} </pre>
<pre>Submitted : {{contactForm.submitted }} </pre>

value: The value property returns the object containing the value of every
FormControl
valid: Returns true if the form is Valid else returns false.
touched: True if the user has entered a value in at least in one field.
submitted: Returns true if the form is submitted. else false.
Local Variable

We can assign the ngForm,FormControl or FormGroup instance to a template


local variable. This allows us to check the status of the form like whether
the form is valid, submitted, and value of the form elements, etc
Grouping the controls using FormGroup
We can group various FormControls together. For Example fields such as
street, city, country and Pincode each will have their own FormControl but can
be grouped together as an address FormGroup

address:new FormGroup({
city:new FormControl(),
street:new FormControl(),
pincode:new FormControl(),
country: new FormControl()
})

we have created new FormGroup Address and added three form controls i.e city,
street, country & Pincode

use the formGroupName directive to enclose the control using a div element as
shown below

What is FormBuilder

The FormBuilder is the helper API to build forms in Angular.


It provides shortcuts to create the instance of the FormControl, FormGroup or
FormArray. It reduces the code required to write the complex forms.

How to use FormBuilder


For That we have to Import & inject
FormBuilder API
import { FormBuilder } from '@angular/forms'

Next, we need to inject it into our component class

constructor(private formBuilder: FormBuilder) {


}
Finally, use the group, array & control methods to build the FormModel

FormGroup

We use the group method to build the Form Group. We pass the list of
FormControl,FormArray, or another FormGroup to the group method as
key-value pair. Where the key is the name of the FormControl, FormGroup or
FormArray. The value is the configuration of the control.

FormBuilder reduces the code required to write the complex forms.

Validators in Reactive Forms

What is a Validator
A Validator is a function that checks the instance of FormControl, FormGroup or
a FormArray and returns a list of errors. If the Validator returns a null means
that validation has passed.

Built-in Validators
The Angular ReactiveForms Module provides several Built-in validators out of
the box. They are required, minlength, maxlength & pattern etc.

Custom Validator in Angular Reactive Form

Built-in validators are useful but do not cover all use cases. This is where we
use the custom validator. It is very easy to create a custom validator in
Angular.

How to Build Custom Validator


Building a custom Validator is as easy as creating a Validator function. It is a
function, which must implement ValidatorFn Interface.
ValidatorFn
The ValidatorFn is an Interface, which defines the signature of the Validator
function.

interface ValidatorFn {
(control: AbstractControl): ValidationErrors | null
}

The function takes the AbstractControl. This is the base class for
FormControl,FormGroup , and FormArray. The validator function must return a
list of errors i.e Validation Errors or null if the validation has passed

Custom Validator Example


<h1>Custom Validator in Angular</h1>

<h2>Reactive Form</h2>

<form [formGroup]="myForm" (ngSubmit)="onSubmit()" novalidate>

<div>
<label for="numVal">Number :</label>
<input type="text" id="numVal" name="numVal" formControlName="numVal">
</div>

<p>Is Form Valid : {{myForm.valid}} </p>

<p>
<button type="submit" [disabled]="!myForm.valid">Submit</button>
</p>

</form>

Our example app has numVal form field. We want it to be greater than 10.
Angular does not have any built-in validator for that. Hence let us build a
custom Validator gte
Create a new file gte.validator.ts under the app folder.
export function gte(val: number): ValidatorFn {

return (control: AbstractControl): ValidationErrors | null => {

let v: number = +control.value;

if (isNaN(v)) {
return { 'gte': true, 'requiredValue': val }
}

if (v <= +val) {
return { 'gte': true, 'requiredValue': val }
}

return null;

First, we create a factory function. It receives the val as the argument. It must
return the function of the type ValidatorFn

Services & Dependency Injection


Services allow us to create reusable code and use it every component that
needs it.The Services can be injected into components and other services
using the dependency injection system. The dependencies are declared in
the Module using the Provider’s metadata. The Angular creates a tree of
injector & Providers that resembles the Component Tree. This is called the
hierarchical pattern.

we will build a simple component that fetches a list of products from an


Angular Service and displays it in our template.Service is a class that has the
purpose of Providing a Service to a Component, Directive, or to another
Service. The Service may be fetching data from the back end.
Service is a piece of reusable code with a focused purpose. A code that you
will use in many components across your application

Our components need to access the data. You can write data access code in
each component, but that is very inefficient and breaks the rule of single
responsibility. The Component must focus on presenting data to the user.
The task of getting data from the back-end server must be delegated to
some other class. We call such a class a Service class. Because it provides
the service of providing data to every component that needs it.

How to create a Service in Angular

An Angular service is simply a Javascript function. All we need to do is to


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. Let
us create a simple service, which gets the product data and passes it to our
component.

What is Angular Dependency Injection

Dependency Injection (DI) is a technique in which a class receives its


dependencies from external sources rather than creating them itself.

Steps to create And registered service


1. Define Service class [ng g s <NameOfSevice>]
2. Register with Injector
3. Declare as dependencies in our components;
HttpClientModule
import { Injectable } from '@angular/core';

import { HttpClient, HttpParams, HttpHeaders } from


'@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { map, catchError} from 'rxjs/operators';

import { repos } from './repos';

@Injectable()
export class GitHubService {

baseURL: string = "https://api.github.com/";

constructor(private http: HttpClient) {


}

getRepos(userName: string): Observable<any> {


return this.http.get(this.baseURL + 'users/' + userName + '/repos')
}

[
{"id":1,"name":"rajat","experience":10},
{"id":2,"name":"babita","experience":20},
{"id":3,"name":"aditya","experience":4},
{"id":4,"name":"harsh","experience":1}
]

You might also like