Angular - Chapter 4 - Data and Event Handling

www.webstackacademy.com
Data and Event Handling
Angular
www.webstackacademy.comwww.webstackacademy.com
Interpolation
(Connecting data with view)
www.webstackacademy.com
Interpolation
• At high level component can be broken into two parts:
 View - Which takes care of the look & Feel (HTML + CSS)
 Business logic - Which takes care of the user and server interactivity (TypeScript -> JavaScript)
{ } <#>
courses.component.ts
courses.services.ts
courses.component.html
courses.component.css
Data
How to access data from into template?
www.webstackacademy.com
Interpolation
• The major difference between writing them in a 'vanilla' fashion (how we have done during
JavaScript module) and Angular is we have followed certain rules
• The main goal of these rules is to de-couple the View (HTML + CSS) and Business Logic
• This makes components re-usable, modular and maintainable which is required for SPA
• In real-world applications these two need to work together by communicating properties
(variables, objects, arrays, etc..) from the component class to the template, you can use
interpolation
• This is achieved with the notation {{ propertyName }} in the template. With this
approach whenever we are changing the functionality, the template don’t need to change.
• This way of connection is called as Binding
www.webstackacademy.com
Interpolation
@Component({
selector: 'courses',
template: `
<h2> {{title}}</h2>
<ul> {{courses}}</ul>
`
})
export class CoursesComponent {
title = 'List of courses in WSA:';
courses = ["FullStack","FrontEnd","BackEnd"]
}
{}
<#>
www.webstackacademy.comwww.webstackacademy.com
Binding
(Connecting data with view)
www.webstackacademy.com
Binding – Big picture
www.webstackacademy.com
DOM - Revisiting
 The Document Object Model (DOM) is a cross-platform and language-independent
application programming interface
 The DOM, is the API through which JavaScript interacts with content within a website
 The DOM API is used to access, traverse and manipulate HTML and XML documents
 The HTML is represented in a tree format with each node representing a property
 Nodes have “parent-child” relationship tracing back to the “root” <html>
www.webstackacademy.com
DOM - Revisiting
www.webstackacademy.com
DOM and HTML
<html>
<body>
<h1> Courses in WSA </h1>
<ul>
<li> FullStack web developer</li>
<li> Frontend web developer </li>
<li> Backend web developer </li>
<ul>
</body>
</html>
www.webstackacademy.com
DOM and HTML – Zooming In!
www.webstackacademy.com
Attribute Binding (One way: Business logic -> View)
export class BindingComponent {
imageLink = "http://www.testimage.com/side-image.png";
}
<p><b>Example of property binding: Image</b></p>
<img [src]= "imageLink"/>
{}
<#>
www.webstackacademy.com
HTML - DOM element object
Following are some of the properties that can be used on all HTML elements
Property Description
clientHeight Returns the height of an element, including padding
Id Sets or returns the value of the id attribute of an element
innerHTML Sets or returns the content of an element
Style Sets or returns the value of the style attribute of an element
textContent Sets or returns the textual content of a node and its descendants
Title Sets or returns the value of the title attribute of an element
nextSibling Returns the next node at the same node tree level
nodeType Returns the node type of a node
www.webstackacademy.comwww.webstackacademy.com
Event Binding
(Capturing events from the view)
www.webstackacademy.com
Event Binding
• In property binding, typically the changes done in the business logic (functionality part) is
getting accessed from the view. It was achieved by the []notation, in combination with the
template (HTML) elements
• Event binding is the opposite of property binding where events from the template is sent back
to the business logic in form of event notification functions.
• Similar to how it was done with vanilla JavaScript, each event to have a call-back function along
with the event in order to notify in case of events
• User actions such as clicking a link, pushing a button, and entering text raise DOM events.
• This event binding is achieved with the ()notation
www.webstackacademy.com
Attribute Binding (One way: Business logic -> View)
{}
<#><button (click)="mySaveFunction()">Save</button>
export class EbindingComponent {
mySaveFunction() {
console.log ("Button was pressed”);
}
}
www.webstackacademy.com
More Event Handling…
<input (keyup.enter)="myKeyPress()">
Event Filtering: Event handlers can be called on a filtering basis.
View variables: Variables can be defined in the view in order to send value to business logic. These
variables are also called as Template Variables.
<input #userInput
(keyup.enter)="myKeyPressWithValue(userInput.value)">
www.webstackacademy.com
Event Binding
Methods Description
Click The event occurs when the user clicks on an element
Dbclick The event occurs when the user double-clicks on an element
Keyup The event occurs when the user releases a key
Mouseover The event occurs when the pointer is moved onto an element, or onto one of its children
Submit The event occurs when a form is submitted
Following are some of the important events which is used in event binding use-cases
www.webstackacademy.comwww.webstackacademy.com
Two way Binding
(Binding Business logic & View in both direction)
www.webstackacademy.com
Two way Binding
• One way binding in Angular is achieved in the following ways:
 From View to Business Logic (Event binding) : ()notation
 From Business logic to view (Data binding) : []notation
• They are also used in a combined manner. An event from the view
triggers a change in a HTML attribute (View->Business Logic->View)
[Ex: Changing another paragraph’s background with a button click
event]
• However handling two way binding is still not feasible with such
approaches.
• There are some ways we have achieved (ex: $event), but parameter
passing quite complex
• In order to achieve two way binding ngModel directive is used
www.webstackacademy.com
What is ngModel directive?
• ngModel is one of the directives supported by Angular to achieve two-way binding
• A directive is a custom HTML element (provided by Angular) that is used to extend the
power of HTML (More on this during next chapter)
• To set up two-way data binding with ngModel, you need to add an input in the template
and achieve binding them using combination of both square bracket and parenthesis
• With this binding whatever changes you are making in both view and business-logic get
synchronized automatically without any explicit parameter passing
<input [(ngModel)]="userInput" (keyup.enter)="userKeyPress()"/>
www.webstackacademy.com
How to use ngModel?
• ngModel is part of the Forms Module in Angular. It is not imported by default, hence it need to be done
explicitly by adding it into the app.module.ts file
www.webstackacademy.comwww.webstackacademy.com
Pipes
(Displaying data in a better way)
www.webstackacademy.com
Pipes
• Pipe takes input in the view and transforms into a better readable / understandable format
• Some of the standard pipes are supported, users can create their own pipes (custom pipes)
• Multiple pipes can be combined together to achieve the desired functionality
• Pipes are used along with text, from the template along with interpolation
• Pipes make application level handling of text much easier. Multiple pipes can also be combined
together
• In case of multiple pipes, output of one pipe is given as input of another
Pipe usage: {{ userText | Pipe }}
www.webstackacademy.com
Standard Pipes
Methods Description
Currency Formats the current input in form of currency (ex: currency:’INR’)
Date Transforms dates (shortDate | shortTime | fullDate)
Decimal Formats decimal numbers (number: ‘2.2-4’)
Lowercase Converts input into lower-case
Uppercase Converts input into upper case
Percent Convers into percentage format (percent:’2.2-5’)
www.webstackacademy.com
Exercise
• Using data binding, change the following HTML attributes by changing appropriate DOM
element:
• Font size
• Left Margin
• Top Margin
• Using event binding, handle the following events by having event handlers
• Mouse over
• Double click
• Change a HTML attribute of a text (ex: BackgroundColor) when the user click any of the
mouse events. Demonstrate view->business logic -> view binding
• Handle the following standard pipes
• Percentage
• Currency
www.webstackacademy.comwww.webstackacademy.com
Creating a Custom Pipe - GUI
(Implementing your own pipe functionality)
www.webstackacademy.com
Creating a pipe – GUI mode
 Step-1: Creating / Adding your pipe TS file
• Open your Angular project folder (ex: myFirstApp) in your editor (ex: VS code). Go to src/app folder.
• Add a new file in the following format: <pipe_name>.pipe.ts (ex: summarypipe.pipe.ts)
• Add the following lines into your new pipe file. Details given as comments.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ // Pipe decorator to tell Angular that we are implementing a pipe
name: 'summarypipe' // Pipe name, which need to be used in interpolation
})
export class SummarypipePipe implements PipeTransform {
transform(value: any,…, args?: any[]): any {
// Implement your pipe functionality here
}
www.webstackacademy.com
Implements interface
 Implements interface ensures classes must follow a particular structure that is already defined
 Basically ensures the class is of same ‘shape’
interface Point {
xValue : number;
yValue : number;
}
class MyPoint implements Point {
xValue: number;
yValue: number;
}
class MyPoint implements Point {
xValue: number;
yValue: number;
zValue: number;
}
www.webstackacademy.com
PipeTransform Interface
 The PipeTransform interface is defined in Angular (ref – below)
 The transform method is where the custom pipe functionality is implemented, which guides the
compiler to have a look-up and execute in run-time
 It will accept any number of any type of arguments and return the transformed value which also can be
of any type
interface PipeTransform {
transform(value: any, ...args: any[]): any
}
Angular official documentation URL: https://angular.io/guide/pipes
www.webstackacademy.com
Creating a pipe – GUI mode
 Step-2: Make your pipe as a part of the module (app.module.ts file)
• Add your new pipe (ex: SummaryPipe) under the declarations sections of the module.
• Ensure you import appropriate pipe files, similar to components
@NgModule({
declarations: [
AppComponent,
SummaryPipe
],
imports: [
BrowserModule,
],
providers: [],
bootstrap: [AppComponent]
})
www.webstackacademy.com
Creating a pipe – GUI mode
 Step-3: Invoking / Using the pipe
 Pipe need to be invoked by the component from its template file
<h2>Custom pipe - Example</h2>
{{ myText | summarypipe }}
 Step-4: Save all and compile. U should be able to use your custom pipe now
www.webstackacademy.comwww.webstackacademy.com
Creating a Custom pipe - CLI
(CLI mode for custom pipes)
www.webstackacademy.com
Creating a component – CLI mode
• Sometimes you might find it little hard to create a component using GUI. In case you miss out
any steps, the app will not work.
• Angular CLI offers much more reliable way to create a pipe (similar to component and services).
Try out the following command, which will not only generate a component but also make
appropriate entries
$ ng g p myformat // Creates a new pipe
www.webstackacademy.com
Creating a pipe – CLI mode
www.webstackacademy.com
Exercise
• Create a custom pipe to find out the zodiac sign of the user
• Input is given as an entry in CSV file format as follows:
• Here are the Zodiac signs for all the months:
Rajan,9845123450,rajan@gmail.com,22/05/1990,Bangalore
• Aries (March 21-April 19)
• Taurus (April 20-May 20)
• Gemini (May 21-June 20)
• Cancer (June 21-July 22)
• Leo (July 23-August 22)
• Virgo (August 23-September 22)
• Libra (September 23-October 22)
• Scorpio (October 23-November 21)
• Sagittarius (November 22-December 21)
• Capricorn (December 22-January 19)
• Aquarius (January 20 to February 18)
• Pisces (February 19 to March 20)
www.webstackacademy.com
WebStack Academy
#83, Farah Towers,
1st Floor, MG Road,
Bangalore – 560001
M: +91-809 555 7332
E: training@webstackacademy.com
WSA in Social Media:
1 de 37

Recomendados

Angular data binding por
Angular data binding Angular data binding
Angular data binding Sultan Ahmed
139 visualizações30 slides
Angular - Chapter 7 - HTTP Services por
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesWebStackAcademy
648 visualizações34 slides
Angular - Chapter 1 - Introduction por
 Angular - Chapter 1 - Introduction Angular - Chapter 1 - Introduction
Angular - Chapter 1 - IntroductionWebStackAcademy
960 visualizações39 slides
Sharing Data Between Angular Components por
Sharing Data Between Angular ComponentsSharing Data Between Angular Components
Sharing Data Between Angular ComponentsSquash Apps Pvt Ltd
1.1K visualizações23 slides
Angular 8 por
Angular 8 Angular 8
Angular 8 Sunil OS
531K visualizações93 slides
Angularjs PPT por
Angularjs PPTAngularjs PPT
Angularjs PPTAmit Baghel
5.7K visualizações24 slides

Mais conteúdo relacionado

Mais procurados

Angular - Chapter 2 - TypeScript Programming por
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming WebStackAcademy
360 visualizações47 slides
React JS - A quick introduction tutorial por
React JS - A quick introduction tutorialReact JS - A quick introduction tutorial
React JS - A quick introduction tutorialMohammed Fazuluddin
6.5K visualizações15 slides
Angular 4 The new Http Client Module por
Angular 4 The new Http Client ModuleAngular 4 The new Http Client Module
Angular 4 The new Http Client Modulearjun singh
1.2K visualizações19 slides
Unit 1 - TypeScript & Introduction to Angular CLI.pptx por
Unit 1 - TypeScript & Introduction to Angular CLI.pptxUnit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptxMalla Reddy University
447 visualizações55 slides
Introduction to angular with a simple but complete project por
Introduction to angular with a simple but complete projectIntroduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectJadson Santos
12.9K visualizações106 slides
Angular Advanced Routing por
Angular Advanced RoutingAngular Advanced Routing
Angular Advanced RoutingLaurent Duveau
4K visualizações43 slides

Mais procurados(20)

Angular - Chapter 2 - TypeScript Programming por WebStackAcademy
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming
WebStackAcademy360 visualizações
React JS - A quick introduction tutorial por Mohammed Fazuluddin
React JS - A quick introduction tutorialReact JS - A quick introduction tutorial
React JS - A quick introduction tutorial
Mohammed Fazuluddin6.5K visualizações
Angular 4 The new Http Client Module por arjun singh
Angular 4 The new Http Client ModuleAngular 4 The new Http Client Module
Angular 4 The new Http Client Module
arjun singh1.2K visualizações
Unit 1 - TypeScript & Introduction to Angular CLI.pptx por Malla Reddy University
Unit 1 - TypeScript & Introduction to Angular CLI.pptxUnit 1 - TypeScript & Introduction to Angular CLI.pptx
Unit 1 - TypeScript & Introduction to Angular CLI.pptx
Malla Reddy University447 visualizações
Introduction to angular with a simple but complete project por Jadson Santos
Introduction to angular with a simple but complete projectIntroduction to angular with a simple but complete project
Introduction to angular with a simple but complete project
Jadson Santos12.9K visualizações
Angular Advanced Routing por Laurent Duveau
Angular Advanced RoutingAngular Advanced Routing
Angular Advanced Routing
Laurent Duveau4K visualizações
Angular Data Binding por Jennifer Estrada
Angular Data BindingAngular Data Binding
Angular Data Binding
Jennifer Estrada659 visualizações
Angular js PPT por Imtiyaz Ahmad Khan
Angular js PPTAngular js PPT
Angular js PPT
Imtiyaz Ahmad Khan4.4K visualizações
Basics of JavaScript por Bala Narayanan
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
Bala Narayanan10.1K visualizações
Reactjs por Neha Sharma
Reactjs Reactjs
Reactjs
Neha Sharma10.5K visualizações
Angular modules in depth por Christoffer Noring
Angular modules in depthAngular modules in depth
Angular modules in depth
Christoffer Noring2.3K visualizações
Angular Pipes Workshop por Nir Kaufman
Angular Pipes WorkshopAngular Pipes Workshop
Angular Pipes Workshop
Nir Kaufman1.4K visualizações
Angular 9 por Raja Vishnu
Angular 9 Angular 9
Angular 9
Raja Vishnu898 visualizações
Intro to React por Justin Reock
Intro to ReactIntro to React
Intro to React
Justin Reock2.4K visualizações
Angular directives and pipes por Knoldus Inc.
Angular directives and pipesAngular directives and pipes
Angular directives and pipes
Knoldus Inc.397 visualizações
An introduction to React.js por Emanuele DelBono
An introduction to React.jsAn introduction to React.js
An introduction to React.js
Emanuele DelBono7.3K visualizações
React js por Rajesh Kolla
React jsReact js
React js
Rajesh Kolla1.2K visualizações
Angular Introduction By Surekha Gadkari por Surekha Gadkari
Angular Introduction By Surekha GadkariAngular Introduction By Surekha Gadkari
Angular Introduction By Surekha Gadkari
Surekha Gadkari901 visualizações
Routing & Navigating Pages in Angular 2 por Knoldus Inc.
Routing & Navigating Pages in Angular 2Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2
Knoldus Inc.1.5K visualizações

Similar a Angular - Chapter 4 - Data and Event Handling

Angular - Chapter 3 - Components por
Angular - Chapter 3 - ComponentsAngular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsWebStackAcademy
822 visualizações30 slides
AngularJS por
AngularJSAngularJS
AngularJSSrivatsan Krishnamachari
981 visualizações124 slides
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS por
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJSAngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJSmurtazahaveliwala
777 visualizações28 slides
AngularJs Workshop SDP December 28th 2014 por
AngularJs Workshop SDP December 28th 2014AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014Ran Wahle
510 visualizações54 slides
Introduction to Angular Js por
Introduction to Angular JsIntroduction to Angular Js
Introduction to Angular JsProfessional Guru
30 visualizações17 slides
angularJs Workshop por
angularJs WorkshopangularJs Workshop
angularJs WorkshopRan Wahle
509 visualizações54 slides

Similar a Angular - Chapter 4 - Data and Event Handling(20)

Angular - Chapter 3 - Components por WebStackAcademy
Angular - Chapter 3 - ComponentsAngular - Chapter 3 - Components
Angular - Chapter 3 - Components
WebStackAcademy822 visualizações
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS por murtazahaveliwala
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJSAngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
murtazahaveliwala777 visualizações
AngularJs Workshop SDP December 28th 2014 por Ran Wahle
AngularJs Workshop SDP December 28th 2014AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014
Ran Wahle510 visualizações
Introduction to Angular Js por Professional Guru
Introduction to Angular JsIntroduction to Angular Js
Introduction to Angular Js
Professional Guru30 visualizações
angularJs Workshop por Ran Wahle
angularJs WorkshopangularJs Workshop
angularJs Workshop
Ran Wahle509 visualizações
MVC Pattern. Flex implementation of MVC por Anton Krasnoshchok
MVC Pattern. Flex implementation of MVCMVC Pattern. Flex implementation of MVC
MVC Pattern. Flex implementation of MVC
Anton Krasnoshchok4.4K visualizações
Google Polymer Introduction por David Price
Google Polymer IntroductionGoogle Polymer Introduction
Google Polymer Introduction
David Price1.4K visualizações
Creating lightweight JS Apps w/ Web Components and lit-html por Ilia Idakiev
Creating lightweight JS Apps w/ Web Components and lit-htmlCreating lightweight JS Apps w/ Web Components and lit-html
Creating lightweight JS Apps w/ Web Components and lit-html
Ilia Idakiev1.2K visualizações
MVC & SQL_In_1_Hour por Dilip Patel
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_Hour
Dilip Patel311 visualizações
Test por guest25229c
TestTest
Test
guest25229c343 visualizações
Presentation Tier optimizations por Anup Hariharan Nair
Presentation Tier optimizationsPresentation Tier optimizations
Presentation Tier optimizations
Anup Hariharan Nair2.2K visualizações
Expedite the development lifecycle with MongoDB and serverless - DEM02 - Sant... por Amazon Web Services
Expedite the development lifecycle with MongoDB and serverless - DEM02 - Sant...Expedite the development lifecycle with MongoDB and serverless - DEM02 - Sant...
Expedite the development lifecycle with MongoDB and serverless - DEM02 - Sant...
Amazon Web Services282 visualizações
Adding a view por Nhan Do
Adding a viewAdding a view
Adding a view
Nhan Do477 visualizações
Angular 2 Essential Training por Patrick Schroeder
Angular 2 Essential Training Angular 2 Essential Training
Angular 2 Essential Training
Patrick Schroeder4K visualizações
introduction to Angularjs basics por Ravindra K
introduction to Angularjs basicsintroduction to Angularjs basics
introduction to Angularjs basics
Ravindra K961 visualizações
Angularjs Basics por Anuradha Bandara
Angularjs BasicsAngularjs Basics
Angularjs Basics
Anuradha Bandara1.4K visualizações
Fundaments of Knockout js por Flavius-Radu Demian
Fundaments of Knockout jsFundaments of Knockout js
Fundaments of Knockout js
Flavius-Radu Demian2.4K visualizações
Knockoutjs databinding por Boulos Dib
Knockoutjs databindingKnockoutjs databinding
Knockoutjs databinding
Boulos Dib1.5K visualizações

Mais de WebStackAcademy

Webstack Academy - Internship Kick Off por
Webstack Academy - Internship Kick OffWebstack Academy - Internship Kick Off
Webstack Academy - Internship Kick OffWebStackAcademy
2 visualizações28 slides
Front-End Developer's Career Roadmap por
Front-End Developer's Career RoadmapFront-End Developer's Career Roadmap
Front-End Developer's Career RoadmapWebStackAcademy
98 visualizações43 slides
Angular - Chapter 9 - Authentication and Authorization por
Angular - Chapter 9 - Authentication and AuthorizationAngular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and AuthorizationWebStackAcademy
1.9K visualizações19 slides
Angular - Chapter 6 - Firebase Integration por
Angular - Chapter 6 - Firebase IntegrationAngular - Chapter 6 - Firebase Integration
Angular - Chapter 6 - Firebase IntegrationWebStackAcademy
255 visualizações42 slides
JavaScript - Chapter 10 - Strings and Arrays por
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and ArraysWebStackAcademy
1.7K visualizações62 slides
JavaScript - Chapter 15 - Debugging Techniques por
 JavaScript - Chapter 15 - Debugging Techniques JavaScript - Chapter 15 - Debugging Techniques
JavaScript - Chapter 15 - Debugging TechniquesWebStackAcademy
768 visualizações25 slides

Mais de WebStackAcademy(20)

Webstack Academy - Internship Kick Off por WebStackAcademy
Webstack Academy - Internship Kick OffWebstack Academy - Internship Kick Off
Webstack Academy - Internship Kick Off
WebStackAcademy2 visualizações
Front-End Developer's Career Roadmap por WebStackAcademy
Front-End Developer's Career RoadmapFront-End Developer's Career Roadmap
Front-End Developer's Career Roadmap
WebStackAcademy98 visualizações
Angular - Chapter 9 - Authentication and Authorization por WebStackAcademy
Angular - Chapter 9 - Authentication and AuthorizationAngular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and Authorization
WebStackAcademy1.9K visualizações
Angular - Chapter 6 - Firebase Integration por WebStackAcademy
Angular - Chapter 6 - Firebase IntegrationAngular - Chapter 6 - Firebase Integration
Angular - Chapter 6 - Firebase Integration
WebStackAcademy255 visualizações
JavaScript - Chapter 10 - Strings and Arrays por WebStackAcademy
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and Arrays
WebStackAcademy1.7K visualizações
JavaScript - Chapter 15 - Debugging Techniques por WebStackAcademy
 JavaScript - Chapter 15 - Debugging Techniques JavaScript - Chapter 15 - Debugging Techniques
JavaScript - Chapter 15 - Debugging Techniques
WebStackAcademy768 visualizações
JavaScript - Chapter 14 - Form Handling por WebStackAcademy
 JavaScript - Chapter 14 - Form Handling   JavaScript - Chapter 14 - Form Handling
JavaScript - Chapter 14 - Form Handling
WebStackAcademy1.1K visualizações
JavaScript - Chapter 13 - Browser Object Model(BOM) por WebStackAcademy
JavaScript - Chapter 13 - Browser Object Model(BOM)JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)
WebStackAcademy3.4K visualizações
JavaScript - Chapter 12 - Document Object Model por WebStackAcademy
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy5.3K visualizações
JavaScript - Chapter 11 - Events por WebStackAcademy
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
WebStackAcademy1.2K visualizações
JavaScript - Chapter 9 - TypeConversion and Regular Expressions por WebStackAcademy
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
WebStackAcademy360 visualizações
JavaScript - Chapter 8 - Objects por WebStackAcademy
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
WebStackAcademy1.6K visualizações
JavaScript - Chapter 7 - Advanced Functions por WebStackAcademy
 JavaScript - Chapter 7 - Advanced Functions JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced Functions
WebStackAcademy241 visualizações
JavaScript - Chapter 6 - Basic Functions por WebStackAcademy
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
WebStackAcademy1.1K visualizações
JavaScript - Chapter 5 - Operators por WebStackAcademy
 JavaScript - Chapter 5 - Operators JavaScript - Chapter 5 - Operators
JavaScript - Chapter 5 - Operators
WebStackAcademy1.1K visualizações
JavaScript - Chapter 4 - Types and Statements por WebStackAcademy
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and Statements
WebStackAcademy1.5K visualizações
JavaScript - Chapter 3 - Introduction por WebStackAcademy
 JavaScript - Chapter 3 - Introduction JavaScript - Chapter 3 - Introduction
JavaScript - Chapter 3 - Introduction
WebStackAcademy3.2K visualizações
JavaScript - Chapter 1 - Problem Solving por WebStackAcademy
 JavaScript - Chapter 1 - Problem Solving JavaScript - Chapter 1 - Problem Solving
JavaScript - Chapter 1 - Problem Solving
WebStackAcademy251 visualizações
jQuery - Chapter 4 - DOM Handling por WebStackAcademy
jQuery - Chapter 4 - DOM Handling jQuery - Chapter 4 - DOM Handling
jQuery - Chapter 4 - DOM Handling
WebStackAcademy113 visualizações
jQuery - Chapter 5 - Ajax por WebStackAcademy
jQuery - Chapter 5 -  AjaxjQuery - Chapter 5 -  Ajax
jQuery - Chapter 5 - Ajax
WebStackAcademy113 visualizações

Último

Melek BEN MAHMOUD.pdf por
Melek BEN MAHMOUD.pdfMelek BEN MAHMOUD.pdf
Melek BEN MAHMOUD.pdfMelekBenMahmoud
14 visualizações1 slide
Attacking IoT Devices from a Web Perspective - Linux Day por
Attacking IoT Devices from a Web Perspective - Linux Day Attacking IoT Devices from a Web Perspective - Linux Day
Attacking IoT Devices from a Web Perspective - Linux Day Simone Onofri
16 visualizações68 slides
Network Source of Truth and Infrastructure as Code revisited por
Network Source of Truth and Infrastructure as Code revisitedNetwork Source of Truth and Infrastructure as Code revisited
Network Source of Truth and Infrastructure as Code revisitedNetwork Automation Forum
26 visualizações45 slides
Microsoft Power Platform.pptx por
Microsoft Power Platform.pptxMicrosoft Power Platform.pptx
Microsoft Power Platform.pptxUni Systems S.M.S.A.
53 visualizações38 slides
Democratising digital commerce in India-Report por
Democratising digital commerce in India-ReportDemocratising digital commerce in India-Report
Democratising digital commerce in India-ReportKapil Khandelwal (KK)
15 visualizações161 slides
The details of description: Techniques, tips, and tangents on alternative tex... por
The details of description: Techniques, tips, and tangents on alternative tex...The details of description: Techniques, tips, and tangents on alternative tex...
The details of description: Techniques, tips, and tangents on alternative tex...BookNet Canada
127 visualizações24 slides

Último(20)

Melek BEN MAHMOUD.pdf por MelekBenMahmoud
Melek BEN MAHMOUD.pdfMelek BEN MAHMOUD.pdf
Melek BEN MAHMOUD.pdf
MelekBenMahmoud14 visualizações
Attacking IoT Devices from a Web Perspective - Linux Day por Simone Onofri
Attacking IoT Devices from a Web Perspective - Linux Day Attacking IoT Devices from a Web Perspective - Linux Day
Attacking IoT Devices from a Web Perspective - Linux Day
Simone Onofri16 visualizações
Network Source of Truth and Infrastructure as Code revisited por Network Automation Forum
Network Source of Truth and Infrastructure as Code revisitedNetwork Source of Truth and Infrastructure as Code revisited
Network Source of Truth and Infrastructure as Code revisited
Network Automation Forum26 visualizações
Microsoft Power Platform.pptx por Uni Systems S.M.S.A.
Microsoft Power Platform.pptxMicrosoft Power Platform.pptx
Microsoft Power Platform.pptx
Uni Systems S.M.S.A.53 visualizações
Democratising digital commerce in India-Report por Kapil Khandelwal (KK)
Democratising digital commerce in India-ReportDemocratising digital commerce in India-Report
Democratising digital commerce in India-Report
Kapil Khandelwal (KK)15 visualizações
The details of description: Techniques, tips, and tangents on alternative tex... por BookNet Canada
The details of description: Techniques, tips, and tangents on alternative tex...The details of description: Techniques, tips, and tangents on alternative tex...
The details of description: Techniques, tips, and tangents on alternative tex...
BookNet Canada127 visualizações
Info Session November 2023.pdf por AleksandraKoprivica4
Info Session November 2023.pdfInfo Session November 2023.pdf
Info Session November 2023.pdf
AleksandraKoprivica412 visualizações
PRODUCT LISTING.pptx por angelicacueva6
PRODUCT LISTING.pptxPRODUCT LISTING.pptx
PRODUCT LISTING.pptx
angelicacueva614 visualizações
virtual reality.pptx por G036GaikwadSnehal
virtual reality.pptxvirtual reality.pptx
virtual reality.pptx
G036GaikwadSnehal11 visualizações
Empathic Computing: Delivering the Potential of the Metaverse por Mark Billinghurst
Empathic Computing: Delivering  the Potential of the MetaverseEmpathic Computing: Delivering  the Potential of the Metaverse
Empathic Computing: Delivering the Potential of the Metaverse
Mark Billinghurst478 visualizações
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N... por James Anderson
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...
James Anderson85 visualizações
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas... por Bernd Ruecker
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
Bernd Ruecker37 visualizações
Evolving the Network Automation Journey from Python to Platforms por Network Automation Forum
Evolving the Network Automation Journey from Python to PlatformsEvolving the Network Automation Journey from Python to Platforms
Evolving the Network Automation Journey from Python to Platforms
Network Automation Forum13 visualizações
Case Study Copenhagen Energy and Business Central.pdf por Aitana
Case Study Copenhagen Energy and Business Central.pdfCase Study Copenhagen Energy and Business Central.pdf
Case Study Copenhagen Energy and Business Central.pdf
Aitana16 visualizações
SUPPLIER SOURCING.pptx por angelicacueva6
SUPPLIER SOURCING.pptxSUPPLIER SOURCING.pptx
SUPPLIER SOURCING.pptx
angelicacueva615 visualizações
Data Integrity for Banking and Financial Services por Precisely
Data Integrity for Banking and Financial ServicesData Integrity for Banking and Financial Services
Data Integrity for Banking and Financial Services
Precisely21 visualizações

Angular - Chapter 4 - Data and Event Handling

  • 3. www.webstackacademy.com Interpolation • At high level component can be broken into two parts:  View - Which takes care of the look & Feel (HTML + CSS)  Business logic - Which takes care of the user and server interactivity (TypeScript -> JavaScript) { } <#> courses.component.ts courses.services.ts courses.component.html courses.component.css Data How to access data from into template?
  • 4. www.webstackacademy.com Interpolation • The major difference between writing them in a 'vanilla' fashion (how we have done during JavaScript module) and Angular is we have followed certain rules • The main goal of these rules is to de-couple the View (HTML + CSS) and Business Logic • This makes components re-usable, modular and maintainable which is required for SPA • In real-world applications these two need to work together by communicating properties (variables, objects, arrays, etc..) from the component class to the template, you can use interpolation • This is achieved with the notation {{ propertyName }} in the template. With this approach whenever we are changing the functionality, the template don’t need to change. • This way of connection is called as Binding
  • 5. www.webstackacademy.com Interpolation @Component({ selector: 'courses', template: ` <h2> {{title}}</h2> <ul> {{courses}}</ul> ` }) export class CoursesComponent { title = 'List of courses in WSA:'; courses = ["FullStack","FrontEnd","BackEnd"] } {} <#>
  • 8. www.webstackacademy.com DOM - Revisiting  The Document Object Model (DOM) is a cross-platform and language-independent application programming interface  The DOM, is the API through which JavaScript interacts with content within a website  The DOM API is used to access, traverse and manipulate HTML and XML documents  The HTML is represented in a tree format with each node representing a property  Nodes have “parent-child” relationship tracing back to the “root” <html>
  • 10. www.webstackacademy.com DOM and HTML <html> <body> <h1> Courses in WSA </h1> <ul> <li> FullStack web developer</li> <li> Frontend web developer </li> <li> Backend web developer </li> <ul> </body> </html>
  • 12. www.webstackacademy.com Attribute Binding (One way: Business logic -> View) export class BindingComponent { imageLink = "http://www.testimage.com/side-image.png"; } <p><b>Example of property binding: Image</b></p> <img [src]= "imageLink"/> {} <#>
  • 13. www.webstackacademy.com HTML - DOM element object Following are some of the properties that can be used on all HTML elements Property Description clientHeight Returns the height of an element, including padding Id Sets or returns the value of the id attribute of an element innerHTML Sets or returns the content of an element Style Sets or returns the value of the style attribute of an element textContent Sets or returns the textual content of a node and its descendants Title Sets or returns the value of the title attribute of an element nextSibling Returns the next node at the same node tree level nodeType Returns the node type of a node
  • 15. www.webstackacademy.com Event Binding • In property binding, typically the changes done in the business logic (functionality part) is getting accessed from the view. It was achieved by the []notation, in combination with the template (HTML) elements • Event binding is the opposite of property binding where events from the template is sent back to the business logic in form of event notification functions. • Similar to how it was done with vanilla JavaScript, each event to have a call-back function along with the event in order to notify in case of events • User actions such as clicking a link, pushing a button, and entering text raise DOM events. • This event binding is achieved with the ()notation
  • 16. www.webstackacademy.com Attribute Binding (One way: Business logic -> View) {} <#><button (click)="mySaveFunction()">Save</button> export class EbindingComponent { mySaveFunction() { console.log ("Button was pressed”); } }
  • 17. www.webstackacademy.com More Event Handling… <input (keyup.enter)="myKeyPress()"> Event Filtering: Event handlers can be called on a filtering basis. View variables: Variables can be defined in the view in order to send value to business logic. These variables are also called as Template Variables. <input #userInput (keyup.enter)="myKeyPressWithValue(userInput.value)">
  • 18. www.webstackacademy.com Event Binding Methods Description Click The event occurs when the user clicks on an element Dbclick The event occurs when the user double-clicks on an element Keyup The event occurs when the user releases a key Mouseover The event occurs when the pointer is moved onto an element, or onto one of its children Submit The event occurs when a form is submitted Following are some of the important events which is used in event binding use-cases
  • 20. www.webstackacademy.com Two way Binding • One way binding in Angular is achieved in the following ways:  From View to Business Logic (Event binding) : ()notation  From Business logic to view (Data binding) : []notation • They are also used in a combined manner. An event from the view triggers a change in a HTML attribute (View->Business Logic->View) [Ex: Changing another paragraph’s background with a button click event] • However handling two way binding is still not feasible with such approaches. • There are some ways we have achieved (ex: $event), but parameter passing quite complex • In order to achieve two way binding ngModel directive is used
  • 21. www.webstackacademy.com What is ngModel directive? • ngModel is one of the directives supported by Angular to achieve two-way binding • A directive is a custom HTML element (provided by Angular) that is used to extend the power of HTML (More on this during next chapter) • To set up two-way data binding with ngModel, you need to add an input in the template and achieve binding them using combination of both square bracket and parenthesis • With this binding whatever changes you are making in both view and business-logic get synchronized automatically without any explicit parameter passing <input [(ngModel)]="userInput" (keyup.enter)="userKeyPress()"/>
  • 22. www.webstackacademy.com How to use ngModel? • ngModel is part of the Forms Module in Angular. It is not imported by default, hence it need to be done explicitly by adding it into the app.module.ts file
  • 24. www.webstackacademy.com Pipes • Pipe takes input in the view and transforms into a better readable / understandable format • Some of the standard pipes are supported, users can create their own pipes (custom pipes) • Multiple pipes can be combined together to achieve the desired functionality • Pipes are used along with text, from the template along with interpolation • Pipes make application level handling of text much easier. Multiple pipes can also be combined together • In case of multiple pipes, output of one pipe is given as input of another Pipe usage: {{ userText | Pipe }}
  • 25. www.webstackacademy.com Standard Pipes Methods Description Currency Formats the current input in form of currency (ex: currency:’INR’) Date Transforms dates (shortDate | shortTime | fullDate) Decimal Formats decimal numbers (number: ‘2.2-4’) Lowercase Converts input into lower-case Uppercase Converts input into upper case Percent Convers into percentage format (percent:’2.2-5’)
  • 26. www.webstackacademy.com Exercise • Using data binding, change the following HTML attributes by changing appropriate DOM element: • Font size • Left Margin • Top Margin • Using event binding, handle the following events by having event handlers • Mouse over • Double click • Change a HTML attribute of a text (ex: BackgroundColor) when the user click any of the mouse events. Demonstrate view->business logic -> view binding • Handle the following standard pipes • Percentage • Currency
  • 27. www.webstackacademy.comwww.webstackacademy.com Creating a Custom Pipe - GUI (Implementing your own pipe functionality)
  • 28. www.webstackacademy.com Creating a pipe – GUI mode  Step-1: Creating / Adding your pipe TS file • Open your Angular project folder (ex: myFirstApp) in your editor (ex: VS code). Go to src/app folder. • Add a new file in the following format: <pipe_name>.pipe.ts (ex: summarypipe.pipe.ts) • Add the following lines into your new pipe file. Details given as comments. import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ // Pipe decorator to tell Angular that we are implementing a pipe name: 'summarypipe' // Pipe name, which need to be used in interpolation }) export class SummarypipePipe implements PipeTransform { transform(value: any,…, args?: any[]): any { // Implement your pipe functionality here }
  • 29. www.webstackacademy.com Implements interface  Implements interface ensures classes must follow a particular structure that is already defined  Basically ensures the class is of same ‘shape’ interface Point { xValue : number; yValue : number; } class MyPoint implements Point { xValue: number; yValue: number; } class MyPoint implements Point { xValue: number; yValue: number; zValue: number; }
  • 30. www.webstackacademy.com PipeTransform Interface  The PipeTransform interface is defined in Angular (ref – below)  The transform method is where the custom pipe functionality is implemented, which guides the compiler to have a look-up and execute in run-time  It will accept any number of any type of arguments and return the transformed value which also can be of any type interface PipeTransform { transform(value: any, ...args: any[]): any } Angular official documentation URL: https://angular.io/guide/pipes
  • 31. www.webstackacademy.com Creating a pipe – GUI mode  Step-2: Make your pipe as a part of the module (app.module.ts file) • Add your new pipe (ex: SummaryPipe) under the declarations sections of the module. • Ensure you import appropriate pipe files, similar to components @NgModule({ declarations: [ AppComponent, SummaryPipe ], imports: [ BrowserModule, ], providers: [], bootstrap: [AppComponent] })
  • 32. www.webstackacademy.com Creating a pipe – GUI mode  Step-3: Invoking / Using the pipe  Pipe need to be invoked by the component from its template file <h2>Custom pipe - Example</h2> {{ myText | summarypipe }}  Step-4: Save all and compile. U should be able to use your custom pipe now
  • 34. www.webstackacademy.com Creating a component – CLI mode • Sometimes you might find it little hard to create a component using GUI. In case you miss out any steps, the app will not work. • Angular CLI offers much more reliable way to create a pipe (similar to component and services). Try out the following command, which will not only generate a component but also make appropriate entries $ ng g p myformat // Creates a new pipe
  • 36. www.webstackacademy.com Exercise • Create a custom pipe to find out the zodiac sign of the user • Input is given as an entry in CSV file format as follows: • Here are the Zodiac signs for all the months: Rajan,9845123450,rajan@gmail.com,22/05/1990,Bangalore • Aries (March 21-April 19) • Taurus (April 20-May 20) • Gemini (May 21-June 20) • Cancer (June 21-July 22) • Leo (July 23-August 22) • Virgo (August 23-September 22) • Libra (September 23-October 22) • Scorpio (October 23-November 21) • Sagittarius (November 22-December 21) • Capricorn (December 22-January 19) • Aquarius (January 20 to February 18) • Pisces (February 19 to March 20)
  • 37. www.webstackacademy.com WebStack Academy #83, Farah Towers, 1st Floor, MG Road, Bangalore – 560001 M: +91-809 555 7332 E: training@webstackacademy.com WSA in Social Media: