Anda di halaman 1dari 6

11/28/2015

Angular 1 and Angular 2 integration: the path to seamless upgrade

25th August Angular 1 and Angular 2 integration: the path to seamless


upgrade
HaveanexistingAngular1applicationandarewonderingaboutupgradingtoAngular2?Well,readonand
learnaboutourplanstosupportincrementalupgrades.

Summary
Goodnews!
We'reenablingmixingofAngular1andAngular2inthesameapplication.
YoucanmixAngular1andAngular2componentsinthesameview.
Angular1andAngular2caninjectservicesacrossframeworks.
Databindingworksacrossframeworks.

WhyUpgrade?
Angular2providesmanybenefitsoverAngular1includingdramaticallybetterperformance,morepowerful
templating,lazyloading,simplerAPIs,easierdebugging,evenmoretestableandmuchmore.Hereareafewof
thehighlights:

Betterperformance
We'vefocusedacrossmanyscenariostomakeyourappssnappy.3xto5xfasteroninitialrenderandrerender
scenarios.
FasterchangedetectionthroughmonomorphicJScalls
Templateprecompilationandreuse
Viewcaching
Lowermemoryusage/VMpressure
Linear(blindinglyfast)scalabilitywithobservableorimmutabledatastructures
Dependencyinjectionsupportsincrementalloading

Morepowerfultemplating
Removesneedformanydirectives
StaticallyanalyzablefuturetoolsandIDEscandiscovererrorsatdevelopmenttimeinsteadofruntime
Allowstemplatewriterstodeterminebindingusageratherthanhardwiringinthedirectivedefinition

Futurework
We'vedecoupledAngular2'srenderingfromtheDOM.Weareactivelyworkingonsupportingthefollowing
othercapabilitiesthatthisdecouplingenables:
Serversiderendering.Enablessuperfastinitialrenderandwebcrawlersupport.
WebWorkers.MoveyourappandmostofAngulartoaWebWorkerthreadtokeeptheUIsmoothand
responsiveatalltimes.
NativemobileUI.We'reenthusiasticaboutsupportingtheWebPlatforminmobileapps.Atthesametime,
someteamswanttodeliverfullynativeUIsontheiriOSandAndroidmobileapps.
Compileasbuildstep.AngularappsparseandcompiletheirHTMLtemplates.We'reworkingtospeed
upinitialrenderingbymovingthecompilestepintoyourbuildprocess.
http://angularjs.blogspot.cl/2015/08/angular-1-and-angular-2-coexistence.html

1/6

11/28/2015

Angular 1 and Angular 2 integration: the path to seamless upgrade

Angular1and2runningtogether
Angular2offersdramaticadvantagesoverAngular1inperformance,simplicity,andflexibility.We'remakingit
easyforyoutotakeadvantageofthesebenefitsinyourexistingAngular1applicationsbylettingyou
seamlesslymixincomponentsandservicesfromAngular2intoasingleapp.Bydoingso,you'llbeableto
upgradeanapplicationoneserviceorcomponentatatimeovermanysmallcommits.
Forexample,youmayhaveanappthatlookssomethinglikethediagrambelow.Togetyourfeetwetwith
Angular2,youdecidetoupgradetheleftnavtoanAngular2component.Onceyou'remoreconfident,you
decidetotakeadvantageofAngular2'srenderingspeedforthescrollingareainyourmaincontentarea.

[http://2.bp.blogspot.com/-fHqaW0OSpkc/VdyH89acxDI/AAAAAAAB0Ik/cfoXHUMDa14/s1600/Screen%2BShot%2B2015-0825%2Bat%2B8.20.05%2BAM.png]

Forthistowork,fourthingsneedtointeroperatebetweenAngular1andAngular2:
Dependencyinjection
Componentnesting
Transclusion
http://angularjs.blogspot.cl/2015/08/angular-1-and-angular-2-coexistence.html

2/6

11/28/2015

Angular 1 and Angular 2 integration: the path to seamless upgrade

Changedetection
Tomakeallthispossible,we'rebuildingalibrarynamedngupgrade.You'llincludengupgradeandAngular2
inyourexistingAngular1app,andyou'llbeabletomixandmatchatwill.
Youcanfindfulldetailsandpseudocodeintheoriginalupgrade design doc
[https://docs.google.com/document/d/1xvBZoFuNq9hsgRhPPZOJC-Z48AHEbIBPlOCBTSD8m0Y] orreadonforan

overviewofthedetailsonhowthisworks.Infutureposts,we'llwalkthroughspecificexamplesofupgrading
Angular1codetoAngular2.

DependencyInjection
First,weneedtosolveforcommunicationbetweenpartsofyourapplication.InAngular,themostcommon
patternforcallinganotherclassorfunctionisthroughdependencyinjection.Angular1hasasinglerootinjector,
whileAngular2hasahierarchical injector [http://victorsavkin.com/post/126514197956/dependency-injection-in-angular-1and-angular-2] .Upgradingservicesoneatatimeimpliesthatthetwoinjectorsneedtobeabletoprovide
instancesfromeachother.
ThengupgradelibrarywillautomaticallymakealloftheAngular1injectablesavailableinAngular2.This
meansthatyourAngular1applicationservicescannowbeinjectedanywhereinAngular2componentsor
services.
ExposinganAngular2serviceintoanAngular1injectorwillalsobesupported,butwillrequirethatyouto
provideasimplemappingconfiguration.
TheresultisthatservicescanbeeasilymovedoneatatimefromAngular1toAngular2overindependent
commitsandcommunicateinamixedenvironment.

ComponentNestingandTransclusion
InbothversionsofAngular,wedefineacomponentasadirectivewhichhasitsowntemplate.Forincremental
migration,you'llneedtobeabletomigratethesecomponentsoneatatime.Thismeansthatngupgradeneeds
toenablecomponentsfromeachframeworktonestwithineachother.
Tosolvethis,ngupgradewillallowyoutowrapAngular1componentsinafacadesothattheycanbeusedin
anAngular2component.Conversely,youcanwrapAngular2componentstobeusedinAngular1.Thiswill
fullyworkwithtransclusioninAngular1anditsanalogofcontentprojectioninAngular2.
Inthisnestedcomponentworld,eachtemplateisfullyownedbyeitherAngular1orAngular2andwillfully
followitssyntaxandsemantics.Thisisnotanemulationmodewhichmostlylooksliketheother,butanactual
executionineachframework,dependendingonthetypeofcomponent.Thismeansthatcomponentswhichare
upgradedtoAngular2willgetallofthebenefitsofAngular2,andnotjustbettersyntax.
ThisalsomeansthatanAngular1componentwillalwaysuseAngular1DependencyInjection,evenwhenused
inanAngular2template,andanAngular2componentwillalwaysuseAngular2DependencyInjection,even
whenusedinanAngular1template.

ChangeDetection
MixingAngular1andAngular2componentsimpliesthatAngular1scopesandAngular2componentsare
http://angularjs.blogspot.cl/2015/08/angular-1-and-angular-2-coexistence.html

3/6

11/28/2015

Angular 1 and Angular 2 integration: the path to seamless upgrade

interleaved.Forthisreason,ngupgradewillmakesurethatthechangedetection(ScopedigestinAngular1
andChangeDetectorsinAngular2)areinterleavedinthesamewaytomaintainapredictableevaluationorder
ofexpressions.
ngupgradetakesthisintoaccountandbridgesthescopedigestfromAngular1andchangedetectionin
Angular2inawaythatcreatesasinglecohesivedigestcyclespanningbothframeworks.

Typicalapplicationupgradeprocess
HereisanexampleofwhatanAngular1projectupgradetoAngular2maylooklike.
1. IncludetheAngular2andngupgradelibrarieswithyourexistingapplication
2. Pickacomponentwhichyouwouldliketomigrate
a.EditanAngular1directive'stemplatetoconformtoAngular2syntax
b.Convertthedirective'scontroller/linkingfunctionintoAngular2syntax/semantics
c.Usengupgradetoexportthedirective(nowaComponent)asanAngular1component(thisisneededif
youwishtocallthenewAngular2componentfromanAngular1template)
3. Pickaservicewhichyouwouldwouldliketomigrate
a.Mostservicesshouldrequireminimaltonochange.
b.ConfiguretheserviceinAngular2
c.(optionally)reexporttheserviceintoAngular1usingngupgradeifit'sstillusedbyotherpartsofyour
Angular1code.
4. Repeatdoingstep#2and#3inanorderconvenientforyourapplicationdevelopmen
5. Oncenomoreservices/componentsneedtobeconverteddropthetoplevelAngular1bootstrapand
replacewithAngular2bootstrap.
Notethateachindividualchangecanbecheckedinseparatelyandtheapplicationcontinuesworkinglettingyou
continuetoreleaseupdatesasyouwish.
Wearenotplanningonaddingsupportforallowingnoncomponentdirectivestobeusableonbothsides.We
thinkmostofthenoncomponentdirectivesarenotneededinAngular2astheyaresupporteddirectlybythe
newtemplatesyntax(i.e.ngclickvs(click))

Q&A
IheardAngular2doesn'tsupport2waybindings.HowwillIreplacethem?
Actually,Angular2supportstwowaydatabindingandngmodel,thoughwithslightlydifferentsyntax.
WhenwesetouttobuildAngular2wewantedtofixissueswiththeAngulardigestcycle.Tosolvethiswechose
tocreateaunidirectionaldataflowforchangedetection.Atfirstitwasnotcleartoushowthetwowayforms
databindingofngmodelinAngular1fitsin,butwealwaysknewthatwehadtomakeformsinAngular2as
simpleasformsinAngular1.
Afterafewiterationswemanagedtofixwhatwasbrokenwithmultipledigestsandstillretainthepowerand
simplicityofngmodelinAngular1.
Twowaydatabindinghasanewsyntax:[(propertyname)]="expression"tomakeitexplicitthattheexpression
isboundinbothdirections.Becauseformostscenariosthisisjustasmallsyntacticchangeweexpecteasy
migration.
http://angularjs.blogspot.cl/2015/08/angular-1-and-angular-2-coexistence.html

4/6

11/28/2015

Angular 1 and Angular 2 integration: the path to seamless upgrade

Asanexample,ifinAngular1youhave:
<inputtype="text"ngmodel="model.name"/>
YouwouldconverttothisinAngular2:
<inputtype="text"[(ngmodel)]="model.name"/>
WhatlanguagescanIusewithAngular2?
Angular2APIsfullysupportcodingintoday'sJavaScript(ES5),thenextversionofJavaScript(ES6orES2015),
TypeScript,andDart.
Whileit'saperfectlyfinechoicetocontinuewithtoday'sJavaScript,we'dliketosuggestthatyouexploreES6
andTypeScript(whichisasupersetofES6)astheyprovidedramaticimprovementstoyourproductivity.
ES6providesmuchimprovedsyntaxandstandardsforcommonlibrarieslikepromisesandmodules.
TypeScriptgivesyoudramaticallybettercodenavigation,automatedrefactoringinIDEs,documentation,finding
errors,andmore.
BothES6andTypeScriptareeasytoadoptastheyaresupersetsoftoday'sES5.Thismeansthatallyour
existingcodeisvalidandyoucanaddtheirfeaturesalittleatatime.
WhatshouldIdowith$watchinourcodebase?
Inordertogainspeedandpredictability,inAngular2youspecifywatchexpressionsdeclarativelyintheHTML
templateorinannotationsonyourcomponentdirectives.OneadditionalbenefitfromthisisthatAngular2
applicationscanbesafelyminified/obfuscatedforsmallerpayload.
Foranyscenariosthatdon'tfitwiththesemechanisms,youcantakeadvantageofobservablesES7
ObservablesasinRx.jsforJavaScriptorStreamsinDart.
WhatcanIdotodaytopreparemyselfforthemigration?
FollowthebestpracticesandbuildyourapplicationusingcomponentsandservicesinAngular1asdescribedin
theAngularJS Style Guide [https://github.com/johnpapa/angular-styleguide] .
Wasn'ttheoriginalupgradeplantousethenewComponentRouter?
Theupgradeplanthatweannouncedatngconf2015wasbasedonupgradingawholeviewatatimeand
havingtheComponentRouterhandlecommunicationbetweenthetwoversionsofAngular.
Thefeedbackwereceivedwasthatwhileyes,thiswasincremental,itwasn'tincrementalenough.Wewent
backandredesignedfortheplanasdescribedabove.
Aretheremoredetailsyoucanshare?
Yes!IntheAngular 1 to Angular 2 Upgrade Strategy
[https://docs.google.com/document/d/1xvBZoFuNq9hsgRhPPZOJC-Z48AHEbIBPlOCBTSD8m0Y] designdoc.

We'reworkingonaseriesofupcomingpostsonrelatedtopicsincluding:
MappingyourAngular1knowledgetoAngular2.
AsetofFAQsondetailsaroundAngular2.
http://angularjs.blogspot.cl/2015/08/angular-1-and-angular-2-coexistence.html

5/6

11/28/2015

Angular 1 and Angular 2 integration: the path to seamless upgrade

Detailedmigrationguidewithworkingcodesamples.
Seeyoubackheresoon!
Posted25thAugustbyBrad Green

Addacomment

Enteryourcomment...

Commentas: angel(Google)

Publish

Preview

http://angularjs.blogspot.cl/2015/08/angular-1-and-angular-2-coexistence.html

Signout

Notifyme

6/6

Anda mungkin juga menyukai