Vous êtes sur la page 1sur 7

10/5/2016

Angular2andTypeScriptAHighLevelOverview

AccordingtoGoogleengineeringdirectorBradGreen,1.3milliondevelopersuseAngularJSand
300thousandarealreadyusingthesoontobereleasedAngular2.AfterworkingwithAngular2
forthelast10monthsIbelieveitsimpactontheJavaScriptcommunitywillrivalthatoftheSpring
frameworkonJava.
InthisarticleIllprovideahighleveloverviewoftheAngular2framework.
Attheendof2014GoogleannouncedthatAngular2wouldbeacompleterewriteofAngularJS,
andtheyevencreatedanewlanguageAtScriptthatwasmeanttobeusedforwritingAngular2
applications.
ButthenMicrosoftagreedtoaddsupportfordecorators(a.k.a.annotations)totheirTypeScript
language(astrictsupersetofJavaScript),andsothatemergedasthelanguageforthe
developmentoftheAngular2frameworkitself,andtherecommendedlanguagefordeveloping
applicationsusingtheAngularJSframework.
YoucanalsodevelopAngular2appsinJavaScript(bothECMAScript5and6)andinDart.
Inaddition,theAngularteamintegratedyetanotherMicrosoftproducttheRxJSlibraryof
reactiveJavaScriptextensions,intotheAngular2framework.
Angular2isnotanMVCframework,butratheracomponentbasedframework.InAngular2an
applicationisatreeoflooselycoupledcomponents.
Forexample,thescreenshotbelowshowsthelandingpageofasampleonlineauctionapplication
thatwasinitiallyprototypedasacollectionofNavbar,Search,Carousel,Product,andFooter
components.

https://www.infoq.com/articles/Angular2TypeScriptHighLevelOverview?utm_campaign=rightbar_v2&utm_source=infoq&utm_medium=articles_link&

1/7

10/5/2016

Angular2andTypeScriptAHighLevelOverview

TheimageaboveillustratesthreeProductcomponentsrendered.Theautomaticrenderingisdone
bybindingthetemplatetothearrayofcomponentsretrievedfromtheserver.Thetitleofeach
productisalinktotheassociatedproductdetailpage.Sincewewanttodesigntheauctionasa
singlepageapplication(SPA),wedontwanttorefreshtheentirepagetodisplayproductdetails.
Letsreusetheareacurrentlyoccupiedbythecarouselandproducts,soitcanalsorenderproduct
detailswhilekeepingtherestofthepageunchanged.Thistaskcanbeaccomplishedinafew
easysteps:
1. UseAngularsrouteroutletdirective,whichallowsyoutodeclaretheareacurrently
occupiedbythecarouselandproductstobe<routeroutlet>sothatitcanvarythe
contentbasedontheusersnavigation.
2. EncapsulateCarouselandProductinsidetheHomecomponent
3. CreateanewProductDetailcomponent
4. ConfiguretheAngularsRoutertoshoweithertheHomeorProductDetailcomponent
inthedesignated<routeroutlet>area.
Wevetalkedalotaboutcomponents,butwehavenotdefinedthem.InTypeScriptacomponentis
simplyaclassannotatedwith@Component:
@Component({
selector:'auctionhome',
template:`
HTMLorothermarkupisinlinedhere
`
})
exportdefaultclassHomeComponent{
//Applicationlogicgoeshere
}
Theannotation@Componentisusedtodefinethecomponentandassociatedmetadata.Inthis
example,thevalueoftheselectorpropertyidentifiesthenameoftheHTMLtagrepresentingthis
component.ThetemplatepropertyisaplaceholderfortheHTML(orother)markup.
Comingbacktoourauctionlandingpage,thetemplateofthetoplevelApplicationComponent
mightlooklikethis:

https://www.infoq.com/articles/Angular2TypeScriptHighLevelOverview?utm_campaign=rightbar_v2&utm_source=infoq&utm_medium=articles_link&

2/7

10/5/2016

Angular2andTypeScriptAHighLevelOverview

ThistemplateconsistsofamixofstandardandcustomHTMLtagsthatrepresentrespective
components.IntheexampleweinlinedtheHTML.Ifweprefertostorethemarkupinaseparate
file(inthiscaseapplication.html),wellwouldusethepropertytemplateURLinsteadoftemplate,
andthecodeoftheApplicationComponentmightlooklikethis:
import{Component}from'angular2/core';
import{Route,RouteConfig,RouterOutlet}from'angular2/router';
importHomeComponentfrom'../home/home';
importNavbarComponentfrom'../navbar/navbar';
importFooterComponentfrom'../footer/footer';
importSearchComponentfrom'../search/search';
importProductDetailComponentfrom"../productdetail/productdetail";
@Component({
selector:'auctionapplication',
templateUrl:'app/components/application/application.html',
directives:[
RouterOutlet,
NavbarComponent,
FooterComponent,
SearchComponent,
HomeComponent
]
})
@RouteConfig([
{path:'/',component:HomeComponent,as:'Home'},
{path:'/products/:id',component:ProductDetailComponent,as:'ProductDetail'
])
exportdefaultclassApplicationComponent{}

TheclassApplicationComponentisannotatedwith@Componentand@RouteConfig(forURL
dependentcontent).ThevalueoftheselectorpropertywillbeusedasauserdefinedHTMLtag
<auctionapplication>.ThetemplateURLspecifiesthelocationofthemarkup.Thesection
directivesincludestheRouterOutletandallchildcomponents.
Theannotation@RouteConfigconfigurestworoutesfortheclientsidenavigation:
ThecontentoftheroutenamedHomewillberenderedbyHomeComponentandmappedtotheURLfragment/.
ThecontentoftheroutenamedProductDetailwillberenderedbyProductDetailComponentandmappedtothe
URLfragment/product:id.
Whentheuserclicksonaparticularproducttitle,thecontentofthedefaultHomeroutewillbe
replacedwiththecontentoftheProductDetailroute,whichprovidesthevalueoftheparameterid
anddisplaystheproductdetailsinthe<routeroutlet>area.Forexample,thelinkfornavigatingto
theProductDetailroute,thattakesproductid1234asaparameter,canlookasfollows:
<a[routerLink]="['/ProductDetail',{'prodId':1234}]">{{product.id}}</a>

DependencyInjection
https://www.infoq.com/articles/Angular2TypeScriptHighLevelOverview?utm_campaign=rightbar_v2&utm_source=infoq&utm_medium=articles_link&

3/7

10/5/2016

Angular2andTypeScriptAHighLevelOverview

Componentsuseservicesforimplementingbusinesslogic.ServicesarejustclassesthatAngular
instantiatesandtheninjectsintocomponents.
exportclassProductService{
products:Product[]=[];
getProducts():Array<Product>{
//Thecodetoretrieveproductintogoeshere
returnproducts;
}
}
NowifyouspecifyanargumentoftypeProductServiceintheHomeComponentconstructor,
Angularwillautomaticallyinstantiateandinjectthatserviceintothecomponent:
@Component{
...
}
exportdefaultclassHomeComponent{
products:Product[]=[];
constructor(productService:ProductService){
this.products=productService.getProducts();
}
}
Angularsdependencyinjectionmoduleisflexible,anditiseasytousebecausetheobjectscan
beinjectedonlyviaconstructors.Injectorsformahierarchy(eachcomponenthasaninjector),and
theinjectableobjectdoesnthavetobeanapplicationlevelsingletonasitmightbydefaultin
Spring.

Intercomponentcommunications
Componentcommunicationcanandshouldbeimplementedinalooselycoupledmanner.A
componentcandeclareinputandoutputproperties.Topassthedatafromaparenttoachild
component,theparentbindsthevaluestotheinputpropertiesofthechild.Thechildhasnoneed
toknowwhoprovidedthevaluesitjustknowswhattodowiththem.
Ifacomponentneedstopassthedatatotheoutsideworld,itemitstheeventsviatheoutput
property.Emitstowhom?Itsnoneofthecomponentsbusiness.Whoeverisinterestedcancreate
alistenertothecustomcomponentsevent.
Thismechanismallowsustotreatcomponentsasblackboxes,thatcangetvaluesinorsenddata
out.Irecentlyrecordedashortvideoyoumightfinduseful,illustratingoneoftheimplementations
oftheMediatordesignpatterninAngular2.

WhyTypeScript
TypeScriptisasupersetofJavaScriptbutlikeJavaitallowsyoutodefinenewtypes.Declaring
variableswithtypesratherthanthegenericvaropensthedoortonewtoolingsupport,whichyou
willfindtobeagreatproductivityenhancer.TypeScriptcomeswithastaticcodeanalyzer,andas
https://www.infoq.com/articles/Angular2TypeScriptHighLevelOverview?utm_campaign=rightbar_v2&utm_source=infoq&utm_medium=articles_link&

4/7

10/5/2016

Angular2andTypeScriptAHighLevelOverview

youentercodeinyourTypeScriptawareIDE(WebStorm/IntelliJIdea,VisualStudioCode,
SublimeText,etc.)youreguidedbycontextsensitivehelpsuggestingtheavailablemethodsinthe
objectortypesofthefunctionargument.Ifyouaccidentallyuseanincorrecttype,theIDEwill
highlighttheerroneouscode.SeehowWebStormsupportsTypeScripthere.
EvenifyourTypeScriptapplicationusesathirdpartylibrarywritteninJavaScript,youcaninstalla
typedefinitionfile(havingtheextension.d.ts),containingtypedeclarationsforthislibrary.Type
declarationsforhundredsofpopularJavaScriptlibrariesarefreelyavailable,andyoucaneasily
installthemwithTypings,aTypeScriptDefinitionManager.ImaginethatyouwanttousejQuery
(writteninJavaScript)fromyourTypeScriptcode.ThetypedefinitionfilesforjQuerywillcontain
declarations(withtypes)ofalljQueryAPIssoyourIDEcanpromptyouwithwhichtypestouse,or
highlightanyerroneouscode.

PerformanceandRendering
RenderingperformanceissubstantiallyimprovedinAngular2.Mostimportantly,thefactthatthe
renderingmoduleislocatedinaseparatemoduleallowsyoutorunthecomputationheavycode
inaworkerthread.VisittheRepaintRateChallengeWebsitetocomparetherendering
performanceofvariousframeworks.Youcanfeelforyourselfthehighspeedofrenderingalarge
datagridwithcontinuouslyupdatingdata.Runthetesttitled"DBMONAngular2.0BetaWeb
Workers"alargedatagridwithconstantdatarefreshes(inaseparatethread)isrepaintedbythe
browserblazinglyfast.
IfyouaskwhatAngular2featuressetitapartfromotherframeworks,firstonmylistwouldbethis
separatemodulefortemplaterenderingandzones:
HavingthecomponentsUIdeclaredinseparatetemplatesprocessedbyanindependentrendereropensup
newopportunitiesinareasfromoptimizationandprecompilationoftemplates,totheabilitytocreatetemplates
forrenderingondifferentdevices.
Themodulezone.jsmonitorsthechangesintheapplicationandmakesdecisionsonwhentoupdatetheUIof
eachcomponent.AnyasynceventtriggerstherevalidationoftheUIineachcomponentanditworksamazingly
fast.
Note:

Whileforthemajorityofapplicationsyouwontneedtoknowtheinternalsofzone.js,ifyourwork
onprojectsrequiringfinetuningUIrenderinginacomplexapplication,youwouldbeservedwell
toallocatesometimetolearnmoreaboutthezoneinnerworkings.

Keepingtherenderingengineinaseparatemoduleallowsthirdpartyvendorstoreplacethe
defaultDOMrendererwithonethattargetsnonbrowserbasedplatforms.Forexample,thisallows
reusingtheapplicationcodeacrossdevices,withtheUIrenderersformobiledevicesthatuse
nativecomponents.ThecodeoftheTypeScriptclassremainsthesame,butthecontentofthe
@ComponentannotationwillcontainXMLoranotherlanguageforrenderingnativecomponents.
AcustomAngular2rendererisalreadyimplementedintheNativeScriptframework,whichserves
asabridgebetweenJavaScriptandnativeiOSandAndroidUIcomponents.WithNativeScript
youcanreusethecomponentscodebyjustreplacingtheHTMLinthetemplatewithXML.
AnothercustomUIrendererallowstouseAngular2withReactNative,whichisanalternativeway
ofcreatingnative(nothybrid)UIsforiOSandAndroid.

Tooling

https://www.infoq.com/articles/Angular2TypeScriptHighLevelOverview?utm_campaign=rightbar_v2&utm_source=infoq&utm_medium=articles_link&

5/7

10/5/2016

Angular2andTypeScriptAHighLevelOverview

WhilethesyntaxandarchitectureofAngular2applicationsisaloteasiertounderstandthan
AngularJS1.X,toolingisabitmorecomplex.Thisisnotsurprisingafterallyouarewritingcodein
onelanguageanddeployingitinanother,becauseeverythingiscompiledtoJavaScript.
AngularCLIisaprojectcurrentlyintheworksthatpromisestoprovideacommandlineinterface
thatwillsubstantiallysimplifyvariousprocesses,frominitialprojectgenerationtoproduction
deployment.
ApplicationdebuggingcanbedoneeitherintheIDEorinthebrowser.WeuseChromeDeveloper
Toolsfordebugging.ThegeneratedsourcemapsallowyoutodebugtheTypeScriptcodewhile
thebrowserrunsJavaScript.IfyouprefertodebugJavaScript,itsalsopossiblebecausethe
TypeScripttranspilergeneratesJavaScriptthatcanbereadbyhumans.

TestingandDeployment
Angular2comeswithatestinglibrarythatallowsyoutowriteunittestsintheBDDformat.
CurrentlyitonlysupportstheJasmineframework,butadditionalframeworksupportisontheway.
WeuseKarmatestrunner,whichallowsteststoberunagainstvariousbrowsers.
TheProtractorframeworkallowsyoutowriteendtoendtestsforyourapplications.Ifyoumonitor
thenetworkwhileloadingasimpleapplicationindevelopmentmodeyouwillseethatthebrowser
downloadsmorethan5Mb(halfofthatbeingtheTypeScriptcompilerusedbythemoduleloader,
SystemJS).Butafterrunningdeploymentandoptimizationscripts(weusetheWebpackbundler),
thesizeofasmallappcanbeaslittleas160K(includingtheAngular2framework).Werelooking
forwardtoseeinghowAngularCLIwillimplementproductionbundling.TheAngularteamworks
onofflinetemplatecompilation,whichwilllowertheframeworksoverheadto50Kb.

LibrariesofUIComponents
AtthetimeofthiswritingthereareseverallibrariesoftheUIcomponentsthatyoucanusewith
Angular2applications:
PrimeNGalibraryofAngular2UIcomponentsbythecreatorsofPrimeFaces(apopularlibraryusedwith
JavaServerFacesframework).
Wijmo5acommerciallibraryofAngular2UIcomponents.Youhavetopurchasedeveloperslicensestouseit.
PolymeralibraryofnicelookingextendablecomponentsbyGoogle.Atourcompanywevemanagedtocreate
apilotAngular2appthatusesPolymercomponents,buttheintegrationofthetwoleavesroomfor
improvement.
MaterialDesign2alibraryofUIcomponentsbeingdevelopedatGooglespecificallyforAngular2.Currently
thislibraryisinearlyAlpha,butdevelopmentisprettyactive,andIexpecttoseeacoupleofdozenwell
designedUIcomponentsintheupcomingthreetofourmonths.
NGLightningalibraryofAngular2componentsanddirectiveswrittenfromscratchinTypeScriptusingthe
LightningDesignSystemCSSframework.

IsitsafetouseAngular2invivo?
StartingfromthefirstBetarelease,weareatFarataSystemsusingAngular2forarealworld
projectandhavenotrunintoanymajorissues,atleastnonethatdidnthaveapractical
workaround.
Ifyouwanttobesafe,waitacouplemoremonths.RumorhasitthatanAngular2release
candidatewillbeannouncedattheGoogleI/OconferenceinMayof2016.

Whatsinthefuture
https://www.infoq.com/articles/Angular2TypeScriptHighLevelOverview?utm_campaign=rightbar_v2&utm_source=infoq&utm_medium=articles_link&

6/7

10/5/2016

Angular2andTypeScriptAHighLevelOverview

InMarchof2016BradGreendeliveredakeynotepresentationattheFluentconferenceby
OReilly.Watchthevideoofthispresentation.Areyouimpressed?Iam.

AbouttheAuthor
YakovFainisaNewYorkbasedJavaChampionandpartneratITconsultancy
FarataSystems.HeleadsthePrincetonJUG,hasauthoredmanyarticleson
softwaredevelopmentandseveralbooks.Recentlyhecoauthoredthe
book"Angular2DevelopmentwithTypeScript",thatwillbepublishedbyManningin
Juneof2016.YakovoftenspeaksatconferencesandteachesJavaandAngular2
classes.Heblogsatyakovfain.com.

https://www.infoq.com/articles/Angular2TypeScriptHighLevelOverview?utm_campaign=rightbar_v2&utm_source=infoq&utm_medium=articles_link&

7/7

Vous aimerez peut-être aussi