Angular
Angular
The Angular CLI creates the Angular Application and uses Typescript,
Webpack ( for Module bundling), Karma ( for unit testing), Protractor (
for end to end testing).
ng new GettingStarted
The above command will create a folder GettingStarted and copies all
the required dependencies and configuration settings.
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)
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
Imports Metadata tells the angular list of other modules used by this
module. We are importing BrowserModule and AppRoutingModule.
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.
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 includes HTML and CSS based design templates for typography, forms,
buttons, tables, navigation, modals, image carousels and many others.
We can install the Bootstrap CSS file in one of the following ways.
npm i [email protected]
npm i [email protected]
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 }}
1
2 //Template
3
4 {{getTitle()}}
5
6
7 //Component
8 title = 'Angular Interpolation Example';
9 getTitle(): string {
10 return this.title;
11 }
12
1
2 <p>Show me <span class = "{{giveMeRed}}">red</span></p>
3 <p style.color={{giveMeRed}}>This is red</p>
4
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.
DatePipe
This pipe is used for the transformation of dates. The first argument is a
format string, like so:
LowerCasePipe
UpperCasePipe
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:
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.
[binding-target]=”binding-source”
<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>
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.
Then you can use it using the two-way binding syntax as shown below
<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.
Structural Directives
Structural directives can change the DOM layout by adding and removing DOM
elements. All structural Directives are preceded by Asterix symbol.
ngFor
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.
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:-
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-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
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; 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>
Example of ngIf
<div *ngIf="condition">
This is shown if condition is true
</div>
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.
<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">
</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.
<ng-template #elseBlock>
content to render, when the condition is false
</ng-template>
When the condition evaluates to false, then the ng-template with the name
#elseBlock is rendered by the ngIf Directive.
<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>
When the condition is true, the template thenBlock is rendered. If false, then
the template elseBlock is rendered.
ngSwitch
<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>
<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.
Syntax
<element [ngClass]="expression">...</element>
Where
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
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.
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.
<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.
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.
Angular Forms
The Angular forms are used to collect the data from the user.
Some things forms are expected to do
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.
FormControl
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.
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
Often forms have more than one field. It is helpful to have a simple way to
manage the Form controls together.
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.
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
ngForm
We have access to the ngForm instance via the local template variable
#contactForm
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
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
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.
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.
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.
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
<h2>Reactive Form</h2>
<div>
<label for="numVal">Number :</label>
<input type="text" id="numVal" name="numVal" formControlName="numVal">
</div>
<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 {
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
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.
@Injectable()
export class GitHubService {
[
{"id":1,"name":"rajat","experience":10},
{"id":2,"name":"babita","experience":20},
{"id":3,"name":"aditya","experience":4},
{"id":4,"name":"harsh","experience":1}
]