0% found this document useful (0 votes)
5 views20 pages

Module 4 Angular

The document provides a comprehensive overview of Angular, an open-source web application framework developed by Google, focusing on its importance, components, directives, and data binding. It outlines the steps to create a basic Angular application, including installation of Angular CLI, project creation, and component management. Additionally, it explains Angular expressions, built-in directives, and the concept of custom directives for enhancing application functionality.

Uploaded by

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

Module 4 Angular

The document provides a comprehensive overview of Angular, an open-source web application framework developed by Google, focusing on its importance, components, directives, and data binding. It outlines the steps to create a basic Angular application, including installation of Angular CLI, project creation, and component management. Additionally, it explains Angular expressions, built-in directives, and the concept of custom directives for enhancing application functionality.

Uploaded by

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

MODULE-IV

Angular
Angular: importance of Angular, Understanding Angular, creating a Basic
Angular Application, Angular Components, Expressions, Data Binding,
Built-in Directives, Custom Directives, Implementing Angular Services in
Web Applications.
( Resources : angular.dev, geeksforgeeks.org, w3schools.com, etc. )
importance of Angular
What is Angular ?
Angular is an open-source web application framework maintained by Google and a community of
developers. It is designed to build dynamic and interactive single-page applications (SPAs) efficiently.
With Angular, developers can create robust, scalable, and maintainable web applications.
Angular is a development platform, built on TypeScript.
As a platform, Angular includes:
 A component-based framework for building scalable web applications
 A collection of well-integrated libraries that cover a wide variety of features, including
routing, forms management, client-server communication, and more
 A suite of developer tools to help you develop, build, test, and update your code
With Angular, you're taking advantage of a platform that can scale from single-developer projects to
enterprise-level applications. Best of all, the Angular ecosystem consists of a diverse group of over
1.7 million developers, library authors, and content creators.

Understanding Angular
To understand the capabilities of the Angular framework, you need to learn about the following:
 Components
 Templates
 Directives
 Dependency injection
Components
Components are the main building blocks of Angular applications. Each component represents a part
of a larger web page. Organizing an application into components helps provide structure to your
project, clearly separating code into specific parts that are easy to maintain and grow over time.
Every component has a few main parts:
1. A @Componentdecorator that contains some configuration used by Angular.
2. An HTML template that controls what renders into the DOM.
3. A CSS selector that defines how the component is used in HTML.
4. A TypeScript class with behaviors, such as handling user input or making requests to a server.
Here is a simplified example of a UserProfile component.
// user-profile.ts
@Component({
selector: 'user-profile',
template: `
<h1>User profile</h1>
<p>This is the user profile page</p>
`,
})
export class UserProfile { /* Your component code goes here */ }
The @Component decorator also optionally accepts a styles property for any CSS you want to
apply to your template:
// user-profile.ts
@Component({
selector: 'user-profile',
template: `
<h1>User profile</h1>
<p>This is the user profile page</p>
`,
styles: `h1 { font-size: 3em; } `,
})
export class UserProfile { /* Your component code goes here */ }
Separating HTML and CSS into separate files
You can define a component's HTML and CSS in separate files using templateUrl and styleUrl:
// user-profile.ts
@Component({
selector: 'user-profile',
templateUrl: 'user-profile.html',
styleUrl: 'user-profile.css',
})
export class UserProfile {
// Component behavior is defined in here
}

<!-- user-profile.html -->


<h1>Use profile</h1>
<p>This is the user profile page</p>

/* user-profile.css */
h1 {
font-size: 3em;
}
Template
Every Angular component has a template that defines the DOM that the component renders onto the
page. By using templates, Angular is able to automatically keep your page up-to-date as data changes.
Templates are usually found within either the template property of a *.component.ts file or
the *.component.html file.
How do templates work?
Templates are based on HTML syntax, with additional features such as built-in template functions,
data binding, event listening, variables, and more.
Angular compiles templates into JavaScript in order to build up an internal understanding of your
application. One of the benefits of this are built-in rendering optimizations that Angular applies to
your application automatically.
Differences from standard HTML
Some differences between templates and standard HTML syntax include:
 Comments in the template source code are not included in the rendered output
 Component and directive elements can be self-closed (e.g., <UserProfile />)
 Attributes with certain characters (i.e., [], (), etc.) have special meaning to Angular.
See binding docs and adding event listeners docs for more information.
 The @ character has a special meaning to Angular for adding dynamic behavior, such
as control flow, to templates. You can include a literal @ character by escaping it as an
HTML entity code (&commat; or &#64;).
 Angular ignores and collapses unnecessary whitespace characters. See whitespace in
templates for more details.
 Angular may add comment nodes to a page as placeholders for dynamic content, but
developers can ignore these.
In addition, while most HTML syntax is valid template syntax, Angular does not
support <script> element in templates. For more information, see the Security page.

Directives
Use Angular's built-in directives to manage forms, lists, styles, and what users see.
The different types of Angular directives are as follows:

Directive Types Details

Components Used with a template. This type of directive is the most common directive type.

Attribute directives Change the appearance or behavior of an element, component, or another directive.

Structural directives Change the DOM layout by adding and removing DOM elements.
Understanding dependency injection
Dependency injection, or DI, is one of the fundamental concepts in Angular. DI is wired into the
Angular framework and allows classes with Angular decorators, such as Components, Directives,
Pipes, and Injectables, to configure dependencies that they need.
Two main roles exist in the DI system: dependency consumer and dependency provider.
Angular facilitates the interaction between dependency consumers and dependency providers using an
abstraction called Injector. When a dependency is requested, the injector checks its registry to see if
there is an instance already available there. If not, a new instance is created and stored in the registry.
Angular creates an application-wide injector (also known as the "root" injector) during the application
bootstrap process. In most cases you don't need to manually create injectors, but you should know that
there is a layer that connects providers and consumers.
creating a Basic Angular Application
Steps to create Angular Project from Scratch:
Step 1: Install Angular CLI:
Angular CLI (Command Line Interface) is a powerful tool for creating and managing Angular
projects. You can install it globally using npm by running the following command in your terminal or
command prompt:
npm install -g @angular/cli
Step 2: Create a New Angular Project:
Once Angular CLI is installed, you can use it to create a new Angular project. Navigate to the
directory where you want to create your project and run the following command:
ng new my-angular-app
Step 3: Serve Your Angular Application:
After the project is created, navigate into the project directory then use an Angular CLI to serve your
application locally by running:
ng serve
Step 4: Create a Component:
Use Angular CLI to generate a new component. Open your terminal or command prompt, navigate to
your project directory, and run the following command:
ng generate component my-component
Step 5: Configure Routes:
Define the routes for your application in the app-routing.module.ts file. You can use Angular's
RouterModule to configure routes and associate components with specific URLs.
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';

const routes: Routes = [


{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent },
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }

Step 6: Add Content to Components:


Open the HTML file of your component (component-name.component.ts, component-
name.component.html, and component-name.component.css) and add the desired content.

Expressions
Angular Expression
An Angular Expression is a code snippet that can be simple or complex JavaScript-like code, like,
the variable references, function calls, operators, and filters, etc., written within double curly braces
{{ }} in order to evaluate & display dynamic values or perform calculations in the template.
Different Use Cases of Angular Expressions
Angular expressions are commonly used for various purposes, which are described below:
 Displaying Data: Angular expressions are extremely useful for displaying data obtained from
variables or properties within templates.
 Performing Calculations: Expressions allow us to perform calculations and display the
results dynamically.
 Conditional Rendering: Angular expressions can be used with directives like ng-if to
conditionally render elements based on data conditions.
 Filtering Data: We can use Angular filters in expressions to format and filter data before
displaying it.
 Event Handling: It can be used to handle user interactions and trigger actions in response to
events.
Syntax
In the below syntax, the msg property is bound to the <p> element and its value will be displayed.

// app.component.html
<p> {{ mymsg }} </p>

// app.component.ts
export class AppComponent {
mymsg = 'Hello, Geek!';
}
Data Binding
Angular provides a function Data Binding which helps us to have an almost real-time reflection of the
input given by the user i.e. it creates a connection between Model and View. Data Binding is a way to
synchronize the data between the model and view components automatically. AngularJS implements
data-binding that treats the model as the single-source-of-truth in your application & for all the time,
the view is a projection of the model. Unlike React, angular supports two-way binding. In this way,
we can make the code more loosely coupled. Data binding can be categorized into 2 types, ie., One-
way Binding & Two-way Binding.
One-way Binding: This type of binding is unidirectional, i.e. this binds the data flow from either
component to view(DOM) or from the view(DOM) to the component. There are various techniques
through which the data flow can be bind from component to view or vice-versa. If the data flow from
component to view(DOM), then this task can be accomplished with the help of String
Interpolation & Property Binding.
Two-way Binding: In this type of binding, the immediate changes to the view & component, will be
reflected automatically, i.e. when the changes made to the component or model then the view will
render the changes simultaneously. Similarly, when the data is altered or modified in the view then the
model or component will be updated accordingly.
In app.module.ts, we have to include FormsModule in imports like the way given down also we have
to import FormsModule. We have to include FormsModule, since ngModel is not a property included
in the project we develop using ng new project-name, so we have to include it by importing this
Module.

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


imports: [
BrowserModule,
FormsModule,
AppRoutingModule,
],

Example: This example describes the implementation of Two-way Data Binding.


<div style="text-align: center">
<h1 style="color: green">
GeeksforGeeks
</h1>
<h3>Two-way Data Binding</h3>
<input type="text"
placeholder="Enter text"
[(ngModel)]="val" />
<br />
{{ val }}
</div>
import { Component } from "@angular/core";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"],
})
export class AppComponent {
val: string;
}

Built-in Directives
Directives are markers in the Document Object Model(DOM). Directives can be used with any
controller or HTML tag which will tell the compiler what exact operation or behavior is expected.
There are some directives present that are predefined but if a developer wants he can create new
directives (custom-directive).
There are basically 3 types of directives and each type has some built-in directives.
 1. Component Directives
 2. Attribute Directives
 3. Structural Directives

1. Component Directives
Components are directives with templates. They are the building blocks of Angular applications,
encapsulating both the UI (User Interface) and the behavior of a part of the application. Components
are used to create reusable and modular UI elements. They are declared using the @Component
decorator and typically have a corresponding HTML template.
Syntax: In the component below, we have used the @Component here to define a component.

import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
})
export class AppComponent {}

2. Attribute Directives
Attribute directives are used to change the appearance or behavior of a DOM element by applying
custom attributes. These directives are applied to elements as attributes and are denoted by square
brackets. Attribute directives are often used for tasks such as dynamic styling, input validation, or
DOM manipulation.
Built-in Attribute Directives:
1. ngClass: The NgClass directive allows us to conditionally apply CSS classes to HTML elements.
Syntax:
<div [ngClass]="{'class-name': condition}">
<!-- Content here -->
</div>

2. ngStyle: The NgStyle directive enables you to conditionally apply inline styles to HTML elements.
Syntax:
<div [ngStyle]="{'property': 'value'}">
<!-- Content here -->
</div>

3. ngModel: The NgModel directive provides two-way data binding for form elements, syncing data
between the model and the view.
Syntax:
<input [(ngModel)]="property">
Example:
Output:

3. Structural Directives
Structural directives are responsible for manipulating the DOM layout by adding, removing, or
manipulating elements based on conditions. They are denoted by an asterisk (*) preceding the
directive name and are commonly used to alter the structure of the DOM based on conditions.
Examples include , , and ngSwitch.
Built-in Attribute Directives:
1. ngIf: The ngIf directive conditionally includes or removes an element based on a provided
expression.
Syntax:
<element *ngIf="condition">
<!-- Content to display when condition is true -->
</element>
2. ngFor: The ngFor directive iterates over a collection and instantiates a template once for each item
in the collection.
Syntax:
<element *ngFor="let item of items">
<!-- Content to repeat for each item -->
</element>
3. ngSwitch: The ngSwitch directive is similar to a switch statement in programming languages. It
displays one element from a set of elements based on a provided expression.
Syntax:
<element [ngSwitch]="expression">
<element *ngSwitchCase="value1"> <!-- Content for case 1 -->
</element>
<element *ngSwitchCase="value2"> <!-- Content for case 2 -->
</element>
<!-- More ngSwitchCase elements for other cases -->
<element *ngSwitchDefault> <!-- Default content -->
</element>
</element>
Example:

Output:
Custom Directives
Angular, a popular framework for building dynamic web applications, offers a powerful feature
known as custom directives. These directives extend the functionality of HTML elements, enabling to
create reusable components and add behavior to their applications. In this article, we'll learn about the
concept of custom directives in Angular.
Table of Content
 What is Custom Directive?
 Features of Custom Directives
 Uses of Custom Directives
 Creating Custom Attribute
What is Custom Directive?
Custom directives in Angular provide a mechanism to create reusable components and add behavior
to HTML elements. They help to encapsulate complex functionality, apply dynamic behavior, and
enhance the structure of the DOM. Custom directives are defined as TypeScript classes decorated with
Angular's @Directive() decorator.
Features of Custom Directives:
 Encapsulation of Behavior: Custom directives encapsulate specific functionality, provides
code reusability and maintainability.
 Dynamic Behavior: They enable the application of dynamic behavior to HTML elements
based on user interactions, data changes, or application logic.
 Access to DOM: Directives can access and manipulate the DOM using
Angular's ElementRef service, providing fine-grained control over the presentation layer.
 Reusable Components: Custom directives can be reused across different parts of the
application, provides modular development and reducing code duplication.
Uses of Custom Directives:
 Adding Styling: Directives can be used to apply dynamic styles to HTML elements based on
application state or user interactions.
 Handling User Input: They enable the creation of custom input controls and validation logic
for forms.
 Structural Manipulation: Directives can manipulate the structure of the DOM, conditionally
rendering elements or repeating content based on data.
 Integrating Third-party Libraries: Custom directives can integrate with third-party
libraries or frameworks, encapsulating their functionality within Angular components.
Creating Custom Attribute
Step 1: Setting Up Angular Project
Install Angular CLI globally (if not already installed)
npm install -g @angular/cli
Create a new Angular project:
ng new custom-attribute-demo
Navigate into the project directory:
cd custom-attribute-demo
Step 2: Create a Custom Attribute Directive
Create a new custom attribute directive:
ng generate directive highlight

Example: Add the following codes in the respective files.


To start the application run the following command.
ng serve
output:
Implementing Angular Services in Web Applications.
The Services is a function or an object that avails or limit to the application in AngularJS, ie., it is
used to create variables/data that can be shared and can be used outside the component in which it is
defined. Service facilitates built-in service or can make our own service. The Service can only be used
inside the controller if it is defined as a dependency. In the case of many Services, the object that can
be utilized, which is defined in DOM already, has few constraints in the AngularJS application.
Why to use the AngularJS Service?
AngularJS supervise the application constantly. In order to handle the events or any changes in a
proper manner, then the Service that is provided by the AngularJS will prefer to use, instead of
Javascript Objects. For instance, the window.location object that is that already defined in the DOM,
can be used with some limitations, likewise the $location service, in the AngularJS application. For
this case, AngularJS generally prefer to use the $location service, instead of using
the window.location object.
There are some commonly used built-in services, are described below:
 $http Service: It makes the request to the server, in order to handle the response by the
application.
 $timeout Service: This service is AngularJS' version of the window.setTimeout function.
 $interval Service: This service is AngularJS' version of the window.setInterval function.
Create the AngularJS Service:
STEP 1: Creating a service will follow the below command:
ng g s service-name
s is a short form for service. This creates two files service-name.service.spec.ts which is not supposed
to be changed and service-name.service.ts.
STEP 2: After the service is created, we have to include it in the providers of app.module.ts
providers: [Service-nameService],
Here, the first letter of the service-name should be capitalized followed by Service written without
any space.
STEP 3: So we have to now make changes in service-name.service.ts to create a JSON variable that
is supposed to be made available to various components
Sailors = [22, ‘Dustin’, 7];
The sailors variable here is an array.
STEP 4: In app.component.ts make the following changes:
import the service among the rest of the required imports. Example:
import { Service-nameService } from './service-name.service';
just like the way we did it in providers.
Create a variable of any type: newData without mentioning any type.
In the constructor define a property of the Service type
constructor(private demoService: ServiceService) {}
Also, create a ngOnInit method:
ngOnInit(): void {
this.newData=this.demoService.Sailors;
STEP 5: In app.component.html we will print the data stored in newData:
{{newData}}
Note: As we have added ngFor in app.component.html we will have to import FormsModule
in app.module.ts
Example: This example describes the basic usage of the Services in angularJS.
Output :

You might also like