SlideShare ist ein Scribd-Unternehmen logo
1 von 48
Downloaden Sie, um offline zu lesen
Angular Rebooted:
Components Everywhere
Carlo Bonamico -Sonia Pini
MILAN 25-26 NOVEMBER 2016
sonia.pini@nispro.it
carlo.bonamico@nispro.it - NIS s.r.l. - a DGS company
carlo.bonamico@gmail.com – Genova Java User Group
Twitter: @carlobonamico @nis_srl
Abstract
Attracted by AngularJS power and simplicity, you have chosen it for your next project.
Getting started with DataBinding, Scopes and Controllers was relatively quick and
easy...
But what do you need to effectively bring a complex application to Production?
We discuss
● the new Component API,
● lifecycle callbacks - $onChanges
● selecting different ways for components to collaborate
● choosing between Two-Way Binding and One-Way Data Flow,
● "smart" vs "dumb" components,
We ‘ll share recipes from our real world experience so that you can productively &
reliably build a complex application out of reusable Components.
We all love AngularJs
● Simple & Powerful
○ Two way data binding is legendary
○ Dependency Injection is awesome
○ Routing is very flexible
○ D.R.Y and reusable code made easy
○ Components/Directives FTW
○ Modular and component-driven
…
○ Testable code
We all love AngularJs
Real world apps are not easy
Bringing a complex application to production
requires more than quickly bind form fields:
● decoupling unrelated parts
● preventing fragility in the face of changes
● keeping collaboration effective as team grows
● avoiding performance issues
Angular gives us good tools
- but we need to use them in the right way
Avoiding bad practices
Often, as the application starts to grow, we see
● single large controller and HTML file per view
○ thousands of lines each
● significant repetition across views
○ same HTML fragments in many files
● “Spaghetti Binding”
○ creates dependencies between unrelated parts
Code becomes hard to navigate / risky to change
We need Software Engineering for the Frontend, too
“Spaghetti Binding” vs Components
What is a Component?
● Self-contained set of UI and logic
○ encapsulates a specific behaviour
○ provides an explicit API
● Since Angular 1.5, special kind of Directive with
○ UI in a template
○ Logic in a controller
○ some metadata (inputs, outputs, …)
● Makes it easier/cheaper to do a good design
○ pushing the community towards best practices
● In Angular 2, the main application construct
Most of the concepts that we present apply to both
Angular 1.5 & Angular 2.0
although syntax is different
Example App: NG Component Mail
Full Source in https://github.com/carlobonamico/angular-component-based
Thinking in Components
<message-list>
<folder-list
> <nav-actions>
<message-viewer>
<search-panel>
<folder-list
>
<message-actions>
Design the Component API
Define input and output properties
● Keep naming conventions consistent
● Follow Clean Code guidelines
<component>
inputs
outputs
<folder-list> API and behavior
input → folder array, title, allowCreate
output → selected folder
encapsulated state and
behaviour →
current folder, select with click,
sorting, filtering
● = → two-way binding
● < → one-way binding
● @ → input string
● ? → optional
<folder-list> - Declaring Inputs
Template
Component
Controller
Passing Inputs to <folder-list>
FolderList Component
Why didn’t we use “=”?
The “=” qualifier means that the binding is two-way
● the <folder-list> component could even replace
the folder array with another one
○ while it’s role is just to display it
● and this change could also immediately affect
various other parts of the page which reference
the folder array in their {{}} expressions and
$watch-es
Guideline: default to “<” for component inputs
● one-way change propagation
Two-way bindings pros and cons
● Very effective collaboration “in the small”
○ like when all people in a room can talk to each
other to solve a problem
○ ng-model for bi-directional updates between
form inputs and model
○ a validation expression can reference several
model variables
● creates chaos “in the large”
○ think all people in the building talking to any
one else
How to handle <folder-list> Output?
Passing the selected folder to the MailController
which updates the message list - ideas?
● Option 1
■ $scope.$parent.currentFolder = selectedFolder
○ avoid! it makes the component non-reusable
● Option 2 - two-way binding
■ binding selectedFolder : “=”
■ <folder-list selected-folder=”mailCtrl.currentFolder”>
■ in the parent, $watch(‘currentFolder’, function(){
loadMessages(currentFolder)})
Making Outputs explicit with Events
Option 3 - The component
● detects when a significant user action takes place
● updates its internal state
○ e.g. track the selected folder
● updates its view
○ display the element in bold / red
● sends an event to notify the parent component
○ including relevant data (e.g. folder id / name)
● lets the parent component decide what to do then
○ e.g. retrieving a new message list
Sending the event in <folder-list>
● We declare an output binding with “&”
● Angular injects an emitter function in the controller
● We call it passing an Event Object including
relevant data
MailController
<folder-list>
component
Using the component output
Specify an expression to be executed in the parent
scope when the event is received
Parent Component Controller
FolderListController
mail-view HTML
Advantages
Stonger Encapsulation (isolated scope + explicit
binding)
● changing the component internal implementation
has less impact on the rest of the application
● more decoupling, less regressions
Reusability (with parametrization)
● same component used in different contexts
○ <message-list> can display either folder
messages and search results
Advantages
Better Collaboration
● less conflicts when team grows
● easier to test for regressions
More Clarity and Readability
● I can effectively use a component knowing only
its API (the bindings section)
● the link to other component is very clear and
explict in the HTML
Components all the way down
What happens if we consistently apply this pattern
across the entire application?
The application becomes...
A tree of collaborating Components
<mail-view>
<folder-list> <message-list>
<nav-actions><common-star>
<message-view>
<common-star>
Types of Components
<mail-view>
<folder-list> <message-list>
<nav-actions><common-star>
<message-view>
<common-star>
more
application - specific
more generic/reusable
Types of Components
<mail-view>
<folder-list> <message-list>
<nav-actions><common-star>
<message-view>
<common-star>
“Smart” components
“Dumb” components
Services /
$http
Components: Smart vs Dumb
● Also called stateful
● Provides data - e.g. from http
REST clients
● May receive initial data via
route resolves
● Has knowledge of the
current state
● Is informed by stateless
components when
something needs to change
● Also called stateless
● Like a pure JavaScript
function
● It receives data via property
binding
● it focuses on rendering and
interaction without
managing business logic
● It requests state changes
through explicit events
Data Flow “down”: property binding
Component pass a subset of their model to children
<mail-view>
<folder-list> <message-list>
<nav-actions><common-star>
<message-view>
<common-star>
folders
messages
currentMessage
Data Flow “up”: events & callbacks
Component pass relevant events/changes to parent
<mail-view>
<folder-list> <message-list>
<nav-actions><common-star>
<message-view>
<common-star>
onSelected()
onCurrentMsg()
onStar()
onReply()
onNext()
Component Interaction
Complex behaviour achieved through collaboration
<mail-view>
<folder-list> <message-list> <message-view>
onSelected()
Component Interaction
Complex behaviour achieved through collaboration
<mail-view>
<folder-list> <message-list> <message-view>
messages
Component Interaction
Complex behaviour achieved through collaboration
<mail-view>
<folder-list> <message-list> <message-view>
onSelected()
onCurrentMsg()messages
currentMessage
Advantages
If a component passes data to its children, that it
knows well, the risk of unintended side effects is low
If a component notifies its parent, the change can
potentially affect unrelated / not yet developed parts
● more explicit and controlled
● parent component can mediate and orchestrate
how the child interacts with the rest
Also, the tree is very good for performance
Component means Composable
What is the right size of a component?
Component means Composable
There is no “right answer”, but...
● if a component becomes too big, split it into
collaborating child components
Basic Design Principles
●Low Coupling - avoid unneeded dependencies
●High Cohesion - Single Responsibility Principle
(SOLID Principle)
− separate things that change for different
reasons or at different times
In short: don’t put your socks in the fridge...
Single Responsibility applied
If you need to do 2 things, make 3 components
● A, B
● C that does A + B
Example
● <upload-attachment> does file browsing and calls
the UploadService HTTP client
● <attachment-list> displays the currently attached
messages
● <mail-attachments> groups the first two
More Component goodies
● Since Angular 1.5.3, Components can declare
"lifecycle hooks"
● $onInit()
○ one-time initialization after interconnected
components have been bound
○ https://toddmotto.com/on-init-require-object-syntax-angular
-component
● $onDestroy()
○ deallocate resources when the component is
removed from the view
○ e.g. a websocket in a chat
Change notification
● $onChanges
○ Called when “<” / input bindings are updated
○ parameter: a changes object including
■ keys for each changed property
■ previousValue and currentValue
● Very effective for
○ compute derived values
■ compute unread messages count
○ apply filtering or sorting to data
■ display various sets of messages according to a choice
http://blog.thoughtram.io/angularjs/2016/03/29/exploring-angular-1.5-lifecycle-hooks.html
$onChanges: filtering message list
Test a Component Controller
Pass inputs to the controller and test its behaviour
ngMock module has been updated with the
$componentController method
Test a Component
we can compile the element and test
● that it renders what we expected
● that it correctly reacts to user events
What happens in Angular 2?
Components in Angular 2
Syntax, some costructs change, but
Component-based Architecture is even stronger
● no more stand-alone controllers
● even application home, first-level views become
components
○ component-based routing
● component metadata + Typescript allow for
○ better tooling support
○ completion, validation
○ more explicit API definition
<folder-list> in Angular2
Components
are
the future of web apps
References on Components
Angular 1.5 Components reference
https://docs.angularjs.org/guide/component
Exploring Angular 1.5 Components
https://toddmotto.com/exploring-the-angular-1-5-component-meth
od/
Refactoring an 1.5 application to Components
https://teropa.info/blog/2015/10/18/refactoring-angular-apps-to-co
mponents.html
Components in Angular 2
https://angular.io/docs/ts/latest/cookbook/component-communicat
ion.html
Thank you!
● Other presentations
− http://www.slideshare.net/carlo.bonamico/presentations
● Follow us on Twitter
− @carlobonamico @nis_srl
● updates on AngularJS!
● and some Security, Ansible, Continuous Delivery
● Contact us
− carlo.bonamico@gmail.com / carlo.bonamico@nispro.it
− Sonia.pini@nispro.it
● Our company
− http://www.nispro.it

Weitere ähnliche Inhalte

Was ist angesagt?

Web application framework
Web application frameworkWeb application framework
Web application frameworkPankaj Chand
 
Basic Java script handouts for students
Basic Java script handouts for students Basic Java script handouts for students
Basic Java script handouts for students shafiq sangi
 
Frontend Monoliths: Run if you can!
Frontend Monoliths: Run if you can!Frontend Monoliths: Run if you can!
Frontend Monoliths: Run if you can!Jonas Bandi
 
“Micro Frontends”- You Keep Using That Word, I Don’t Think It Means What You ...
“Micro Frontends”- You Keep Using That Word, I Don’t Think It Means What You ...“Micro Frontends”- You Keep Using That Word, I Don’t Think It Means What You ...
“Micro Frontends”- You Keep Using That Word, I Don’t Think It Means What You ...Shem Magnezi
 
Refactoring to a Single Page Application
Refactoring to a Single Page ApplicationRefactoring to a Single Page Application
Refactoring to a Single Page ApplicationCodemotion
 
Overview of React.JS - Internship Presentation - Week 5
Overview of React.JS - Internship Presentation - Week 5Overview of React.JS - Internship Presentation - Week 5
Overview of React.JS - Internship Presentation - Week 5Devang Garach
 
Angular 2 Seminar_(December 7/12/2015)
Angular 2 Seminar_(December 7/12/2015)Angular 2 Seminar_(December 7/12/2015)
Angular 2 Seminar_(December 7/12/2015)Haim Michael
 
Single Page Application (SPA) using AngularJS
Single Page Application (SPA) using AngularJSSingle Page Application (SPA) using AngularJS
Single Page Application (SPA) using AngularJSM R Rony
 
MTaulty_DevWeek_Silverlight
MTaulty_DevWeek_SilverlightMTaulty_DevWeek_Silverlight
MTaulty_DevWeek_Silverlightukdpe
 
MVVM+MEF in Silvelight - W 2010ebday
MVVM+MEF in Silvelight - W 2010ebdayMVVM+MEF in Silvelight - W 2010ebday
MVVM+MEF in Silvelight - W 2010ebdayRicardo Fiel
 
The Ultimate Getting Started with Angular Workshop - Devoxx UK 2017
The Ultimate Getting Started with Angular Workshop - Devoxx UK 2017The Ultimate Getting Started with Angular Workshop - Devoxx UK 2017
The Ultimate Getting Started with Angular Workshop - Devoxx UK 2017Matt Raible
 
ASP Dot Net Software Development in India - iFour Technolab
ASP Dot Net Software Development in India - iFour TechnolabASP Dot Net Software Development in India - iFour Technolab
ASP Dot Net Software Development in India - iFour TechnolabiFour Technolab Pvt. Ltd.
 
Web Development Presentation
Web Development PresentationWeb Development Presentation
Web Development PresentationTurnToTech
 
Building Cross Platform Mobile Apps
Building Cross Platform Mobile AppsBuilding Cross Platform Mobile Apps
Building Cross Platform Mobile AppsShailendra Chauhan
 
Latest Javascript MVC & Front End Frameworks 2017
Latest Javascript MVC & Front End Frameworks 2017Latest Javascript MVC & Front End Frameworks 2017
Latest Javascript MVC & Front End Frameworks 2017AmarInfotech
 
PLASTIC 2011: "Enterprise JavaScript with Jangaroo"
PLASTIC 2011: "Enterprise JavaScript with Jangaroo"PLASTIC 2011: "Enterprise JavaScript with Jangaroo"
PLASTIC 2011: "Enterprise JavaScript with Jangaroo"Frank Wienberg
 

Was ist angesagt? (20)

Web application framework
Web application frameworkWeb application framework
Web application framework
 
Basic Java script handouts for students
Basic Java script handouts for students Basic Java script handouts for students
Basic Java script handouts for students
 
Frontend Monoliths: Run if you can!
Frontend Monoliths: Run if you can!Frontend Monoliths: Run if you can!
Frontend Monoliths: Run if you can!
 
“Micro Frontends”- You Keep Using That Word, I Don’t Think It Means What You ...
“Micro Frontends”- You Keep Using That Word, I Don’t Think It Means What You ...“Micro Frontends”- You Keep Using That Word, I Don’t Think It Means What You ...
“Micro Frontends”- You Keep Using That Word, I Don’t Think It Means What You ...
 
Refactoring to a Single Page Application
Refactoring to a Single Page ApplicationRefactoring to a Single Page Application
Refactoring to a Single Page Application
 
Overview of React.JS - Internship Presentation - Week 5
Overview of React.JS - Internship Presentation - Week 5Overview of React.JS - Internship Presentation - Week 5
Overview of React.JS - Internship Presentation - Week 5
 
Angular 2 Seminar_(December 7/12/2015)
Angular 2 Seminar_(December 7/12/2015)Angular 2 Seminar_(December 7/12/2015)
Angular 2 Seminar_(December 7/12/2015)
 
Top java script frameworks ppt
Top java script frameworks pptTop java script frameworks ppt
Top java script frameworks ppt
 
Mvc Training
Mvc TrainingMvc Training
Mvc Training
 
Single Page Application (SPA) using AngularJS
Single Page Application (SPA) using AngularJSSingle Page Application (SPA) using AngularJS
Single Page Application (SPA) using AngularJS
 
MTaulty_DevWeek_Silverlight
MTaulty_DevWeek_SilverlightMTaulty_DevWeek_Silverlight
MTaulty_DevWeek_Silverlight
 
Angular 2 - Better or worse
Angular 2 - Better or worseAngular 2 - Better or worse
Angular 2 - Better or worse
 
MVVM+MEF in Silvelight - W 2010ebday
MVVM+MEF in Silvelight - W 2010ebdayMVVM+MEF in Silvelight - W 2010ebday
MVVM+MEF in Silvelight - W 2010ebday
 
Angular
AngularAngular
Angular
 
The Ultimate Getting Started with Angular Workshop - Devoxx UK 2017
The Ultimate Getting Started with Angular Workshop - Devoxx UK 2017The Ultimate Getting Started with Angular Workshop - Devoxx UK 2017
The Ultimate Getting Started with Angular Workshop - Devoxx UK 2017
 
ASP Dot Net Software Development in India - iFour Technolab
ASP Dot Net Software Development in India - iFour TechnolabASP Dot Net Software Development in India - iFour Technolab
ASP Dot Net Software Development in India - iFour Technolab
 
Web Development Presentation
Web Development PresentationWeb Development Presentation
Web Development Presentation
 
Building Cross Platform Mobile Apps
Building Cross Platform Mobile AppsBuilding Cross Platform Mobile Apps
Building Cross Platform Mobile Apps
 
Latest Javascript MVC & Front End Frameworks 2017
Latest Javascript MVC & Front End Frameworks 2017Latest Javascript MVC & Front End Frameworks 2017
Latest Javascript MVC & Front End Frameworks 2017
 
PLASTIC 2011: "Enterprise JavaScript with Jangaroo"
PLASTIC 2011: "Enterprise JavaScript with Jangaroo"PLASTIC 2011: "Enterprise JavaScript with Jangaroo"
PLASTIC 2011: "Enterprise JavaScript with Jangaroo"
 

Andere mochten auch

Component Based UI Architectures for the Web
Component Based UI Architectures for the WebComponent Based UI Architectures for the Web
Component Based UI Architectures for the WebAndrew Rota
 
Continuous Security: Zap security bugs now Codemotion-2015
Continuous Security: Zap security bugs now Codemotion-2015Continuous Security: Zap security bugs now Codemotion-2015
Continuous Security: Zap security bugs now Codemotion-2015Carlo Bonamico
 
Is my Web Application secure? OWASP Top Ten Security Risks and Beyond...
Is my Web Application secure? OWASP Top Ten Security Risks and Beyond...Is my Web Application secure? OWASP Top Ten Security Risks and Beyond...
Is my Web Application secure? OWASP Top Ten Security Risks and Beyond...Carlo Bonamico
 
codemotion-docker-2014
codemotion-docker-2014codemotion-docker-2014
codemotion-docker-2014Carlo Bonamico
 
Angular 1.x reloaded: improve your app now! and get ready for 2.0
Angular 1.x reloaded:  improve your app now! and get ready for 2.0Angular 1.x reloaded:  improve your app now! and get ready for 2.0
Angular 1.x reloaded: improve your app now! and get ready for 2.0Carlo Bonamico
 
SOA, DDD e microservices
SOA, DDD e microservicesSOA, DDD e microservices
SOA, DDD e microservicesMauro Servienti
 
Single Sign On con IdentityServer
Single Sign On con IdentityServerSingle Sign On con IdentityServer
Single Sign On con IdentityServerMauro Servienti
 
Progressive web apps with Angular 2
Progressive web apps with Angular 2Progressive web apps with Angular 2
Progressive web apps with Angular 2Manfred Steyer
 
Approccio prestazionale antincendio nelle caserme
Approccio prestazionale antincendio nelle casermeApproccio prestazionale antincendio nelle caserme
Approccio prestazionale antincendio nelle casermeMarcello Mangione
 
Angular 2 for Java Developers
Angular 2 for Java DevelopersAngular 2 for Java Developers
Angular 2 for Java DevelopersYakov Fain
 
Maven 2 in the real world
Maven 2 in the real worldMaven 2 in the real world
Maven 2 in the real worldCarlo Bonamico
 

Andere mochten auch (12)

Component Based UI Architectures for the Web
Component Based UI Architectures for the WebComponent Based UI Architectures for the Web
Component Based UI Architectures for the Web
 
Continuous Security: Zap security bugs now Codemotion-2015
Continuous Security: Zap security bugs now Codemotion-2015Continuous Security: Zap security bugs now Codemotion-2015
Continuous Security: Zap security bugs now Codemotion-2015
 
Is my Web Application secure? OWASP Top Ten Security Risks and Beyond...
Is my Web Application secure? OWASP Top Ten Security Risks and Beyond...Is my Web Application secure? OWASP Top Ten Security Risks and Beyond...
Is my Web Application secure? OWASP Top Ten Security Risks and Beyond...
 
Pub/Sub Basics
Pub/Sub BasicsPub/Sub Basics
Pub/Sub Basics
 
codemotion-docker-2014
codemotion-docker-2014codemotion-docker-2014
codemotion-docker-2014
 
Angular 1.x reloaded: improve your app now! and get ready for 2.0
Angular 1.x reloaded:  improve your app now! and get ready for 2.0Angular 1.x reloaded:  improve your app now! and get ready for 2.0
Angular 1.x reloaded: improve your app now! and get ready for 2.0
 
SOA, DDD e microservices
SOA, DDD e microservicesSOA, DDD e microservices
SOA, DDD e microservices
 
Single Sign On con IdentityServer
Single Sign On con IdentityServerSingle Sign On con IdentityServer
Single Sign On con IdentityServer
 
Progressive web apps with Angular 2
Progressive web apps with Angular 2Progressive web apps with Angular 2
Progressive web apps with Angular 2
 
Approccio prestazionale antincendio nelle caserme
Approccio prestazionale antincendio nelle casermeApproccio prestazionale antincendio nelle caserme
Approccio prestazionale antincendio nelle caserme
 
Angular 2 for Java Developers
Angular 2 for Java DevelopersAngular 2 for Java Developers
Angular 2 for Java Developers
 
Maven 2 in the real world
Maven 2 in the real worldMaven 2 in the real world
Maven 2 in the real world
 

Ähnlich wie Angular Rebooted: Components Everywhere

Carlo Bonamico, Sonia Pini - So you want to build your (Angular) Component Li...
Carlo Bonamico, Sonia Pini - So you want to build your (Angular) Component Li...Carlo Bonamico, Sonia Pini - So you want to build your (Angular) Component Li...
Carlo Bonamico, Sonia Pini - So you want to build your (Angular) Component Li...Codemotion
 
Build Your Own Angular Component Library
Build Your Own Angular Component LibraryBuild Your Own Angular Component Library
Build Your Own Angular Component LibraryCarlo Bonamico
 
Nicholas Gustilo "Clean Android: building great mobile apps"
Nicholas Gustilo "Clean Android: building great mobile apps"Nicholas Gustilo "Clean Android: building great mobile apps"
Nicholas Gustilo "Clean Android: building great mobile apps"IT Event
 
Think components. March 2017
Think components. March 2017Think components. March 2017
Think components. March 2017Ivan Babak
 
AngularJS in Production (CTO Forum)
AngularJS in Production (CTO Forum)AngularJS in Production (CTO Forum)
AngularJS in Production (CTO Forum)Alex Ross
 
Fighting legacy with hexagonal architecture and frameworkless php
Fighting legacy with hexagonal architecture and frameworkless phpFighting legacy with hexagonal architecture and frameworkless php
Fighting legacy with hexagonal architecture and frameworkless phpFabio Pellegrini
 
Top 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular AppTop 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular AppKaty Slemon
 
Single Responsibility Principle
Single Responsibility PrincipleSingle Responsibility Principle
Single Responsibility PrincipleBADR
 
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...Luis Valencia
 
Angular interview questions
Angular interview questionsAngular interview questions
Angular interview questionsGoa App
 
DOC-20210303-WA0017..pptx,coding stuff in c
DOC-20210303-WA0017..pptx,coding stuff in cDOC-20210303-WA0017..pptx,coding stuff in c
DOC-20210303-WA0017..pptx,coding stuff in cfloraaluoch3
 
Angular2 with type script
Angular2 with type scriptAngular2 with type script
Angular2 with type scriptRavi Mone
 
Foster - Getting started with Angular
Foster - Getting started with AngularFoster - Getting started with Angular
Foster - Getting started with AngularMukundSonaiya1
 
Angular js 1.3 presentation for fed nov 2014
Angular js 1.3 presentation for fed   nov 2014Angular js 1.3 presentation for fed   nov 2014
Angular js 1.3 presentation for fed nov 2014Sarah Hudson
 
Data Sharing Between Child and Parent Components in AngularJS
Data Sharing Between Child and Parent Components in AngularJSData Sharing Between Child and Parent Components in AngularJS
Data Sharing Between Child and Parent Components in AngularJSFibonalabs
 
Design concepts and principles
Design concepts and principlesDesign concepts and principles
Design concepts and principlessaurabhshertukde
 

Ähnlich wie Angular Rebooted: Components Everywhere (20)

Carlo Bonamico, Sonia Pini - So you want to build your (Angular) Component Li...
Carlo Bonamico, Sonia Pini - So you want to build your (Angular) Component Li...Carlo Bonamico, Sonia Pini - So you want to build your (Angular) Component Li...
Carlo Bonamico, Sonia Pini - So you want to build your (Angular) Component Li...
 
Build Your Own Angular Component Library
Build Your Own Angular Component LibraryBuild Your Own Angular Component Library
Build Your Own Angular Component Library
 
Nicholas Gustilo "Clean Android: building great mobile apps"
Nicholas Gustilo "Clean Android: building great mobile apps"Nicholas Gustilo "Clean Android: building great mobile apps"
Nicholas Gustilo "Clean Android: building great mobile apps"
 
Think components. March 2017
Think components. March 2017Think components. March 2017
Think components. March 2017
 
AngularJS in Production (CTO Forum)
AngularJS in Production (CTO Forum)AngularJS in Production (CTO Forum)
AngularJS in Production (CTO Forum)
 
Fighting legacy with hexagonal architecture and frameworkless php
Fighting legacy with hexagonal architecture and frameworkless phpFighting legacy with hexagonal architecture and frameworkless php
Fighting legacy with hexagonal architecture and frameworkless php
 
How Does Angular Work?
How Does Angular Work?How Does Angular Work?
How Does Angular Work?
 
Top 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular AppTop 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular App
 
Creating a SPA blog withAngular and Cloud Firestore
Creating a SPA blog withAngular and Cloud FirestoreCreating a SPA blog withAngular and Cloud Firestore
Creating a SPA blog withAngular and Cloud Firestore
 
Single Responsibility Principle
Single Responsibility PrincipleSingle Responsibility Principle
Single Responsibility Principle
 
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
 
Angular interview questions
Angular interview questionsAngular interview questions
Angular interview questions
 
DOC-20210303-WA0017..pptx,coding stuff in c
DOC-20210303-WA0017..pptx,coding stuff in cDOC-20210303-WA0017..pptx,coding stuff in c
DOC-20210303-WA0017..pptx,coding stuff in c
 
Angular2 with type script
Angular2 with type scriptAngular2 with type script
Angular2 with type script
 
DDD with Behat
DDD with BehatDDD with Behat
DDD with Behat
 
Foster - Getting started with Angular
Foster - Getting started with AngularFoster - Getting started with Angular
Foster - Getting started with Angular
 
Angular js 1.3 presentation for fed nov 2014
Angular js 1.3 presentation for fed   nov 2014Angular js 1.3 presentation for fed   nov 2014
Angular js 1.3 presentation for fed nov 2014
 
Data Sharing Between Child and Parent Components in AngularJS
Data Sharing Between Child and Parent Components in AngularJSData Sharing Between Child and Parent Components in AngularJS
Data Sharing Between Child and Parent Components in AngularJS
 
AngularJS best practices
AngularJS best practicesAngularJS best practices
AngularJS best practices
 
Design concepts and principles
Design concepts and principlesDesign concepts and principles
Design concepts and principles
 

Mehr von Carlo Bonamico

Real World AngularJS recipes: beyond TodoMVC
Real World AngularJS recipes: beyond TodoMVCReal World AngularJS recipes: beyond TodoMVC
Real World AngularJS recipes: beyond TodoMVCCarlo Bonamico
 
Infrastructure as Data with Ansible for easier Continuous Delivery
Infrastructure as Data with Ansible for easier Continuous DeliveryInfrastructure as Data with Ansible for easier Continuous Delivery
Infrastructure as Data with Ansible for easier Continuous DeliveryCarlo Bonamico
 
Infrastructure as Data with Ansible
Infrastructure as Data with AnsibleInfrastructure as Data with Ansible
Infrastructure as Data with AnsibleCarlo Bonamico
 
Nasa World Wind For Java (by Fabrizio Giudici)
Nasa World Wind For Java (by Fabrizio Giudici)Nasa World Wind For Java (by Fabrizio Giudici)
Nasa World Wind For Java (by Fabrizio Giudici)Carlo Bonamico
 
Continuous Integration With Hudson (and Jenkins)
Continuous Integration With Hudson (and Jenkins)Continuous Integration With Hudson (and Jenkins)
Continuous Integration With Hudson (and Jenkins)Carlo Bonamico
 

Mehr von Carlo Bonamico (6)

Real World AngularJS recipes: beyond TodoMVC
Real World AngularJS recipes: beyond TodoMVCReal World AngularJS recipes: beyond TodoMVC
Real World AngularJS recipes: beyond TodoMVC
 
Infrastructure as Data with Ansible for easier Continuous Delivery
Infrastructure as Data with Ansible for easier Continuous DeliveryInfrastructure as Data with Ansible for easier Continuous Delivery
Infrastructure as Data with Ansible for easier Continuous Delivery
 
Infrastructure as Data with Ansible
Infrastructure as Data with AnsibleInfrastructure as Data with Ansible
Infrastructure as Data with Ansible
 
Nasa World Wind For Java (by Fabrizio Giudici)
Nasa World Wind For Java (by Fabrizio Giudici)Nasa World Wind For Java (by Fabrizio Giudici)
Nasa World Wind For Java (by Fabrizio Giudici)
 
Continuous Integration With Hudson (and Jenkins)
Continuous Integration With Hudson (and Jenkins)Continuous Integration With Hudson (and Jenkins)
Continuous Integration With Hudson (and Jenkins)
 
Build Automation Tips
Build Automation TipsBuild Automation Tips
Build Automation Tips
 

Kürzlich hochgeladen

The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 

Kürzlich hochgeladen (20)

The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 

Angular Rebooted: Components Everywhere

  • 1. Angular Rebooted: Components Everywhere Carlo Bonamico -Sonia Pini MILAN 25-26 NOVEMBER 2016 sonia.pini@nispro.it carlo.bonamico@nispro.it - NIS s.r.l. - a DGS company carlo.bonamico@gmail.com – Genova Java User Group Twitter: @carlobonamico @nis_srl
  • 2. Abstract Attracted by AngularJS power and simplicity, you have chosen it for your next project. Getting started with DataBinding, Scopes and Controllers was relatively quick and easy... But what do you need to effectively bring a complex application to Production? We discuss ● the new Component API, ● lifecycle callbacks - $onChanges ● selecting different ways for components to collaborate ● choosing between Two-Way Binding and One-Way Data Flow, ● "smart" vs "dumb" components, We ‘ll share recipes from our real world experience so that you can productively & reliably build a complex application out of reusable Components.
  • 3. We all love AngularJs ● Simple & Powerful ○ Two way data binding is legendary ○ Dependency Injection is awesome ○ Routing is very flexible ○ D.R.Y and reusable code made easy ○ Components/Directives FTW ○ Modular and component-driven … ○ Testable code We all love AngularJs
  • 4. Real world apps are not easy Bringing a complex application to production requires more than quickly bind form fields: ● decoupling unrelated parts ● preventing fragility in the face of changes ● keeping collaboration effective as team grows ● avoiding performance issues Angular gives us good tools - but we need to use them in the right way
  • 5. Avoiding bad practices Often, as the application starts to grow, we see ● single large controller and HTML file per view ○ thousands of lines each ● significant repetition across views ○ same HTML fragments in many files ● “Spaghetti Binding” ○ creates dependencies between unrelated parts Code becomes hard to navigate / risky to change We need Software Engineering for the Frontend, too
  • 7. What is a Component? ● Self-contained set of UI and logic ○ encapsulates a specific behaviour ○ provides an explicit API ● Since Angular 1.5, special kind of Directive with ○ UI in a template ○ Logic in a controller ○ some metadata (inputs, outputs, …) ● Makes it easier/cheaper to do a good design ○ pushing the community towards best practices ● In Angular 2, the main application construct
  • 8. Most of the concepts that we present apply to both Angular 1.5 & Angular 2.0 although syntax is different
  • 9. Example App: NG Component Mail Full Source in https://github.com/carlobonamico/angular-component-based
  • 10. Thinking in Components <message-list> <folder-list > <nav-actions> <message-viewer> <search-panel> <folder-list > <message-actions>
  • 11. Design the Component API Define input and output properties ● Keep naming conventions consistent ● Follow Clean Code guidelines <component> inputs outputs
  • 12. <folder-list> API and behavior input → folder array, title, allowCreate output → selected folder encapsulated state and behaviour → current folder, select with click, sorting, filtering
  • 13. ● = → two-way binding ● < → one-way binding ● @ → input string ● ? → optional <folder-list> - Declaring Inputs
  • 15. Passing Inputs to <folder-list> FolderList Component
  • 16. Why didn’t we use “=”? The “=” qualifier means that the binding is two-way ● the <folder-list> component could even replace the folder array with another one ○ while it’s role is just to display it ● and this change could also immediately affect various other parts of the page which reference the folder array in their {{}} expressions and $watch-es Guideline: default to “<” for component inputs ● one-way change propagation
  • 17. Two-way bindings pros and cons ● Very effective collaboration “in the small” ○ like when all people in a room can talk to each other to solve a problem ○ ng-model for bi-directional updates between form inputs and model ○ a validation expression can reference several model variables ● creates chaos “in the large” ○ think all people in the building talking to any one else
  • 18. How to handle <folder-list> Output? Passing the selected folder to the MailController which updates the message list - ideas? ● Option 1 ■ $scope.$parent.currentFolder = selectedFolder ○ avoid! it makes the component non-reusable ● Option 2 - two-way binding ■ binding selectedFolder : “=” ■ <folder-list selected-folder=”mailCtrl.currentFolder”> ■ in the parent, $watch(‘currentFolder’, function(){ loadMessages(currentFolder)})
  • 19. Making Outputs explicit with Events Option 3 - The component ● detects when a significant user action takes place ● updates its internal state ○ e.g. track the selected folder ● updates its view ○ display the element in bold / red ● sends an event to notify the parent component ○ including relevant data (e.g. folder id / name) ● lets the parent component decide what to do then ○ e.g. retrieving a new message list
  • 20. Sending the event in <folder-list> ● We declare an output binding with “&” ● Angular injects an emitter function in the controller ● We call it passing an Event Object including relevant data MailController <folder-list> component
  • 21. Using the component output Specify an expression to be executed in the parent scope when the event is received Parent Component Controller FolderListController mail-view HTML
  • 22. Advantages Stonger Encapsulation (isolated scope + explicit binding) ● changing the component internal implementation has less impact on the rest of the application ● more decoupling, less regressions Reusability (with parametrization) ● same component used in different contexts ○ <message-list> can display either folder messages and search results
  • 23. Advantages Better Collaboration ● less conflicts when team grows ● easier to test for regressions More Clarity and Readability ● I can effectively use a component knowing only its API (the bindings section) ● the link to other component is very clear and explict in the HTML
  • 24. Components all the way down What happens if we consistently apply this pattern across the entire application? The application becomes...
  • 25. A tree of collaborating Components <mail-view> <folder-list> <message-list> <nav-actions><common-star> <message-view> <common-star>
  • 26. Types of Components <mail-view> <folder-list> <message-list> <nav-actions><common-star> <message-view> <common-star> more application - specific more generic/reusable
  • 27. Types of Components <mail-view> <folder-list> <message-list> <nav-actions><common-star> <message-view> <common-star> “Smart” components “Dumb” components Services / $http
  • 28. Components: Smart vs Dumb ● Also called stateful ● Provides data - e.g. from http REST clients ● May receive initial data via route resolves ● Has knowledge of the current state ● Is informed by stateless components when something needs to change ● Also called stateless ● Like a pure JavaScript function ● It receives data via property binding ● it focuses on rendering and interaction without managing business logic ● It requests state changes through explicit events
  • 29. Data Flow “down”: property binding Component pass a subset of their model to children <mail-view> <folder-list> <message-list> <nav-actions><common-star> <message-view> <common-star> folders messages currentMessage
  • 30. Data Flow “up”: events & callbacks Component pass relevant events/changes to parent <mail-view> <folder-list> <message-list> <nav-actions><common-star> <message-view> <common-star> onSelected() onCurrentMsg() onStar() onReply() onNext()
  • 31. Component Interaction Complex behaviour achieved through collaboration <mail-view> <folder-list> <message-list> <message-view> onSelected()
  • 32. Component Interaction Complex behaviour achieved through collaboration <mail-view> <folder-list> <message-list> <message-view> messages
  • 33. Component Interaction Complex behaviour achieved through collaboration <mail-view> <folder-list> <message-list> <message-view> onSelected() onCurrentMsg()messages currentMessage
  • 34. Advantages If a component passes data to its children, that it knows well, the risk of unintended side effects is low If a component notifies its parent, the change can potentially affect unrelated / not yet developed parts ● more explicit and controlled ● parent component can mediate and orchestrate how the child interacts with the rest Also, the tree is very good for performance
  • 35. Component means Composable What is the right size of a component?
  • 36. Component means Composable There is no “right answer”, but... ● if a component becomes too big, split it into collaborating child components Basic Design Principles ●Low Coupling - avoid unneeded dependencies ●High Cohesion - Single Responsibility Principle (SOLID Principle) − separate things that change for different reasons or at different times In short: don’t put your socks in the fridge...
  • 37. Single Responsibility applied If you need to do 2 things, make 3 components ● A, B ● C that does A + B Example ● <upload-attachment> does file browsing and calls the UploadService HTTP client ● <attachment-list> displays the currently attached messages ● <mail-attachments> groups the first two
  • 38. More Component goodies ● Since Angular 1.5.3, Components can declare "lifecycle hooks" ● $onInit() ○ one-time initialization after interconnected components have been bound ○ https://toddmotto.com/on-init-require-object-syntax-angular -component ● $onDestroy() ○ deallocate resources when the component is removed from the view ○ e.g. a websocket in a chat
  • 39. Change notification ● $onChanges ○ Called when “<” / input bindings are updated ○ parameter: a changes object including ■ keys for each changed property ■ previousValue and currentValue ● Very effective for ○ compute derived values ■ compute unread messages count ○ apply filtering or sorting to data ■ display various sets of messages according to a choice http://blog.thoughtram.io/angularjs/2016/03/29/exploring-angular-1.5-lifecycle-hooks.html
  • 41. Test a Component Controller Pass inputs to the controller and test its behaviour ngMock module has been updated with the $componentController method
  • 42. Test a Component we can compile the element and test ● that it renders what we expected ● that it correctly reacts to user events
  • 43. What happens in Angular 2?
  • 44. Components in Angular 2 Syntax, some costructs change, but Component-based Architecture is even stronger ● no more stand-alone controllers ● even application home, first-level views become components ○ component-based routing ● component metadata + Typescript allow for ○ better tooling support ○ completion, validation ○ more explicit API definition
  • 47. References on Components Angular 1.5 Components reference https://docs.angularjs.org/guide/component Exploring Angular 1.5 Components https://toddmotto.com/exploring-the-angular-1-5-component-meth od/ Refactoring an 1.5 application to Components https://teropa.info/blog/2015/10/18/refactoring-angular-apps-to-co mponents.html Components in Angular 2 https://angular.io/docs/ts/latest/cookbook/component-communicat ion.html
  • 48. Thank you! ● Other presentations − http://www.slideshare.net/carlo.bonamico/presentations ● Follow us on Twitter − @carlobonamico @nis_srl ● updates on AngularJS! ● and some Security, Ansible, Continuous Delivery ● Contact us − carlo.bonamico@gmail.com / carlo.bonamico@nispro.it − Sonia.pini@nispro.it ● Our company − http://www.nispro.it