2CSC22Notes 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

UNIT -2:- Angular – JS Web Framework

Introduction:

Template :
In Angular, a template is a blueprint for a fragment of a user interface (UI). Templates are
written in HTML, and special syntax can be used within a template to build on many of
Angular's features.

Components :
Components are the main building block for Angular applications. Each component consists
of:
 An HTML template that declares what renders on the page
 A TypeScript class that defines behavior
 A CSS selector that defines how the component is used in a template
 Optionally, CSS styles applied to the template

Directives :
Directives are classes that add additional behavior to elements in your Angular applications.
Use Angular's built-in directives to manage forms, lists, styles, and what users see.
Event binding :
Event binding lets you listen for and respond to user actions such as keystrokes, mouse
movements, clicks, and touches.
Property binding :
Property binding in Angular helps you set values for properties of HTML elements or
directives. Use property binding to do things such as toggle button features, set paths
programmatically, and share values between components.
what is angular ?
Angular is one of the most known TypeScript ( is a superset of JavaScript) front-end
framework developed by Google to create dynamic and modern web apps.
First introduced in 2009, the framework has gained huge traction over the years for
eliminating unnecessary code and ensuring lighter and faster apps.
Having rapidly evolved from Angular JS in 2010 to Angular 5 in 2017 and to Angular 8 in
2019, the front-end framework is today used by more than 44.3% of software engineers to
create user interfaces.
Single-page applications:-
Single-page applications are web applications or a particular type of website that provide
users with a very intuitive, responsive, and fast user experience. It is enriched with menus,
multiple blocks, tiles, and interactive buttons on one page, helping users easily navigate the
application. It helps to load a portion of the current page dynamically instead of reloading the
entire page from the server. This is why Angular-based applications are called reactive fast-
speed loading pages
Why choosing Angular instead of other frameworks ? Features of Angular ?
1. Supported by Google
2. TypeScript
3. Declarative UI
4. POJO (Plain old Java object)
5. Simplified MVC Pattern MVVM
6. Modular Structure
7. Code Consistency
1.Supported by Google :
• Google is an american company known as one of the biggest pillars in technology and
the best part about it is Google’s Long-Term Support (LTS) for Angular means
Google is scaling up the project and that the project is going further with time.
• Another important point to mention is that a lot of Google projects are using Angular
2.TypeScript :
• Currently angular projects are built with Typescript, as I already mentioned, is a
superset of JavaScript which primarily provides optional static typing, classes and
interfaces.
• One of the its salient benefits is to enable IDEs to provide a richer environment for
spotting common errors as you type the code.

• This language ensures an improved refactoring, navigation, and


auto-completion services. You can even opt out of its inbuilt
features when needed.
• It fully supports core ES2015 and ES2016/ES2017 features
such as decorators or async/await. Check the following figure for
further understanding.

Declarative UI :
Angular uses HTML to define the UI of the application. HTML, as compared to
JavaScript, is a less convoluted language. HTML is also a declarative and intuitive
language.
How will it help ? You don’t need to invest your time in program flows and deciding
what loads first. Define what you require and Angular will do the job.
POJO (Plain old Java object) :
• With Angular, you don’t need any additional getter and setter functions. Since, every
object it uses is POJO , which enables object manipulation by providing all the
conventional JavaScript functionalities. You can remove or add properties from the
objects, while also looping over these objects when required.
Angular Testing :
• In Angular, testing is extremely simple. Angular.js modules has the application parts
that are easy to manipulate. With module separation, you can load the necessary
services, while effectively performing automatic testing using Jasmine, Karma.. etc .
• You don’t even need to remember module loading order if you follow “one file-one
module” principle.
Simplified MVC Pattern MVVM :
Angular framework is embedded with original MVC but it’s more of an MVVM software
architectural setup. Angular does not ask developers to split an application into different
MVC components and build a code that could unite them.
• Its framework uses the MVVM(Model-View-
ViewModel) architecture better than an MVC (Model-
View-Controller) one. The MVVM model supports two-
way data binding between View and ViewModel.

• This allows the automatic propagation to change within ViewModel’s state to the
view. Typically, ViewModel uses the observer model to inform changes to the
ViewModel model to model.
• Furthermore, it only asks to divide the app and takes care of everything else.
Therefore, Angular and MVVM (Model-View-View-Model) design structure are
quite similar.
Angular ensures easy development as it eliminates the need for unnecessary code. It
has a simplified MVC architecture, which makes writing getters and setters needless.
• Directives can be managed by some other teams as these are not part of app code.
• All in all, developers are promised less coding along with lighter and faster apps.
• According to Amazon, every 100-millisecond improvement in page loading speed led
to 1% increase in revenue.

Modular Structure :
• Angular organizes code into buckets, whether it is components, directives, pipes or
services.
• Those who are familiar with Angular refer to these buckets as modules.
• Modules make application functionality organization easy through dividing it into
features and reusable chunks.
• Modules also allow lazy loading, which paves way for application feature loading in
the background or on-demand.
• Angular makes it an achievable goal to divide the labor across different team
members while ensuring organized code.
• In fact, you can make the best modules when you have a proper understanding of it.
Developers can improve productivity with appropriate modules built.
Code Consistency :
• Any code base requires consistent coding. A writer knows how important consistency
is in their content.
• We know if the content fails to resonate with the readers to a deeper level at any
touch-point, we are on a downward slope of lead conversions, and coding is no
different.
• Inconsistent coding increases the risks of delayed launches or elevated costs.
AngularJS Features :
1. MVC
2. Data Model Binding
3. Writing less code
4. Unit Testing
MVC — The framework is built on the famous concept of MVC (Model-View-Controller).
This is a design pattern used in all modern-day web applications.
This pattern is based on splitting the business logic layer, the data layer, and presentation
layer into separate sections. The division into different sections is done so that each one could
be managed more easily.
Data Model Binding — You don’t need to write special code to bind data to the HTML
controls. This can be done by Angular by just adding a few snippets of code.
Writing less code — When carrying out DOM manipulation a lot of JavaScript was required
to be written to design any application. But with Angular, you will be amazed by the lesser
amount of code you need to write for DOM manipulation.
Unit Testing ready — The designers at Google not only developed Angular but also
developed a testing framework called “Karma” which helps in designing unit tests for
AngularJS applications.

Components:-
Angular Components :
• Everything in Angular is developed as a component; classes interact with different
files that are embedded in components, which form a browser display. It can also be
referred to as a kind of a directive with configuration that's suitable for an application
structure that is component-based.
• The architecture of an Angular application is a tree of components originating
from one root component configured in the bootstrap property on your root
NgModule (in the app. module.ts file).
• file structure of an Angular :
Let's look at the file structure of an Angular root component that was created by default in
the process of bootstrapping a new Angular application:
• app.component.css: This is the style sheet for the component
• app.component.html: This is the HTML template file for the component
• app.component.spec.ts: This is the testing file for the component
• app.component.ts: This is the TypeScript class for the component
• app.module.ts: This is the TypeScript module file for the application
Angular components :
Components are the main building block for Angular applications. Each component
consists of:
• An HTML template that declares what renders on the page
• A TypeScript class that defines behavior
• A CSS selector that defines how the component is used in a template
• Optionally, CSS styles applied to the template
Creating a component :
The best way to create a component is with the Angular CLI. You can also create a
component manually.
• Creating a component using the Angular CLI
• To create a component using the Angular CLI:
Steps to create component :
1.From a terminal window, navigate to the directory containing your application.
2.Run the ng generate component <component-name> command, where <component-
name> is the name of your new component.
By default, this command creates the following:
• A directory named after the component
• A component file, <component-name>.component.ts
• A template file, <component-name>.component.html
• A CSS file, <component-name>.component.css
• A testing specification file, <component-name>.component.spec.ts
Where <component-name> is the name of your component.
Creating a component manually :
Although the Angular CLI is the best way to create an Angular component, you can also
create a component manually. This section describes how to create the core component file
within an existing Angular project.
Steps To create a new component manually:
1. Navigate to your Angular project directory.
2. Create a new file, <component-name>.component.ts.
3. At the top of the file, add the following import statement.
import { Component } from '@angular/core';
4.After the import statement, add a @Component decorator.
@Component({
})
5.Choose a CSS selector for the component.
@Component({
selector: 'app-component-overview', })
6.Define the HTML template that the component uses to display information. In most cases,
this template is a separate HTML file.
@Component({
selector: 'app-component-overview',
templateUrl: './component-overview.component.html',
})

7.Select the styles for the component's template. In most cases, you define the styles for your
component's template in a separate file.
@Component({
selector: 'app-component-overview',
templateUrl: './component-overview.component.html',
styleUrls: ['./component-overview.component.css']
})
8.Add a class statement that includes the code for the component.
export class ComponentOverviewComponent {
}

Example using css selector


Specifying a component's CSS selector :
Every component requires a CSS selector. A selector instructs Angular to instantiate this
component wherever it finds the corresponding tag in template HTML. For example, consider
a component hello-world.component.ts that defines its selector as app-hello-world. This
selector instructs Angular to instantiate this component any time the tag <app-hello-
world> appears in a template.
Specify a component's selector by adding a selector statement to the @Component decorator.
@Component({
selector: 'app-component-overview',
})
Defining a component's template :
A template is a block of HTML that tells Angular how to render the component in your
application. Define a template for your component in one of two ways: by referencing an
external file, or directly within the component.
To define a template as an external file, add a templateUrl property to
the @Component decorator.
@Component({
selector: 'app-component-overview',
templateUrl: './component-overview.component.html',
})
To define a template within the component, add a template property to
the @Component decorator that contains the HTML you want to use.
@Component({
selector: 'app-component-overview',
template: '<h1>Hello World!</h1>',
})
If you want your template to span multiple lines, use backticks (`).
For example:
@Component({
selector: 'app-component-overview',
template: `
<h1>Hello World!</h1>
<p>This template definition spans multiple lines.</p>
`
})
Declaring a component's styles :
Declare component styles used for its template in one of two ways: By referencing an
external file, or directly within the component.
To declare the styles for a component in a separate file, add a styleUrls property to
the @Component decorator.
@Component({
selector: 'app-component-overview',
templateUrl: './component-overview.component.html',
styleUrls: ['./component-overview.component.css']
})
To declare the styles within the component, add a styles property to
the @Component decorator that contains the styles you want to use.
@Component({
selector: 'app-component-overview',
template: '<h1>Hello World!</h1>',
styles: ['h1 { font-weight: normal; }']
})
The styles property takes an array of strings that contain the CSS rule declarations.

Templates:-
Understanding templates :
In Angular, a template is a blueprint for a fragment of a user interface (UI). Templates are
written in HTML, and special syntax can be used within a template to build on many of
Angular's features.
Enhancing HTML :
• Angular extends the HTML syntax in your templates with additional functionality.
• For example, Angular’s data binding syntax helps to set Document Object Model
(DOM) properties dynamically.
• Almost all HTML syntax is valid template syntax. However, because an Angular
template is only a fragment of the UI, it does not include elements such as <html>,
<body>, or <base>.

Template expressions are the same expression that we use with JavaScript. But the
difference is that we
can use it within our Html template, so it looks like that we are using JavaScript along with
Html but keep in mind
that not every JavaScript expressions are supported like (new), (++) and (--).
Let’s see a simple example of the mathematical calculation using template expression.
App.component.html
<p>Addition : {{ 1 + 1 }}</p>
<p>Subtraction : {{ 25 - 50 }}</p>
<p>Multiplication : {{ 25 * 50 }}</p>
<p>Division : {{ 25 / 50 }}</p>
Here we have used {{ }} brackets in order to use an expression within our template
• Template statement will be triggered when an event will be raised using any binding
target such as component, directive or a simple element.
Expression will always be the right side of the event using a (=) symbol like the
Following example.
<input type="button" (click)="clickevent()" value="Submit"/>
In the above example, we have a template statement and we are using the event clickevent ().
This is called a
template statement.
Same as template expression, not every JavaScript expression are supported in
Template statements

Data Binding :
Angular CLI provides various features and one of them is to create the new file using just a
single line of command. By using a command, we can generate various kind of files like
Component, Module, Pipe and many more are listed below:
Command:
ng generate <file_type> <file_name>
Angular CLI commands for creating various types of files:
• ng generate class
• ng generate component
• ng generate module
• ng generate service
• ng generate pipe
• ng generate application
• ng generate library
• ng generate directive
• ng generate enum
• ng generate interface
• ng generate guard
• ng generate appShell
Data Binding in Angular :
• Data binding is one of the important core concepts which is used to do the
communication between the component and DOM.
• In other words, we can say that the Data binding is a way to add/push elements into
HTML DOM or pop the different elements based on the instructions given by the
Component.
There are mainly three types of data binding supported in order to achieve the data
bindings in Angular.
1. One-way Binding (Interpolation, Attribute, Property, Class, Style)
2. Event Binding
3. Two-way Binding

Interpolation :
Interpolation in Angular is used to show the property value from component to the template
or used to execute the expressions.
App.component.ts
myMessage: string = "Hello World";
App.component.html
<p>{{ myMessage }}</p>
<p>Total : {{ 25 + 50 + 75 + 100 }}</p>
Property Binding :
Property binding is generally used to show or update the value of the variables in component
and vice versa. We can also call it one-way data binding thus it is not used to update the two-
way binding mechanism, and value will be reflected at the component level.
App.component.ts
myMessage: string = "Hello World";
App.component.html
<h1>{{ myMessage }}</h1>
Whenever we change the value of the myMessage variable, at that time it will be reflected in
the template but not vice versa.
2.Event binding :
• User activities are a common thing in a web application to do some actions, at that
time click or mouse event will be used to fulfill the goal of an activity. When the user
clicks on any element, at that time it generates the event and into the event, we will
perform the various operations to achieve something, for that we can use Event
binding in Angular.
• For event binding, the targeted event will be on the left side and the event name will
on the right side. The event name is surrounded by the punctuations like (), [] or
preceded by the prefix like (on-, bind-)
Let’s understand event binding by using a simple example, where we will use click event
on a button.
App.component.html
<button (click)="clickEvent()">
Click me to generate an event
</button>
Here in this template file, we have used the click event and it’s surrounded by the ()
brackets.
App.component.ts :
import{ Component } from '@angular/core’;
@Component({
selector: 'my-app’,
templateUrl: './app.component.html’,
styleUrls: ['./app.component.css’]
})
Export class AppComponent {
clickEvent() {
console.log("Button Clicked");
}
}
In the component file, we have created one method for handling click event, whenever the
user clicks on the button, at that time our clickEvent () will be triggered.

3.Two-way data binding :


• Two-way binding is one of the strongest binding mechanisms, where two different
bindings are merged i.e. input and output bindings.
• It means that Event binding works with the two different binding mechanisms at a
time and generates the output based on the event which was triggered. For two-way
data binding, we will use the punctuation [( )] in order to bind the two-way data.
• It can be happen using the directive called ngModel which listen to the input for any
changes and return the output.
• We will understand more by implementing the simple example, where we will type
the text into the input and at the same time, we will get the value of the same input
value.

App.component.html :
Full Name : <input type="text" [(ngModel)]="fullName">
Your Name is : {{ fullName }}
App.component.ts
import{ Component } from '@angular/core’;
@Component({
selector: 'my-app’,
templateUrl: './app.component.html’,
styleUrls: ['./app.component.css’]
})
Export class AppComponent {
fullName: string = ‘ ‘;
}

Directive in Angular :
Implementing Directive

 A directive is a concept in Angular that allows you to attach attributes and behaviors
to a DOM element.
 This concept is used to extend the power of HTML by giving it a new syntax. Each
directive has a name, which can either be predefined in Angular, such as ng-repeat, or
a name that's generated by the developer.
 Each directive determines where it can be used: in an element, attribute, class, or
comment. We will focus more on predefined directives here. There are three types of
directives: component, structural, and attribute. Let's look at each of these in detail

Component directive:
This is the most commonly used directive, known as a directive in a template. In this type of
directive, you can use other directives, custom or built-in, in the @Component annotation, as
shown here:
@Component({
selector: "my-app"
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
directives: [custom_directive_here] })
use this directive in your view as: <my-app></my-app>
From the previous snippet, the objects we have inside the @Components decorators are
known as component directives and can be explained further. selector: "string" identifies
and instantiates a directive in a template. directives: [custom_directive_ here] defines a set
of directive providers in the format, as follows:
• Inputs: This defines a set of data-bound input properties: inputs: ['string'],

• Outputs: This defines a set of event-bound output properties: outputs: ['string'],

Other directives are providers, exportAs, queries, jit, and host. Even though we have
already made use of component directives in previous sections, we will be covering some
other directives in detail in the following sections and exercises.
Structural directive: Structural directives are responsible for providing a DOM structure and
for reshaping the HTML layout by adding or manipulating elements. Most structural
directives are easily recognized by the * sign that precedes the directive. Examples of
structural directives are *ngIf, *ngFor, and *ngSwitch (this includes a set of cooperating
directives: NgSwitch, NgSwitchCase, and NgSwitchDefault). You can create a custom
structural directive as well.
Attribute directive: This is a directive that attaches behavior to the DOM element.
Exercise 12: Implementing a Structural Directive
In this exercise, we will implement a structural directive. We will be implementing the

1. Create a structural-dir component in my-new-app using the following command:

ng g component structural-dir the previous snippet, the objects we have inside


2. Declare a global variable named courseTitles in the component after the class class,
in the aforementioned file, as shown in the following snippet: courseTitles = ['MEAN
Stack', 'MEVN Stack', 'MERN Stack'];
3. Edit the content of the component template (structural-dir.component.html) with
the following code:
<div class="form-group" *ngFor="let course of courseTitles">
{{course}}</div>
4. Update the root component HTML file with the following code:

<app-structural-dir ></app- structural-dir >


5. Run the application using the following command:

ng serve -o
You will obtain the following output:

Figure 3.7: *ngFor output


As can be seen in the preceding output, we have successfully implemented the *ngFor
structural directive.
Exercise 13: Implementing an Attribute Directive
In this exercise, we will be implementing the [ngStyle] and [hidden] built-in attribute
directives in a component of an existing application (my-new-app). Perform the following
steps to complete the exercise:
1. Create an attribute-dir.component.ts file in the app folder by running the following
command: ng g component attribute-dir
2. Apply [ngStyle] and [hidden], which are attribute directives to H1 and H2 elements,
respectively, in the component template (attribute-dir.component.html) using the
following command:
<h1 [ngStyle]="myStyle"> Attribute directive </h1>
<h2 [hidden]="hide">Attribute directive 2 </h2>
3. Declare and assign a value to the variable named myStyle and hide it in the
component class in attribute-dir.components.ts using the following code:
hide = true;
public myStyle={
"color":"green"
}
4. Update the root component HTML file with the following command:

<app-attribute-dir></app-attribute-dir>
5. Run the application using the following command:

ng serve -o
You will obtain the following output:

Figure 3.8: Output with implemented attribute directives


In the preceding output, observe that the H1 element is displayed in green and that the H2
element is hidden.

Modules :

 Angular applications are modular and Angular has its own modularity system called
NgModules.
 NgModules are containers for a cohesive block of code dedicated to an application
domain, a workflow, or a closely related set of capabilities.
 They can contain components, service providers, and other code files whose scope is
defined by the containing NgModule.
 They can import functionality that is exported from other NgModules, and export
selected functionality for use by other NgModules.
 Every Angular application has at least one NgModule class, the root module, which is
conventionally named AppModule and resides in a file named app.module.ts.
 You launch your application by bootstrapping the root NgModule.
 While a small application might have only one NgModule, most applications have
many more feature modules.
 The root NgModule for an application is so named because it can include child
NgModules in a hierarchy of any depth.

NgModule metadata
An NgModule is defined by a class decorated with @NgModule(). The @NgModule()
decorator is a function that takes a single metadata object, whose properties describe the
module. The most important properties are as follows.

PROPERTIES DETAILS

The components, directives, and pipes that belong to


declarations this NgModule.

The subset of declarations that should be visible and


usable in the component templates of other
exports NgModules.

Other modules whose exported classes are needed by


imports component templates declared in this NgModule.
PROPERTIES DETAILS

Creators of services that this NgModule contributes to


the global collection of services; they become
accessible in all parts of the application. (You can also
providers specify providers at the component level.)

The main application view, called the root component,


which hosts all other application views. Only the root
bootstrap NgModule should set the bootstrap property.

Here's a simple root NgModule definition.


import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
@NgModule({
imports: [ BrowserModule ],
providers: [ Logger ],
declarations: [ AppComponent ],
exports: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }

Expressions:

Understanding template expressions


This topic explores some aspects of Angular text interpolation.

Syntax
Template expressions are similar to JavaScript. Many JavaScript expressions are legal
template expressions, with the following exceptions.
You can't use JavaScript expressions that have or promote side effects, including:
 Assignments (=, +=, -=, ...)
 Operators such as new, typeof, or instanceof
 Chaining expressions with ; or ,
 The increment and decrement operators ++ and --
 Some of the ES2015+ operators
Other notable differences from JavaScript syntax include:
 No support for the bitwise operators such as | and &
 New template expression operators, such as |, ?. and !
Expression context
 Interpolated expressions have a context—a particular part of the application to which
the expression belongs. Typically, this context is the component instance.
 In the following snippet, the expression recommended and the expression
itemImageUrl2 refer to properties of the AppComponent.

src/app/app.component.html

<h4>{{recommended}}</h4>
<img alt="item 2" [src]="itemImageUrl2">

An expression can also refer to properties of the template's context such as a template input
variable or a template reference variable.

The following example uses a template input variable of customer.


src/app/app.component.html (template input variable)
<ul>
<li *ngFor="let customer of customers">{{customer.name}}</li>
</ul>

This next example features a template reference variable, #customerInput.


src/app/app.component.html (template reference variable)
<label>Type something:
<input #customerInput>{{customerInput.value}}
</label>

Expression best practices:


When using template expressions, follow these best practices:
 Use short expressions
Use property names or method calls whenever possible. Keep application and business logic
in the component, where it is accessible to develop and test.

 Quick execution
Angular executes template expressions after every change detection cycle. Many
asynchronous activities trigger change detection cycles, such as promise resolutions, HTTP
results, timer events, key presses, and mouse moves.

Expressions should finish quickly to keep the user experience as efficient as possible,
especially on slower devices. Consider caching values when their computation requires
greater resources.

 No visible side effects


According to Angular's unidirectional data flow model, a template expression should not
change any application state other than the value of the target property. Reading a component
value should not change some other displayed value. The view should be stable throughout a
single rendering pass.

You might also like