0% found this document useful (0 votes)
114 views62 pages

Angular 01052023

1. The document explains AngularJS concepts like directives, data binding, controllers and services through examples of a simple AngularJS application. 2. It demonstrates how to load AngularJS, define an app, initialize data, bind to the view and establish two-way data binding between the model and view. 3. The examples show common AngularJS constructs like modules, services, controllers configured and used together in a single file application.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
114 views62 pages

Angular 01052023

1. The document explains AngularJS concepts like directives, data binding, controllers and services through examples of a simple AngularJS application. 2. It demonstrates how to load AngularJS, define an app, initialize data, bind to the view and establish two-way data binding between the model and view. 3. The examples show common AngularJS constructs like modules, services, controllers configured and used together in a single file application.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 62

ANGULARJS Explanation

Dr. A. Sri Nagesh,


RVR & JCCEE, Guntur
Modern Web
Angular App
Rich Client
Server-Side MVC
First Program
<!DOCTYPE html>
<html ng-app>
<head>
<title>Hello, Angular</title>
<script src="https://code.angularjs.org/1.5.8/angular.min.js"></script>
</head>
<body ng-init="name='World'">
<label>Name</label>
<input ng-model="name" />
<span>Hello, {{ name }}!</span>
<p ng-bind="name"></p>
</body>
</html>
Explanation:
1. Load the Angular framework from a Content Delivery Network.
<script src="https://code.angularjs.org/1.5.8/angular.min.js"></script>
2. Define the HTML document as an Angular application with the ng-app directive
<html ng-app>
3. Initialize the name variable using ng-init
<body ng-init=" name = 'World' ">
Note that ng-init should be used for demonstrative and testing purposes only. When building
an actual application, controllers should initialize the data.
4. Bind data from the model to the view on HTML controls. Bind an <input> to the name
property with ng-model
<input ng-model="name" />
• 5. Display content from the model using double braces {{ }}
• <span>Hello, {{ name }}</span>
• 6. Another way of binding the name property is using ng-bind instead of handlebars"{{ }}"
• <span ng-bind="name"></span>
• The last three steps establish the two way data-binding. Changes made to the input
update the model, which is reflected in the view.
• There is a difference between using handlebars and ng-bind. If you use handlebars, you
might see the actual
• 5. Display content from the model using double braces {{ }}
• <span>Hello, {{ name }}</span>
• 6. Another way of binding the name property is using ng-bind instead of handlebars"{{ }}"
• <span ng-bind="name"></span>
• The last three steps establish the two way data-binding. Changes made to the input
update the model, which is reflected in the view.
• There is a difference between using handlebars and ng-bind. If you use handlebars, you
might see the actual
• Hello, {{name}} as the page loads before the expression is resolved (before the data is
loaded) whereas if you use
• ng-bind, it will only show the data when the name is resolved. As an alternative the
directive ng-cloak can be used
• to prevent handlebars to display before it is compiled.
The following example shows common AngularJS constructs in one file:

<!DOCTYPE html>
<html ng-app="myDemoApp">
<head>
<style>.started { background: gold; }</style>
<script src="https://code.angularjs.org/1.5.8/angular.min.js"></script>
<script>
function MyDataService() {
return {
getWorlds: function getWorlds() {
return ["this world", "another world"];
} };
}
function DemoController(worldsService) {
var vm = this;
vm.messages = worldsService.getWorlds().map(function(w) {
return "Hello, " + w + "!";
}
);
}
The following example shows common AngularJS constructs in one file:

function startup($rootScope, $window) {


$window.alert("Hello, user! Loading worlds...");
$rootScope.hasStarted = true;
}
angular.module("myDemoApp", [/* module dependencies go here */])
.service("worldsService", [MyDataService])
.controller("demoController", ["worldsService", DemoController])
.config(function() {
console.log('configuring application');
})
.run(["$rootScope", "$window", startup]);
</script>
</head>
The following example shows common AngularJS constructs in one file:

<body ng-class="{ 'started': hasStarted }" ng-cloak>


<div ng-controller="demoController as vm">
GoalKicker.com – AngularJS Notes for Professionals 8
<ul>
<li ng-repeat="msg in vm.messages">{{ msg }}</li>
</ul>
</div>
</body>
</html>
1. ng-app="myDemoApp", the ngApp directive that bootstraps the
application and tells angular that a DOM
element is controlled by a specific angular.module named
"myDemoApp";
2. <script src="angular.min.js"> is the first step in bootstrapping the
AngularJS library;
Three functions (MyDataService, DemoController, and startup) are
declared, which are used (and explained)
below.
3. angular.module(...) used with an array as the second argument
creates a new module. This array is used
to supply a list of module dependencies. In this example we chain calls
on the result of the module(...)
function;
4. .service(...) creates an Angular Service and returns the module for
chaining;
5. .controller(...) creates an Angular Controller and returns the
module for chaining;
6. .config(...) Use this method to register work which needs to be
performed on module loading.
7. .run(...) makes sure code is run at startup time and takes an
array of items as a parameter. Use this
method to register work which should be performed when the
injector is done loading all modules.
the first item is letting Angular know that the startup function
requires the built-in $rootScope service
to be injected as an argument;
the second item is letting Angular know that the startup function
requires the built-in $window service
to be injected as an argument;
the last item in the array, startup, is the actual function to run on
startup;
8. ng-class is the ngClass directive to set a dynamic class, and in
this example utilizes hasStarted on the
$rootScope dynamically
9. ng-cloak is a directive to prevent the unrendered Angular html
template (e.g. "{{ msg }}") to be briefly
shown before Angular has fully loaded the application.
10. ng-controller is the directive that asks Angular to instantiate
a new controller of specific name to
orchestrate that part of the DOM;
11. ng-repeat is the directive to make Angular iterate over a
collection and clone a DOM template for each item;
12. {{ msg }} showcases interpolation: on-the-spot rendering of a
part of the scope or controller;
• Open Visual Studio Code IDE. Go to the File menu and
select the "Open Folder" option. Select the MyApp
folder you have created earlier.
• Observe for our AppComponent you have below files 
– app.component.ts
– app.component.html
– app.component.css
• Let us explore each one of them
• Go to src folder-> app -> open app.component.ts file 
• Observe the following code
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'AngDemo';
}
Line 3: Adds component decorator to the class which makes the class a
component
Line 4: Specifies the tag name to be used in the HTML page to load the
component
Line 5: Specifies the template or HTML file to be rendered when the
component is loaded in the HTML page. The template represents the
view to be displayed
Line 6: Specifies the stylesheet file which contains CSS styles to be applied
to the template.
Line 8: Every component is a class (AppComponent, here) and export is
used to make it accessible in other components
Line 9: Creates a property with the name title and initializes it to value
'AngDemo'
• Open app.component.html from the app folder
and observe the following code snippet in that
file
• <span>{{ title }} app is running!</span>
• Line 3: Accessing the class property by placing
property called title inside {{ }}. This is called
interpolation which is one of the data binding
mechanisms to access class properties inside
the template.
Open index.html under the src folder.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>MyApp</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>

Line 11: loads the root component in the HTML page. app-root is the selector name given to
the component. This will execute the component and renders the template inside the browser. 
 
• ng serve –open
• ng serve --open --port 3000
• Creating a Component
• ng generate component hello
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-hello',
templateUrl: './hello.component.html',
styleUrls: ['./hello.component.css']
})
export class HelloComponent implements OnInit {
courseName: string = "Angular";
constructor() { }
ngOnInit() {
}
}
Activity
Open hello.component.html and display the
courseName as shown below in Line 2
<p>
Hello {{ courseName }}
</p>
Open hello.component.css and add the following
styles for the paragraph element
p{
color:blue;
font-size:20px;
}
• Open app.module.ts file and add
HelloComponent to bootstrap property as
shown below in Line 11 to load it for execution
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello/hello.component';
@NgModule({
imports: [BrowserModule,AppRoutingModule],
declarations: [AppComponent, HelloComponent],
providers: [],
bootstrap: [HelloComponent]
})
export class AppModule { }
• Open index.html and load the hello
component by using its selector name i.e.,
app-hello as shown below in Line 11
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>MyApp</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-hello></app-hello>
</body>
</html>
• Now run the application by giving the
following command
• ng serve --open
Templates
• By default, Angular CLI uses the external template.
• It binds the external template with a component
using templateUrl option.
•  
• Example
• app.component.html
• <h1> Welcome </h1>
• <h2> Course Name: {{ courseName }}</h2>
app.component.ts
• import { Component } from '@angular/core';
• @Component({
• selector: 'app-root',
• templateUrl:'./app.component.html',
• styleUrls: ['./app.component.css']
• })
• export class AppComponent {
• courseName = "Angular";
• }
• Highlights:
• Using the inline template
• Exploring the syntax of the inline template
• Demosteps:
• Consider HelloComponent created in the previous demo.
Angular CLI has used external template option. Now use the
inline template option.
• Problem Statement:  Moving HTML code of HelloComponent
to the component class using an inline template which should
display the following output
• Hello Angular
• Copy the code
from hello.component.html and paste it
in hello.component.ts (Line 5 to 9)
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-hello',
template:`
<p>
Hello {{ courseName }}
</p>
`,
styleUrls: ['./hello.component.css']
})
export class HelloComponent implements OnInit {
courseName = "Angular";
constructor() { }
ngOnInit() {
}
}
Elements of Template
The basic elements of template syntax:
HTML
Interpolation
Template Expressions
Template Statements
 
HTML
Angular uses HTML as a template language. In the below example, the template
contains pure HTML code.
 
Interpolation
Interpolation is one of the forms of data binding where component’s data can
be accessed in a template. For interpolation, double curly braces {{ }} is used.
 
Template Expressions
The text inside {{ }} is called as template expression.
{{ expression }}
• Angular first evaluates the expression and returns the result as a
string. The scope of a template expression is a component instance.
• That means, if you write {{ courseName }}, courseName should be
the property of the component to which this template is bound.
•  Template Statement
• Template Statements are the statements that respond to a user
event.
• (event) = statement
• For example (click) = "changeName()"
• This is called event binding. In Angular, all events should be placed
in ( ).
•  
Example:
app.component.ts

• ...
• export class AppComponent {
• courseName = "Angular";
• changeName() {
• this.courseName = "TypeScript";
• }
• }
• Line 5-7: changeName is a method of AppComponent class
where you are changing courseName property value to
"TypeScript"
•  
app.component.html
• <h1> Welcome </h1>
• <h2> Course Name: {{ courseName }}</h2>
• <p (click)="changeName()">Click here to
change</p>
• Line 3: changeName() method is bound to click
event which will be invoked on click of a
paragraph at run time. This is called event
binding.
•  
When a user clicks on the paragraph, the course name
will be changed to 'Typescript'.
Highlights:
Understanding the template elements
Responding to user actions
Demosteps:
Problem Statement: Adding an event to the hello component template and when it is clicked, it should change the courseName as shown below
Open hello.component.ts, add a
method called changeName() as
shown below in Line 12-14. Also,
use external template
hello.component.html.
Change the code
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-hello',
templateUrl: "./hello.component.html",
styleUrls: ['./hello.component.css']
})
export class HelloComponent implements OnInit {
courseName = "Angular";
constructor() { }
ngOnInit() {
}
changeName() {
this.courseName = "TypeScript";
}
}
Open hello.component.html and add a
paragraph and bind it with changeName()
method as shown in Line 3
<h1>Welcome</h1>
<h2>Course Name: {{ courseName }}</h2>
<p (click)="changeName()">Click here to
change</p>
• What does Angular do when a change is detected?
• Angular runs a change detector algorithm on each
component from top to bottom in the component tree.
This change detector algorithm is automatically generated
at run time which will check and update the changes at
appropriate places in the component tree.
• Angular is very fast though it goes through all components
from top to bottom for every single event as it generates
VM-friendly code. Due to this, Angular can perform
hundreds of thousands of checks in a few milliseconds.
• Code for WelcomeComponent is present in the file welcome.component.ts.
• import { Component } from '@angular/core';
• @Component({
• templateUrl: 'welcome.component.html',
• styleUrls: ['welcome.component.css']
• })
• export class WelcomeComponent {
• public pageTitle = 'Welcome';
• constructor() {

• }
• }
•  
• Line 3-6: @Component marks the class as component and the component is bound with template and
CSS file using templateUrl and styleUrls properties respectively.
• Line 8: Creates a property called pageTitle and initialized it to “welcome”.
• Line 11: This statement displays the login button at the top right corner of the page.
• Code for WelcomeComponent template is present in the welcome.component.html file. 
• <!-- Welcome page -->
• <div class="container container-styles">
• <div class="panel panel-primary">
• <div class="panel-heading">{{pageTitle}}</div>
• <div class="panel-body">
• <div class="row">
• <span class="img-responsive center-block logo-styles">
• <span class="glyphicon glyphicon-shopping-cart"> </span>
• </span>
• <div id="div1" class="shadow title-styles">mCart</div>

• </div>
• <br />
• <div class="row">
• <div class="text-center text-styles">An online app to purchase mobile gadgets</div>
• </div>
• </div>
• </div>
• </div>
• Line 4: pageTitle property is rendered using interpolation.
• Line 7-9: Displays a shopping cart symbol. Used bootstrap CSS classes for this.
• Line 10: Displays mCart title.
• Code for the styling of WelcomeComponent is present in the welcome.component.css file. 
• .shadow {
•     text-shadow: 3px 3px 2px rgba(150, 150, 150, 1);
• }
• .logo-styles{
•     width: 50px; 
•     font-size: 50px; 
•     color: #ff0080
• }
• .title-styles{
•     text-align: center; 
•     color: #ff0080; 
•     font-size: 40px
• }
• .text-styles{
•     color:#337ab7;
•     font-size: 15px
• }
• .container-styles{
•     position: relative; 
•     top: 180px;
•     width:50%
• }
• Line 1-3: shadow class applies a shadow effect to mCart text
• Line 5-9: logo-styles class applies width, font size and color
properties to the shopping cart logo
• Line 11-15: title-styles class applies the mentioned CSS
properties to mCart text
• Line 17-20: text-styles class applies the mentioned CSS
properties to the description text rendered at the bottom of
the welcome component
• Line 22-26: container-styles class applies the mentioned CSS
properties to the entire container
Create a Login Component as show in the
previous Slide
• Code for the LoginComponent template is
present in the login.component.html file. 
<!-- Login form-->
<div class="container container-styles">
<div class="col-xs-7 col-xs-offset-3">
<div class="panel panel-primary">
<div class="panel-heading">Login</div>
<div class="panel-body padding">
<form class="form-horizontal" [formGroup]="loginForm">
<div class="form-group" >
<label for="name" class="col-xs-4 control-label" style="text-align:left">User Name</label>
<div class="col-xs-8">
<input type="text" class="form-control" [ngClass]="{'valid':loginForm.controls['userName'].valid,
'invalid':loginForm.controls['userName'].invalid && !loginForm.controls['userName'].pristine}"
formControlName="userName">
<div *ngIf="loginForm.controls['password'].errors && loginForm.controls['userName'].dirty">
<div *ngIf="loginForm.controls['userName'].errors?.['required']" style="color:red">UserName is required
</div>
</div></div></div>
<div class="form-group">
<label for="password" class="col-xs-4 control-label" style="text-align:left">Password</label>
<div class="col-xs-8">
<input type="password" class="form-control" [ngClass]="{'valid':loginForm.controls['password'].valid,
'invalid':loginForm.controls['password'].invalid && !loginForm.controls['password'].pristine}"
formControlName="password">
<div *ngIf="loginForm.controls['password'].errors && loginForm.controls['password'].dirty">
<div *ngIf="loginForm.controls['password'].errors?.['required']"
style="color:red">Password is required
</div>
</div></div></div>
<div *ngIf="!valid" class="error">Invalid Credentials...Please try again...</div>
<br />
<div class="form-group">
<span class="col-xs-4"></span>
<div class="col-xs-3">
<button (click)="onSubmit()" class="btn btn-primary" [disabled]="!
loginForm.valid">Login</button>
</div>
<span class="col-xs-5" style="top:8px">
<a [routerLink]="['/welcome']" style="color:#337ab7;text-decoration:
underline;">Cancel</a>
</span>
</div>
</form></div></div> </div> </div>
• Line 7-41: We have created a form with two labels and two text boxes for
username and password
• Note: In the code snippet (Line nos: 11-13 and 21-23), there are some
additional code for data binding and validations which will be explained
in subsequent demos.
• Line 35: A login button is created and the click event is bound with the
onSubmit() method. onSubmit() has the code to check the validity of the
credentials.
• Line 38: A hyperlink for canceling the operation and navigating back to
the welcome component
• Note: In the code snippet (Line no: 38), there is an additional code for
routing which will be explained in subsequent demos.
•  
•  LoginComponent has a model class coded in
the login.ts, below is the code for it.
• export class Login {
• public userName: string='';
• public password: string='';
• }
•  Code for LoginComponent is coded in the file login.component.ts.
• import { Component, ElementRef, OnInit, Renderer2, ViewChild } from '@angular/core';
• import { FormBuilder, FormGroup, Validators } from '@angular/forms';
• import { Router } from '@angular/router';
• import { Login } from './Login';
• import { LoginService } from './login.service';
• @Component({
• templateUrl: './login.component.html',
• styleUrls: ['./login.component.css'],
• providers: [LoginService]
• })
• export class LoginComponent implements OnInit {
• login = new Login();
•     
•     ...
•     onSubmit() {
•   //logic for validation
•   }
• }
• Line 4: Importing Login class from login.ts
• Line 7-11: Component decorator marks the class as a
component and templateUrl to bind HTML page to Login
component
• Line 14: An instance of Login class is created
•  
• 5. Finally, bind both the components of Welcome and
Login in the root module.
• 6.  This is done in the module file of the application
i.e. app.module.ts file, it contains the below-given code. 
• import { NgModule } from '@angular/core';
• import { BrowserModule } from '@angular/platform-browser';
• import { ReactiveFormsModule } from '@angular/forms';
• import { HttpClientModule } from '@angular/common/http';
• import { AppComponent } from './app.component';
• import { AppRoutingModule } from './app-routing.module';
• import { WelcomeComponent } from './welcome/welcome.component';
• import { LoginComponent } from './login/login.component';
• @NgModule({
• imports: [BrowserModule, HttpClientModule, ReactiveFormsModule, AppRoutingModule],
• declarations: [AppComponent, WelcomeComponent, LoginComponent],
• providers: [],
• bootstrap: [AppComponent]
• })
• export class AppModule { }
• Line 7-8: Import WelcomeComponent and
LoginComponent classes
• Line 13: Include them in the declarations
property of NgModule decorator to make
them available in the entire module

You might also like