diff --git a/.gitignore b/.gitignore index f0c8a32616..80f34ea11b 100644 --- a/.gitignore +++ b/.gitignore @@ -20,7 +20,7 @@ _.* public/docs/xref-*.* _zip-output www -/npm-debug.log +npm-debug.log npm-debug.log.* *.plnkr.html plnkr.html diff --git a/README.md b/README.md index 63a1f5fd53..2ee11b04d9 100644 --- a/README.md +++ b/README.md @@ -62,7 +62,7 @@ For example, all of the TypeScript docs are in `public/docs/ts/latest`, e.g. If you are only going to work on a specific part of the docs, such as the dev guide, then you can use one of the more specific gulp tasks to only watch those parts of the file system: * `gulp serve-and-sync` : watch all the local Jade/Sass files, the API source and examples, and the dev guide files -* `gulp serve-and-sync-api-docs` : watch only the API source and example files +* `gulp serve-and-sync-api` : watch only the API source and example files * `gulp serve-and-sync-devguide` : watch only the dev guide files * `gulp build-and-serve` : watch only the local Jade/Sass files diff --git a/firebase.json b/firebase.json index b82585e7f8..957cd5fc28 100644 --- a/firebase.json +++ b/firebase.json @@ -57,6 +57,10 @@ { "source": "/dart", "destination": "/docs/dart/latest/index.html" + }, + { + "source": "/styleguide", + "destination": "/docs/ts/latest/guide/style-guide.html" } ], "ignore": [ diff --git a/gulpfile.js b/gulpfile.js index 1476231c6c..448f9afb48 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -109,10 +109,12 @@ gulp.task('run-e2e-tests', function() { // with the corresponding apps that they should run under. Then run // each app/spec collection sequentially. function findAndRunE2eTests(filter) { + var lang = (argv.lang || '(ts|js)').toLowerCase(); + if (lang === 'all') { lang = '(ts|js|dart)'; } var startTime = new Date().getTime(); // create an output file with header. var outputFile = path.join(process.cwd(), 'protractor-results.txt'); - var header = "Protractor example results for: " + (new Date()).toLocaleString() + "\n\n"; + var header = "Protractor example results for " + lang + " on " + (new Date()).toLocaleString() + "\n\n"; if (filter) { header += ' Filter: ' + filter.toString() + '\n\n'; } @@ -128,6 +130,10 @@ function findAndRunE2eTests(filter) { fsExtra.copySync(srcConfig, destConfig); // get all of the examples under each dir where a pcFilename is found examplePaths = getExamplePaths(specPath, true); + // Filter by language + examplePaths = examplePaths.filter(function (fn) { + return fn.match('/'+lang+'$') != null; + }); if (filter) { examplePaths = examplePaths.filter(function (fn) { return fn.match(filter) != null; @@ -142,7 +148,9 @@ function findAndRunE2eTests(filter) { var status = { passed: [], failed: [] }; return exeConfigs.reduce(function (promise, combo) { return promise.then(function () { - return runE2eTests(combo.examplePath, combo.protractorConfigFilename, outputFile).then(function(ok) { + var isDart = combo.examplePath.indexOf('/dart') > -1; + var runTests = isDart ? runE2eDartTests : runE2eTsTests; + return runTests(combo.examplePath, combo.protractorConfigFilename, outputFile).then(function(ok) { var arr = ok ? status.passed : status.failed; arr.push(combo.examplePath); }) @@ -158,12 +166,16 @@ function findAndRunE2eTests(filter) { // start the example in appDir; then run protractor with the specified // fileName; then shut down the example. All protractor output is appended // to the outputFile. -function runE2eTests(appDir, protractorConfigFilename, outputFile ) { +function runE2eTsTests(appDir, protractorConfigFilename, outputFile) { // start the app var appRunSpawnInfo = spawnExt('npm',['run','http-server:e2e', '--', '-s' ], { cwd: appDir }); var tscRunSpawnInfo = spawnExt('npm',['run','tsc'], { cwd: appDir }); - return tscRunSpawnInfo.promise.then(function(data) { + return runProtractor(tscRunSpawnInfo.promise, appDir, appRunSpawnInfo, protractorConfigFilename, outputFile); +} + +function runProtractor(prepPromise, appDir, appRunSpawnInfo, protractorConfigFilename, outputFile) { + return prepPromise.then(function (data) { // start protractor var pcFilename = path.resolve(protractorConfigFilename); // need to resolve because we are going to be running from a different dir var exePath = path.join(process.cwd(), "./node_modules/.bin/"); @@ -175,7 +187,7 @@ function runE2eTests(appDir, protractorConfigFilename, outputFile ) { // Ugh... proc.kill does not work properly on windows with child processes. // appRun.proc.kill(); treeKill(appRunSpawnInfo.proc.pid); - return true; + return !data; }).fail(function(err) { // Ugh... proc.kill does not work properly on windows with child processes. // appRun.proc.kill(); @@ -184,19 +196,39 @@ function runE2eTests(appDir, protractorConfigFilename, outputFile ) { }); } +// start the server in appDir/build/web; then run protractor with the specified +// fileName; then shut down the example. All protractor output is appended +// to the outputFile. +function runE2eDartTests(appDir, protractorConfigFilename, outputFile) { + var deployDir = path.resolve(path.join(appDir, 'build/web')); + gutil.log('AppDir for Dart e2e: ' + appDir); + gutil.log('Deploying from: ' + deployDir); + + var appRunSpawnInfo = spawnExt('npm', ['run', 'http-server:e2e', '--', deployDir, '-s'], { cwd: EXAMPLES_PATH }); + if (!appRunSpawnInfo.proc.pid) { + gutil.log('http-server failed to launch over ' + deployDir); + return false; + } + var pubUpgradeSpawnInfo = spawnExt('pub', ['upgrade'], { cwd: appDir }); + var prepPromise = pubUpgradeSpawnInfo.promise.then(function (data) { + return spawnExt('pub', ['build'], { cwd: appDir }).promise; + }); + return runProtractor(prepPromise, appDir, appRunSpawnInfo, protractorConfigFilename, outputFile); +} + function reportStatus(status) { gutil.log('Suites passed:'); status.passed.forEach(function(val) { gutil.log(' ' + val); }); - gutil.log('Suites failed:'); - status.failed.forEach(function(val) { - gutil.log(' ' + val); - }); - if (status.failed.length == 0) { gutil.log('All tests passed'); + } else { + gutil.log('Suites failed:'); + status.failed.forEach(function (val) { + gutil.log(' ' + val); + }); } gutil.log('Elapsed time: ' + status.elapsedTime + ' seconds'); } @@ -808,7 +840,8 @@ function devGuideExamplesWatch(shredOptions, postShredAction) { // removed this version because gulp.watch has the same glob issue that dgeni has. // var excludePattern = '!' + path.join(shredOptions.examplesDir, '**/node_modules/**/*.*'); // gulp.watch([includePattern, excludePattern], {readDelay: 500}, function (event, done) { - var files = globby.sync( [includePattern], { ignore: [ '**/node_modules/**', '**/_fragments/**']}); + var files = globby.sync( [includePattern], { ignore: [ '**/node_modules/**', '**/_fragments/**', + '**/dart/build/**' ]}); gulp.watch([files], {readDelay: 500}, function (event, done) { gutil.log('Dev Guide example changed') gutil.log('Event type: ' + event.type); // added, changed, or deleted diff --git a/harp.json b/harp.json index aeeda7f949..5c2478685e 100644 --- a/harp.json +++ b/harp.json @@ -290,6 +290,7 @@ "name": "Stephen Fluin", "picture": "/resources/images/bios/stephenfluin.jpg", "twitter": "stephenfluin", + "website": "https://plus.google.com/+stephenfluin", "bio": "Stephen is a Developer Advocate working on the Angular team. Before joining Google, he was a Google Expert. Stephen loves to help enterprises use technology more effectively.", "type": "Google" }, diff --git a/package.json b/package.json index 91076fd867..e1a34a4754 100644 --- a/package.json +++ b/package.json @@ -17,8 +17,8 @@ }, "licenses": [ { - "type": "Apache", - "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + "type": "MIT", + "url": "https://github.com/angular/angular.io/blob/master/LICENSE" } ], "bugs": { @@ -34,7 +34,7 @@ "codelyzer": "0.0.18", "del": "^1.2.0", "dgeni": "^0.4.0", - "dgeni-packages": "^0.11.1", + "dgeni-packages": "^0.13.0", "diff": "^2.1.3", "fs-extra": "^0.24.0", "glob": "^5.0.14", diff --git a/public/_data.json b/public/_data.json index eec7703cf9..db51fd2e0d 100644 --- a/public/_data.json +++ b/public/_data.json @@ -47,9 +47,5 @@ "tooling": { "title": "工具与库" - }, - - "all-resources": { - "title": "资源" } } diff --git a/public/_includes/_hero-home.jade b/public/_includes/_hero-home.jade index a653da5d4f..6795c124ea 100644 --- a/public/_includes/_hero-home.jade +++ b/public/_includes/_hero-home.jade @@ -7,11 +7,3 @@ header(class="background-sky") h2 点击“译文”可显示/隐藏“原文”,点击“原文”可隐藏自身 -.banner.banner-floaty - .banner-ng-annoucement - div(class="banner-text") - p Watch the ng-conf Live Stream May 4th-6th.  - p 观看 ng-conf 实时视频 May 4th-6th.  - div(class="banner-button") - a(href="https://www.ng-conf.org/#/extended" target="_blank" class="button md-button") View Live Stream - a(href="https://www.ng-conf.org/#/extended" target="_blank" class="button md-button") 查看实时视频 diff --git a/public/_includes/_hero.jade b/public/_includes/_hero.jade index 53bf8fee5d..6e301a0b71 100644 --- a/public/_includes/_hero.jade +++ b/public/_includes/_hero.jade @@ -4,6 +4,12 @@ - var capitalize = function capitalize(str) { return str.charAt(0).toUpperCase() + str.slice(1); } - var useBadges = docType || stability; +// renamer :: String -> String +// Renames `Let` and `Var` into `Const` +- var renamer = function renamer(docType) { +- return (docType === 'Let' || docType === 'Var') ? 'Const' : docType +- } + if current.path[4] && current.path[3] == 'api' - var textFormat = 'is-standard-case' @@ -14,12 +20,15 @@ header(class="hero background-sky") span(class="badges") if docType span(class="status-badge"). - #{capitalize(docType)} + #{renamer(capitalize(docType))} if stability span(layout="row" class="status-badge") // badge circle is filled based on stability by matching a css selector in _hero.scss span(class="status-circle status-#{stability}") span Stability: #{capitalize(stability)} + if security + span(class="status-badge security-risk-badge"). + Security Risk if subtitle h2.hero-subtitle.text-subhead #{subtitle} diff --git a/public/_includes/_scripts-include.jade b/public/_includes/_scripts-include.jade index 5dd3407ed7..cb70b047e6 100644 --- a/public/_includes/_scripts-include.jade +++ b/public/_includes/_scripts-include.jade @@ -12,12 +12,18 @@ script(src="/resources/js/vendor/angular-animate.min.js") script(src="/resources/js/vendor/angular-aria.min.js") script(src="/resources/js/vendor/angular-material.min.js") + + + + + script(src="/resources/js/translate.js") script(src="/resources/js/site.js") script(src="/resources/js/controllers/app-controller.js") +script(src="/resources/js/controllers/resources-controller.js") script(src="/resources/js/directives/cheatsheet.js") script(src="/resources/js/directives/api-list.js") script(src="/resources/js/directives/bio.js") diff --git a/public/_includes/_util-fns.jade b/public/_includes/_util-fns.jade index 00288b6c6c..42dfe66944 100644 --- a/public/_includes/_util-fns.jade +++ b/public/_includes/_util-fns.jade @@ -1,5 +1,56 @@ //- Mixins and associated functions +//- _docsFor: used to identify the language this version of the docs if for; +//- Should be one of: 'ts', 'dart' or 'js'. Set in lang specific _util-fns file. +- var _docsFor = ''; + +//- Should match `_docsFor`, but in this case provides the full capitalized +//- name of the language. +- var _Lang = 'TypeScript'; + +//- Simple "macros" used via interpolation in text: +//- e.g., the #{_priv}el variable has an `@Input` #{_decorator}. + +//- Use #{_decorator} whereever the word "decorator" is expected, provided it is not +//- preceded by the article "a". (E.g., will be "annotation" for Dart) +- var _decorator = 'decorator'; + +//- Articles (which toggle between 'a' and 'an'). Used for, e.g., +//- array vs. list; decorator vs. annotation. +- var _a = 'a'; +- var _an = 'an'; + +//- TS arrays vs. Dart lists +- var _array = 'array'; +//- Deprecate now that we have the articles _a and _an +- var _an_array = 'an array'; + +//- Promise vs. Future, etc +- var _Promise = 'Promise'; +- var _Observable = 'Observable'; + +//- Location of sample code +- var _liveLink = 'live link'; + + +//- Used to prefix identifiers that are private. In Dart this will be '_'. +- var _priv = ''; + +//- Use to conditionally include the block that follows +ifDocsFor(...). +//- Generally favor use of Jade named blocks instead. ifDocsFor is convenient +//- for prose that should appear only in one language version. +mixin ifDocsFor(lang) + if _docsFor.toLowerCase() === lang.toLowerCase() + block + +//- Use to map inlined (prose) TS paths into, say, Dart paths via the +//- adjustExamplePath transformer function. +mixin adjExPath(path) + if adjustExamplePath + | #{adjustExamplePath(path)} + else + | #{path} + mixin includeShared(filePath, region) - var newPath = translatePath(filePath, region); !=partial(newPath) @@ -11,6 +62,7 @@ mixin makeExample(_filePath, region, _title, stylePatterns) - var frag = getFrag(filePath, region); - var defaultFormat = frag.split('\n').length > 2 ? "linenums" : ""; - var format = attributes.format || defaultFormat; + - if (attributes.format === '.') format = ''; - var avoid = !!attributes.avoid; if (title) @@ -21,10 +73,49 @@ mixin makeExample(_filePath, region, _title, stylePatterns) code-example(language="#{language}" format="#{format}") != styleString(frag, stylePatterns) +//- Like makeExample, but the first argument is a path that is +//- relative to the project root. Unless title is defined, +//- the project relative path will be used. +mixin makeProjExample(projRootRelativePath, region, title, stylePatterns) + - var relPath = projRootRelativePath.trim(); + - var filePath = getExampleName() + '/ts/' + relPath; + - if (!title) { + - // Is path like styles.1.css? Then drop the '.1' qualifier: + - var matches = relPath.match(/^(.*)\.\d(\.\w+)$/); + - title = matches ? matches[1] + matches[2] : relPath; + - } + +makeExample(filePath, region, title, stylePatterns) + +//- Like makeExample, but doesn't show line numbers, and the first +//- argument is a path that is relative to the example project root. +//- Unless title is defined, the project relative path will be used. +//- Title will always end with a phrase in parentheses; if no such +//- ending is given, then the title will be suffixed with +//- either "(excerpt)", or "(#{region})" when region is defined. +mixin makeExcerpt(projRootRelativePath, region, title, stylePatterns) + - var relPath = projRootRelativePath.trim(); + - var filePath = getExampleName() + '/ts/' + relPath; + - if (!title) { + - // Is path like styles.1.css? Then drop the '.1' qualifier: + - var matches = relPath.match(/^(.*)\.\d(\.\w+)$/); + - title = matches ? matches[1] + matches[2] : relPath; + - } + - var excerpt = region || 'excerpt'; + - if (title && !title.match(/\([\w ]+\)$/)) title = title + ' (' + excerpt + ')'; + +makeExample(filePath, region, title, stylePatterns)(format='.') + +//- Extract the doc example name from `current`. +- var getExampleName = function() { +- var dir = current.path[current.path.length - 1]; +- return dir == 'latest' ? current.source : dir; +- }; + mixin makeTabs(filePaths, regions, tabNames, stylePatterns) - filePaths = strSplit(filePaths); + - if (adjustExamplePath) filePaths = filePaths.map(adjustExamplePath); - regions = strSplit(regions, filePaths.length); - tabNames = strSplit(tabNames, filePaths.length); + - if (adjustExampleTitle) tabNames = tabNames.map(adjustExampleTitle); code-tabs each filePath,index in filePaths @@ -77,7 +168,7 @@ script. el.style.display = isVerbose ? 'block' : 'none'; var el = document.querySelector('button.verbose.on'); el.style.display = isVerbose ? 'none' : 'block'; - + CCSStylesheetRuleStyle('main','.l-verbose-section', 'display', isVerbose ? 'block' : 'none'); } diff --git a/public/all-resources.jade b/public/all-resources.jade deleted file mode 100644 index 1d6dfa6d0c..0000000000 --- a/public/all-resources.jade +++ /dev/null @@ -1,200 +0,0 @@ -div - p(class="text-body") Would you like to be listed in this page? Fill out this form. - div(style="display: flex; justify-content: space-between; flex-wrap: wrap;") - div - h1 Books - div(class="resources") - h3 Packt Publishing - ul(class="publisher") - li(class="book") - a(class="title text-body" href="https://www.packtpub.com/web-development/switching-angular-2") Switching to Angular 2 - li(class="book") - a(class="title text-body" href="https://www.packtpub.com/web-development/mastering-angular-2-components") Mastering Angular 2 Components - li(class="book") - a(class="title text-body" href="https://www.packtpub.com/web-development/angular-2-blueprints") Angular 2 Blueprints - li(class="book") - a(class="title text-body" href="https://www.packtpub.com/web-development/angular-2-example") Angular 2 By Examples - li(class="book") - a(class="title text-body" href="https://www.packtpub.com/web-development/mastering-angular-2-components") Angular 2 Components - li(class="book") - a(class="title text-body" href="https://www.packtpub.com/web-development/learning-angular-2-net-developers") Learning Angular 2 for .NET Developers - li(class="book") - a(class="title text-body" href="https://www.packtpub.com/web-development/angular-2-test-driven-development") Angular 2 Test-driven Development - - h3 Manning Publications - ul(class="publisher") - li(class="book") - a(class="title text-body" href="https://www.manning.com/books/angular-2-in-action") Angular 2 In Action - li(class="book") - a(class="title text-body" href="https://www.manning.com/books/angular-2-development-with-typescript") Angular 2 Development with TypeScript - li(class="book") - a(class="title text-body" href="https://www.manning.com/books/testing-angular-2-applications") Testing Angular 2 Applications - - h3 O'Reilly Media - ul(class="publisher") - li(class="book") - a(class="title text-body" href="http://www.oreilly.com/pub/e/3693") Angular 2 Web Development with TypeScript - li(class="book") - a(class="title text-body" href="http://shop.oreilly.com/product/0636920051824.do") Migrating to Angular 2 - li(class="book") - a(class="title text-body" href="http://shop.oreilly.com/product/9781785886201.do") Switching to Angular 2 - - h3 Self-published - ul(class="publisher") - li(class="book") - a(class="title text-body" href="http://ngcourse.rangle.io/") Rangle.io: ngCourse 2 - li(class="book") - a(class="title text-body" href="https://www.ng-book.com/2/") ng-book 2 - li(class="book") - a(class="title text-body" href="https://leanpub.com/angular2-book") Angular 2 Book - li(class="book") - a(class="title text-body" href="https://books.ninja-squad.com/angular2") Become a ninja with Angular 2 - li(class="book") - a(class="title text-body" href="https://leanpub.com/practical-angular-2") Practical Angular 2 - - div - h1 Training - div(class="resources") - h3 Rangle.io - ul(class="publisher") - li(class="course") - a(class="title text-body" href="http://rangle.io/services/javascript-training/training-angular1-angular2-with-ngupgrade/") Angular 2 Online Training - - h3 Pluralsight - ul(class="publisher") - li(class="course") - a(class="title text-body" href="https://www.pluralsight.com/courses/angular-2-first-look") Angular 2: First Look - li(class="course") - a(class="title text-body" href="https://www.pluralsight.com/courses/angular-2-getting-started") Angular 2: Getting Started - - h3 Udemy - ul(class="publisher") - li - a(class="title text-body" href="https://www.udemy.com/the-complete-guide-to-angular-2/?utm_content=_._ag_angular%202_._ad_47395956109_._de_c_._dm__._lo_9061189_._&matchtype=b&gclid=CjwKEAjww9O3BRDp1tq0jIP023YSJAB0-j1S4bFN4tudrjzZO_-ABNAfFQJrhrKo7KX1AnV-8yjV-hoCRrDw_wcB&utm_medium=udemyads&k_clickid=dce13cd7-9844-44dc-9967-020275b637c9_408_GOOGLE_NEW-AW-PROS-TECH-Dev-angular-2-EN-ENG_._ci_756150_._sl_ENG_._vi_TECH_._sd_All_._la_EN_.__angular%202_%2Bangular%20%2B2_b_47395956109_c&utm_campaign=NEW-AW-PROS-TECH-Dev-angular-2-EN-ENG_._ci_756150_._sl_ENG_._vi_TECH_._sd_All_._la_EN_._&utm_source=adwords&utm_term=_._pl__._pd__._ti_kwd-68757357257_._kw_%2Bangular%20%2B2_._&pmtag=72bf13dc-329c-411c-b381-a6143735b9dc") The Complete Guide to Angular 2 - li - a(class="title text-body" href="https://www.udemy.com/angular-2-tutorial-for-beginners/") Angular 2 With TypeScript for Beginners - li - a(class="title text-body" href="https://www.udemy.com/angular-2-tutorial-for-beginners/") Angular 2 Jumpstart with Typescript - li - a(class="title text-body" href="https://www.udemy.com/angular-2-fundamentals/") Angular 2 Fundamentals - li - a(class="title text-body" href="https://www.udemy.com/angular-2-master-class-with-alejandro-rangel/") Angular 2 Master Class - li - a(class="title text-body" href="https://www.udemy.com/introduction-to-angular2/") Angular 2 Demystified - - h3 egghead.io - ul(class="publisher") - li - a(class="title text-body" href="https://egghead.io/technologies/angular2") Angular 2 videos - - h3 Workshops & Onsite Training Vendors - ul(class="publisher") - li - a(class="title text-body" href="http://rangle.io/services/javascript-training/angular2-training/") Rangle.io - li - a(class="title text-body" href="http://oasisdigital.com/training") Oasis Digital - li - a(class="title text-body" href="http://thoughtram.io/") Thoughtram - - div - h1 Tooling and Libraries - div(class="resources") - h3 Tooling - ul - li - a(class="text-body" href="https://augury.rangle.io/") Augury - li - a(class="text-body" href="https://github.com/angular/universal") Angular Universal - li - a(class="text-body" href="https://github.com/johnpapa/lite-server") Lite-server - li - a(class="text-body" href="https://github.com/mgechev/codelyzer") Codelyzer - - h3 IDEs - ul - li - a(class="text-body" href="http://code.visualstudio.com/") Visual Studio Code - li - a(class="text-body" href="https://www.jetbrains.com/webstorm/") WebStorm - li - a(class="text-body" href="https://www.jetbrains.com/idea/") IntelliJ IDEA - - h3 Data Libraries - ul - li - a(class="text-body" href="https://www.firebase.com/") Firebase - li - a(class="text-body" href="https://www.meteor.com/") Meteor - li - a(class="text-body" href="http://mean.io/") MEAN - - h3 UI Components - ul - li - a(class="text-body" href="https://github.com/angular/material2") Angular Material 2 - li - a(class="text-body" href="http://www.primefaces.org/primeng/") Prime Faces - li - a(class="text-body" href="http://www.telerik.com/blogs/what-to-expect-in-2016-for-kendo-ui-with-angular-2-and-more") Kendo UI - li - a(class="text-body" href="http://ng-lightning.github.io/ng-lightning/") ng-lightening - li - a(class="text-body" href="http://wijmo.com/products/wijmo-5/") Wijmo - li - a(class="text-body" href="https://angular-ui.github.io/bootstrap/") Bootstrap UI - li - a(class="text-body" href="https://vaadin.com/home") Vaadin - - h3 Cross-Platform Development - ul - li - a(class="text-body" href="https://github.com/NativeScript/nativescript-angular") NativeScript - li - a(class="text-body" href="http://angular.github.io/react-native-renderer/") React Native - li - a(class="text-body" href="http://ionicframework.com/docs/v2/") Ionic - li - a(class="text-body" href="http://github.com/angular/angular-electron") Electron - li - a(class="text-body" href="http://github.com/preboot/angular2-universal-windows-app") Windows (UWP) - - div - h1 Communities - div(class="resources") - p(class="text-body") Would you like to be listed in this page? Fill out this form. - - h3 Podcasts - ul(class="podcasts") - li(class="podcast") - a(class="text-body" href="https://angularair.com/") AngularAir - li(class="podcast") - a(class="text-body" href="https://javascriptair.com/") JavaScript Air - li(class="podcast") - a(class="text-body" href="https://devchat.tv/adventures-in-angular") Adventures in Angular - - - h3 Communities - ul(class="communities") - li(class="community") - a(class="text-body" href="http://angularbeers.org/") Angular Beers - li(class="community") - a(class="text-body" href="http://angularcamp.org/") Angular Camp - li(class="community") - a(class="text-body" href="http://www.meetup.com/find/?allMeetups=false&keywords=angularjs&radius=Infinity&userFreeform=94043&gcResults=Mountain+View%2C+CA+94043%2C+USA%3AUS%3ACalifornia%3ASanta+Clara+County%3AMountain+View%3Anull%3A94043%3A37.428434%3A-122.07238159999997&change=yes&sort=default") Angular Meetups - - - - - - - - - - - - - - - - - diff --git a/public/books.jade b/public/books.jade deleted file mode 100644 index b9a60d089a..0000000000 --- a/public/books.jade +++ /dev/null @@ -1,54 +0,0 @@ -div(class="resources") - p(class="text-body") Would you like to be listed in this page? Fill out this form. - - h3 Packt Publishing - ul(class="publisher") - li(class="book") - a(class="title text-body" href="https://www.packtpub.com/web-development/switching-angular-2") Switching to Angular 2 - li(class="book") - a(class="title text-body" href="https://www.packtpub.com/web-development/mastering-angular-2-components") Mastering Angular 2 Components - li(class="book") - a(class="title text-body" href="https://www.packtpub.com/web-development/angular-2-blueprints") Angular 2 Blueprints - li(class="book") - a(class="title text-body" href="https://www.packtpub.com/web-development/angular-2-example") Angular 2 By Examples - li(class="book") - a(class="title text-body" href="https://www.packtpub.com/web-development/mastering-angular-2-components") Angular 2 Components - li(class="book") - a(class="title text-body" href="https://www.packtpub.com/web-development/learning-angular-2-net-developers") Learning Angular 2 for .NET Developers - li(class="book") - a(class="title text-body" href="https://www.packtpub.com/web-development/angular-2-test-driven-development") Angular 2 Test-driven Development - - h3 Manning Publications - ul(class="publisher") - li(class="book") - a(class="title text-body" href="https://www.manning.com/books/angular-2-in-action") Angular 2 In Action - li(class="book") - a(class="title text-body" href="https://www.manning.com/books/angular-2-development-with-typescript") Angular 2 Development with TypeScript - li(class="book") - a(class="title text-body" href="https://www.manning.com/books/testing-angular-2-applications") Testing Angular 2 Applications - - h3 O'Reilly Media - ul(class="publisher") - li(class="book") - a(class="title text-body" href="http://www.oreilly.com/pub/e/3693") Angular 2 Web Development with TypeScript - li(class="book") - a(class="title text-body" href="http://shop.oreilly.com/product/0636920051824.do") Migrating to Angular 2 - li(class="book") - a(class="title text-body" href="http://shop.oreilly.com/product/9781785886201.do") Switching to Angular 2 - - h3 Self-published - ul(class="publisher") - li(class="book") - a(class="title text-body" href="http://ngcourse.rangle.io/") Rangle.io: ngCourse 2 - li(class="book") - a(class="title text-body" href="https://www.ng-book.com/2/") ng-book 2 - li(class="book") - a(class="title text-body" href="https://leanpub.com/angular2-book") Angular 2 Book - li(class="book") - a(class="title text-body" href="https://books.ninja-squad.com/angular2") Become a ninja with Angular 2 - li(class="book") - a(class="title text-body" href="https://leanpub.com/practical-angular-2") Practical Angular 2 - - - - diff --git a/public/communities.jade b/public/communities.jade deleted file mode 100644 index a6b5c0dcf4..0000000000 --- a/public/communities.jade +++ /dev/null @@ -1,26 +0,0 @@ -div(class="resources") - p(class="text-body") Would you like to be listed in this page? Fill out this form. - - h3 Podcasts - ul(class="podcasts") - li(class="podcast") - a(class="text-body" href="https://angularair.com/") AngularAir - li(class="podcast") - a(class="text-body" href="https://javascriptair.com/") JavaScript Air - li(class="podcast") - a(class="text-body" href="https://devchat.tv/adventures-in-angular") Adventures in Angular - - - h3 Communities - ul(class="communities") - li(class="community") - a(class="text-body" href="http://angularbeers.org/") Angular Beers - li(class="community") - a(class="text-body" href="http://angularcamp.org/") Angular Camp - li(class="community") - a(class="text-body" href="http://www.meetup.com/find/?allMeetups=false&keywords=angularjs&radius=Infinity&userFreeform=94043&gcResults=Mountain+View%2C+CA+94043%2C+USA%3AUS%3ACalifornia%3ASanta+Clara+County%3AMountain+View%3Anull%3A94043%3A37.428434%3A-122.07238159999997&change=yes&sort=default") Angular Meetups - - - - - diff --git a/public/docs/_examples/.gitignore b/public/docs/_examples/.gitignore index a7b60352e4..449fd35581 100644 --- a/public/docs/_examples/.gitignore +++ b/public/docs/_examples/.gitignore @@ -20,7 +20,7 @@ _test-output _temp **/ts/**/*.js **/ts-snippets/**/*.js -**/ts/**/*.d.ts +*.d.ts !**/*e2e-spec.js !systemjs.config.1.js diff --git a/public/docs/_examples/architecture/ts/app/app.component.ts b/public/docs/_examples/architecture/ts/app/app.component.ts index 409fde3aa3..930cf5f045 100644 --- a/public/docs/_examples/architecture/ts/app/app.component.ts +++ b/public/docs/_examples/architecture/ts/app/app.component.ts @@ -1,8 +1,8 @@ // #docregion import -import {Component} from '@angular/core'; +import { Component } from '@angular/core'; // #enddocregion import -import {HeroListComponent} from './hero-list.component'; -import {SalesTaxComponent} from './sales-tax.component'; +import { HeroListComponent } from './hero-list.component'; +import { SalesTaxComponent } from './sales-tax.component'; @Component({ selector: 'my-app', diff --git a/public/docs/_examples/architecture/ts/app/backend.service.ts b/public/docs/_examples/architecture/ts/app/backend.service.ts index 2170c88758..907a40696e 100644 --- a/public/docs/_examples/architecture/ts/app/backend.service.ts +++ b/public/docs/_examples/architecture/ts/app/backend.service.ts @@ -1,6 +1,7 @@ -import {Injectable, Type} from '@angular/core'; -import {Logger} from './logger.service'; -import {Hero} from './hero'; +import { Injectable, Type } from '@angular/core'; + +import { Logger } from './logger.service'; +import { Hero } from './hero'; const HEROES = [ new Hero('Windstorm', 'Weather mastery'), @@ -10,7 +11,7 @@ const HEROES = [ @Injectable() export class BackendService { - constructor(private _logger: Logger) {} + constructor(private logger: Logger) {} getAll(type:Type) : PromiseLike{ if (type === Hero) { @@ -18,7 +19,7 @@ export class BackendService { return Promise.resolve(HEROES); } let err = new Error('Cannot get object of this type'); - this._logger.error(err); + this.logger.error(err); throw err; } -} \ No newline at end of file +} diff --git a/public/docs/_examples/architecture/ts/app/hero-detail.component.ts b/public/docs/_examples/architecture/ts/app/hero-detail.component.ts index 2a8d23e392..579ef637b0 100644 --- a/public/docs/_examples/architecture/ts/app/hero-detail.component.ts +++ b/public/docs/_examples/architecture/ts/app/hero-detail.component.ts @@ -1,5 +1,6 @@ -import {Component, Input} from '@angular/core'; -import {Hero} from './hero'; +import { Component, Input} from '@angular/core'; + +import { Hero } from './hero'; @Component({ selector: 'hero-detail', diff --git a/public/docs/_examples/architecture/ts/app/hero-list.component.ts b/public/docs/_examples/architecture/ts/app/hero-list.component.ts index 686775eff5..8e4ca9b1ae 100644 --- a/public/docs/_examples/architecture/ts/app/hero-list.component.ts +++ b/public/docs/_examples/architecture/ts/app/hero-list.component.ts @@ -1,8 +1,9 @@ // #docplaster -import {Component, OnInit} from '@angular/core'; -import {Hero} from './hero'; -import {HeroDetailComponent} from './hero-detail.component'; -import {HeroService} from './hero.service'; +import { Component, OnInit } from '@angular/core'; + +import { Hero } from './hero'; +import { HeroDetailComponent } from './hero-detail.component'; +import { HeroService } from './hero.service'; // #docregion metadata // #docregion providers @@ -24,14 +25,14 @@ export class HeroesComponent { ... } // #docregion class export class HeroListComponent implements OnInit { // #docregion ctor - constructor(private _service: HeroService) { } + constructor(private service: HeroService) { } // #enddocregion ctor heroes: Hero[]; selectedHero: Hero; ngOnInit() { - this.heroes = this._service.getHeroes(); + this.heroes = this.service.getHeroes(); } selectHero(hero: Hero) { this.selectedHero = hero; } diff --git a/public/docs/_examples/architecture/ts/app/hero.service.ts b/public/docs/_examples/architecture/ts/app/hero.service.ts index 7f524daa4d..d5df3bdf31 100644 --- a/public/docs/_examples/architecture/ts/app/hero.service.ts +++ b/public/docs/_examples/architecture/ts/app/hero.service.ts @@ -1,25 +1,26 @@ -import {Injectable} from '@angular/core'; -import {Hero} from './hero'; -import {BackendService} from './backend.service'; -import {Logger} from './logger.service'; +import { Injectable } from '@angular/core'; + +import { Hero } from './hero'; +import { BackendService } from './backend.service'; +import { Logger } from './logger.service'; @Injectable() // #docregion class export class HeroService { // #docregion ctor constructor( - private _backend: BackendService, - private _logger: Logger) { } + private backend: BackendService, + private logger: Logger) { } // #enddocregion ctor - private _heroes: Hero[] = []; + private heroes: Hero[] = []; getHeroes() { - this._backend.getAll(Hero).then( (heroes: Hero[]) => { - this._logger.log(`Fetched ${heroes.length} heroes.`); - this._heroes.push(...heroes); // fill cache + this.backend.getAll(Hero).then( (heroes: Hero[]) => { + this.logger.log(`Fetched ${heroes.length} heroes.`); + this.heroes.push(...heroes); // fill cache }); - return this._heroes; + return this.heroes; } } // #enddocregion class diff --git a/public/docs/_examples/architecture/ts/app/logger.service.ts b/public/docs/_examples/architecture/ts/app/logger.service.ts index ddbcb61ca7..2d66d202eb 100644 --- a/public/docs/_examples/architecture/ts/app/logger.service.ts +++ b/public/docs/_examples/architecture/ts/app/logger.service.ts @@ -1,5 +1,5 @@ // #docregion -import {Injectable} from '@angular/core'; +import { Injectable } from '@angular/core'; @Injectable() // #docregion class diff --git a/public/docs/_examples/architecture/ts/app/main.ts b/public/docs/_examples/architecture/ts/app/main.ts index f5ab51b113..4e8c107afd 100644 --- a/public/docs/_examples/architecture/ts/app/main.ts +++ b/public/docs/_examples/architecture/ts/app/main.ts @@ -1,10 +1,10 @@ -import {bootstrap} from '@angular/platform-browser-dynamic'; +import { bootstrap } from '@angular/platform-browser-dynamic'; // #docregion import -import {AppComponent} from './app.component'; +import { AppComponent } from './app.component'; // #enddocregion import -import {HeroService} from './hero.service'; -import {BackendService} from './backend.service'; -import {Logger} from './logger.service'; +import { HeroService } from './hero.service'; +import { BackendService } from './backend.service'; +import { Logger } from './logger.service'; // #docregion bootstrap bootstrap(AppComponent, [BackendService, HeroService, Logger]); diff --git a/public/docs/_examples/architecture/ts/app/sales-tax.component.ts b/public/docs/_examples/architecture/ts/app/sales-tax.component.ts index 19234de171..6d0c668578 100644 --- a/public/docs/_examples/architecture/ts/app/sales-tax.component.ts +++ b/public/docs/_examples/architecture/ts/app/sales-tax.component.ts @@ -1,8 +1,9 @@ // #docplaster // #docregion -import {Component} from '@angular/core'; -import {SalesTaxService} from './sales-tax.service'; -import {TaxRateService} from './tax-rate.service'; +import { Component } from '@angular/core'; + +import { SalesTaxService } from './sales-tax.service'; +import { TaxRateService } from './tax-rate.service'; // #docregion metadata // #docregion providers @@ -12,7 +13,7 @@ import {TaxRateService} from './tax-rate.service'; template: `

Sales Tax Calculator

Amount: - +
The sales tax is {{ getTax(amountBox.value) | currency:'USD':true:'1.2-2' }} @@ -31,11 +32,11 @@ export class SalesTaxComponent { ... } // #docregion class export class SalesTaxComponent { // #docregion ctor - constructor(private _salesTaxService: SalesTaxService) { } + constructor(private salesTaxService: SalesTaxService) { } // #enddocregion ctor getTax(value:string | number){ - return this._salesTaxService.getVAT(value); + return this.salesTaxService.getVAT(value); } } // #enddocregion class diff --git a/public/docs/_examples/architecture/ts/app/sales-tax.service.ts b/public/docs/_examples/architecture/ts/app/sales-tax.service.ts index 86a797515c..813cb4c9c0 100644 --- a/public/docs/_examples/architecture/ts/app/sales-tax.service.ts +++ b/public/docs/_examples/architecture/ts/app/sales-tax.service.ts @@ -1,11 +1,12 @@ // #docregion -import {Injectable, Inject} from '@angular/core'; -import {TaxRateService} from './tax-rate.service'; +import { Inject, Injectable } from '@angular/core'; + +import { TaxRateService } from './tax-rate.service'; // #docregion class @Injectable() export class SalesTaxService { - constructor(private _rateService: TaxRateService) { } + constructor(private rateService: TaxRateService) { } getVAT(value:string | number){ let amount:number; if (typeof value === "string"){ @@ -13,7 +14,7 @@ export class SalesTaxService { } else { amount = value; } - return (amount || 0) * this._rateService.getRate('VAT'); + return (amount || 0) * this.rateService.getRate('VAT'); } } -// #enddocregion class \ No newline at end of file +// #enddocregion class diff --git a/public/docs/_examples/architecture/ts/app/tax-rate.service.ts b/public/docs/_examples/architecture/ts/app/tax-rate.service.ts index 8e6b9add1e..baaa8f49c7 100644 --- a/public/docs/_examples/architecture/ts/app/tax-rate.service.ts +++ b/public/docs/_examples/architecture/ts/app/tax-rate.service.ts @@ -1,9 +1,9 @@ // #docregion -import {Injectable} from '@angular/core'; +import { Injectable } from '@angular/core'; // #docregion class @Injectable() export class TaxRateService { getRate(rateName:string){return 0.10;} // always 10% everywhere } -// #enddocregion class \ No newline at end of file +// #enddocregion class diff --git a/public/docs/_examples/architecture/ts/index.html b/public/docs/_examples/architecture/ts/index.html index eb3a14a9c4..e9026e0ffc 100644 --- a/public/docs/_examples/architecture/ts/index.html +++ b/public/docs/_examples/architecture/ts/index.html @@ -15,7 +15,7 @@ diff --git a/public/docs/_examples/attribute-directives/dart/lib/app_component.dart b/public/docs/_examples/attribute-directives/dart/lib/app_component.dart index 2494fc3fd7..29f44ea6e9 100644 --- a/public/docs/_examples/attribute-directives/dart/lib/app_component.dart +++ b/public/docs/_examples/attribute-directives/dart/lib/app_component.dart @@ -6,7 +6,7 @@ import 'highlight_directive.dart'; @Component( selector: 'my-app', templateUrl: 'app_component.html', - directives: const [Highlight]) + directives: const [HighlightDirective]) class AppComponent { String color; } diff --git a/public/docs/_examples/attribute-directives/dart/lib/app_component.html b/public/docs/_examples/attribute-directives/dart/lib/app_component.html index b8fd63c8e3..f174bebbbb 100644 --- a/public/docs/_examples/attribute-directives/dart/lib/app_component.html +++ b/public/docs/_examples/attribute-directives/dart/lib/app_component.html @@ -7,14 +7,14 @@ Yellow Cyan
- -

Highlight me!

- + +

Highlight me!

+ -

+

Highlight me too! -

+

diff --git a/public/docs/_examples/attribute-directives/dart/lib/app_component_1.html b/public/docs/_examples/attribute-directives/dart/lib/app_component_1.html index b76a260a1a..e5ee1c6463 100644 --- a/public/docs/_examples/attribute-directives/dart/lib/app_component_1.html +++ b/public/docs/_examples/attribute-directives/dart/lib/app_component_1.html @@ -1,3 +1,7 @@

My First Attribute Directive

-Highlight me! +

Highlight me!

+ + +

I am green with envy!

+ diff --git a/public/docs/_examples/attribute-directives/dart/lib/highlight_directive.dart b/public/docs/_examples/attribute-directives/dart/lib/highlight_directive.dart index a6c0856cc4..e6190a443c 100644 --- a/public/docs/_examples/attribute-directives/dart/lib/highlight_directive.dart +++ b/public/docs/_examples/attribute-directives/dart/lib/highlight_directive.dart @@ -2,51 +2,42 @@ // #docregion full import 'package:angular2/core.dart'; -@Directive(selector: '[my-highlight]', host: const { +@Directive(selector: '[myHighlight]', host: const { '(mouseenter)': 'onMouseEnter()', '(mouseleave)': 'onMouseLeave()' }) // #docregion class-1 -class Highlight { - // #enddocregion class-1 -// #enddocregion full - /* -// #docregion highlight - @Input() myHighlight: string; -// #enddocregion highlight - */ -// #docregion full -// #docregion class-1 -// #docregion color - @Input('my-highlight') String highlightColor; -// #enddocregion color - +class HighlightDirective { String _defaultColor = 'red'; + final dynamic _el; + + HighlightDirective(ElementRef elRef) : _el = elRef.nativeElement; // #enddocregion class-1 + // #docregion defaultColor @Input() set defaultColor(String colorName) { _defaultColor = (colorName ?? _defaultColor); } // #enddocregion defaultColor -// #docregion class-1 + // #docregion class-1 - final ElementRef _element; + // #docregion color + @Input('myHighlight') String highlightColor; + // #enddocregion color + + // #docregion mouse-enter + void onMouseEnter() { _highlight(highlightColor ?? _defaultColor); } + // #enddocregion mouse-enter + void onMouseLeave() { _highlight(); } -// #docregion mouse-enter - onMouseEnter() { - _highlight(highlightColor ?? _defaultColor); + void _highlight([String color]) { + if(_el != null) _el.style.backgroundColor = color; } - -// #enddocregion mouse-enter - onMouseLeave() { - _highlight(null); - } - - void _highlight(String color) { - _element.nativeElement.style.backgroundColor = color; - } - - Highlight(this._element); } // #enddocregion class-1 // #enddocregion full +/* +// #docregion highlight +@Input() String myHighlight; +// #enddocregion highlight +*/ diff --git a/public/docs/_examples/attribute-directives/dart/lib/highlight_directive_1.dart b/public/docs/_examples/attribute-directives/dart/lib/highlight_directive_1.dart index 3b79e66a3b..2ce0e35919 100644 --- a/public/docs/_examples/attribute-directives/dart/lib/highlight_directive_1.dart +++ b/public/docs/_examples/attribute-directives/dart/lib/highlight_directive_1.dart @@ -3,9 +3,9 @@ library attribute_directives.highlight_directive; import 'package:angular2/core.dart'; -@Directive(selector: '[my-highlight]') -class Highlight { - Highlight(ElementRef element) { +@Directive(selector: '[myHighlight]') +class HighlightDirective { + HighlightDirective(ElementRef element) { element.nativeElement.style.backgroundColor = 'yellow'; } } diff --git a/public/docs/_examples/attribute-directives/dart/lib/highlight_directive_2.dart b/public/docs/_examples/attribute-directives/dart/lib/highlight_directive_2.dart index 8c540b3a6a..8546f36279 100644 --- a/public/docs/_examples/attribute-directives/dart/lib/highlight_directive_2.dart +++ b/public/docs/_examples/attribute-directives/dart/lib/highlight_directive_2.dart @@ -1,32 +1,28 @@ // #docregion import 'package:angular2/core.dart'; -@Directive(selector: '[my-highlight]', -// #docregion host +@Directive(selector: '[myHighlight]', + // #docregion host host: const { '(mouseenter)': 'onMouseEnter()', '(mouseleave)': 'onMouseLeave()' } -// #enddocregion host - ) -class Highlight { - final ElementRef _element; -// #docregion mouse-methods - onMouseEnter() { - _highlight("yellow"); - } + // #enddocregion host +) +class HighlightDirective { + // #docregion ctor + final dynamic _el; - onMouseLeave() { - _highlight(null); + HighlightDirective(ElementRef elRef) : _el = elRef.nativeElement; + // #enddocregion ctor + + // #docregion mouse-methods + void onMouseEnter() { _highlight("yellow"); } + void onMouseLeave() { _highlight(); } + + void _highlight([String color]) { + if (_el != null) _el.style.backgroundColor = color; } // #enddocregion mouse-methods - - void _highlight(String color) { - _element.nativeElement.style.backgroundColor = color; - } - -// #docregion ctor - Highlight(this._element); -// #enddocregion ctor } // #enddocregion diff --git a/public/docs/_examples/attribute-directives/ts/app/app.component.1.html b/public/docs/_examples/attribute-directives/ts/app/app.component.1.html index 177c90f5da..e5ee1c6463 100644 --- a/public/docs/_examples/attribute-directives/ts/app/app.component.1.html +++ b/public/docs/_examples/attribute-directives/ts/app/app.component.1.html @@ -1,4 +1,7 @@

My First Attribute Directive

-Highlight me! - \ No newline at end of file +

Highlight me!

+ + +

I am green with envy!

+ diff --git a/public/docs/_examples/attribute-directives/ts/app/app.component.html b/public/docs/_examples/attribute-directives/ts/app/app.component.html index 35b5d43aae..e4e445b1a8 100644 --- a/public/docs/_examples/attribute-directives/ts/app/app.component.html +++ b/public/docs/_examples/attribute-directives/ts/app/app.component.html @@ -7,10 +7,9 @@ Yellow Cyan - - +

Highlight me!

- + @@ -18,5 +17,4 @@ Highlight me too!

- - \ No newline at end of file + diff --git a/public/docs/_examples/attribute-directives/ts/app/app.component.ts b/public/docs/_examples/attribute-directives/ts/app/app.component.ts index 458e02e08e..15167310c6 100644 --- a/public/docs/_examples/attribute-directives/ts/app/app.component.ts +++ b/public/docs/_examples/attribute-directives/ts/app/app.component.ts @@ -1,6 +1,7 @@ // #docregion -import {Component} from '@angular/core'; -import {HighlightDirective} from './highlight.directive'; +import { Component } from '@angular/core'; + +import { HighlightDirective } from './highlight.directive'; @Component({ selector: 'my-app', diff --git a/public/docs/_examples/attribute-directives/ts/app/highlight.directive.1.ts b/public/docs/_examples/attribute-directives/ts/app/highlight.directive.1.ts index 3d3632272a..f8c1a95ea1 100644 --- a/public/docs/_examples/attribute-directives/ts/app/highlight.directive.1.ts +++ b/public/docs/_examples/attribute-directives/ts/app/highlight.directive.1.ts @@ -1,13 +1,9 @@ // #docregion -import {Directive, ElementRef, Input} from '@angular/core'; - -@Directive({ - selector: '[myHighlight]' -}) +import { Directive, ElementRef, Input } from '@angular/core'; +@Directive({ selector: '[myHighlight]' }) export class HighlightDirective { constructor(el: ElementRef) { el.nativeElement.style.backgroundColor = 'yellow'; } } -// #enddocregion \ No newline at end of file diff --git a/public/docs/_examples/attribute-directives/ts/app/highlight.directive.2.ts b/public/docs/_examples/attribute-directives/ts/app/highlight.directive.2.ts index 9e7abaab88..8e64391f05 100644 --- a/public/docs/_examples/attribute-directives/ts/app/highlight.directive.2.ts +++ b/public/docs/_examples/attribute-directives/ts/app/highlight.directive.2.ts @@ -1,5 +1,5 @@ // #docregion -import {Directive, ElementRef, Input} from '@angular/core'; +import { Directive, ElementRef, Input } from '@angular/core'; @Directive({ selector: '[myHighlight]', @@ -12,20 +12,20 @@ import {Directive, ElementRef, Input} from '@angular/core'; }) export class HighlightDirective { - + // #docregion ctor - private _el:HTMLElement; - constructor(el: ElementRef) { this._el = el.nativeElement; } + private el:HTMLElement; + constructor(el: ElementRef) { this.el = el.nativeElement; } // #enddocregion ctor // #docregion mouse-methods - onMouseEnter() { this._highlight("yellow"); } - onMouseLeave() { this._highlight(null); } + onMouseEnter() { this.highlight("yellow"); } + onMouseLeave() { this.highlight(null); } - private _highlight(color: string) { - this._el.style.backgroundColor = color; + private highlight(color: string) { + this.el.style.backgroundColor = color; } // #enddocregion mouse-methods } -// #enddocregion \ No newline at end of file +// #enddocregion diff --git a/public/docs/_examples/attribute-directives/ts/app/highlight.directive.ts b/public/docs/_examples/attribute-directives/ts/app/highlight.directive.ts index 2e9d68e9e1..6ec9842602 100644 --- a/public/docs/_examples/attribute-directives/ts/app/highlight.directive.ts +++ b/public/docs/_examples/attribute-directives/ts/app/highlight.directive.ts @@ -1,6 +1,6 @@ // #docplaster // #docregion full -import {Directive, ElementRef, Input} from '@angular/core'; +import { Directive, ElementRef, Input } from '@angular/core'; @Directive({ selector: '[myHighlight]', @@ -9,44 +9,38 @@ import {Directive, ElementRef, Input} from '@angular/core'; '(mouseleave)': 'onMouseLeave()' } }) - // #docregion class-1 export class HighlightDirective { - private _defaultColor = 'red'; - private _el:HTMLElement; -// #enddocregion class-1 -// #enddocregion full - /* -// #docregion highlight - @Input() myHighlight: string; -// #enddocregion highlight - */ -// #docregion full + private el: HTMLElement; + + constructor(el: ElementRef) { this.el = el.nativeElement; } + // #enddocregion class-1 -// #docregion defaultColor + // #docregion defaultColor @Input() set defaultColor(colorName:string){ this._defaultColor = colorName || this._defaultColor; } -// #enddocregion defaultColor -// #docregion class-1 + // #enddocregion defaultColor + // #docregion class-1 -// #docregion color + // #docregion color @Input('myHighlight') highlightColor: string; -// #enddocregion color + // #enddocregion color -// #enddocregion class-1 -// #docregion class-1 - constructor(el: ElementRef) { this._el = el.nativeElement; } + // #docregion mouse-enter + onMouseEnter() { this.highlight(this.highlightColor || this._defaultColor); } + // #enddocregion mouse-enter + onMouseLeave() { this.highlight(null); } -// #docregion mouse-enter - onMouseEnter() { this._highlight(this.highlightColor || this._defaultColor); } -// #enddocregion mouse-enter - onMouseLeave() { this._highlight(null); } - - private _highlight(color:string) { - this._el.style.backgroundColor = color; + private highlight(color:string) { + this.el.style.backgroundColor = color; } } // #enddocregion class-1 -// #enddocregion full \ No newline at end of file +// #enddocregion full +/* +// #docregion highlight +@Input() myHighlight: string; +// #enddocregion highlight +*/ diff --git a/public/docs/_examples/attribute-directives/ts/app/main.ts b/public/docs/_examples/attribute-directives/ts/app/main.ts index 1bb870eea0..4fc79adda1 100644 --- a/public/docs/_examples/attribute-directives/ts/app/main.ts +++ b/public/docs/_examples/attribute-directives/ts/app/main.ts @@ -1,5 +1,7 @@ // #docregion -import {bootstrap} from '@angular/platform-browser-dynamic'; -import {AppComponent} from './app.component'; +import { bootstrap } from '@angular/platform-browser-dynamic'; + +import { AppComponent } from './app.component'; bootstrap(AppComponent); + diff --git a/public/docs/_examples/attribute-directives/ts/index.html b/public/docs/_examples/attribute-directives/ts/index.html index 6bfef2480d..6988ae496a 100644 --- a/public/docs/_examples/attribute-directives/ts/index.html +++ b/public/docs/_examples/attribute-directives/ts/index.html @@ -16,13 +16,10 @@ - - loading... - diff --git a/public/docs/_examples/cb-a1-a2-quick-reference/ts/app/app.component.ts b/public/docs/_examples/cb-a1-a2-quick-reference/ts/app/app.component.ts index e8d95fe134..f2ca099297 100644 --- a/public/docs/_examples/cb-a1-a2-quick-reference/ts/app/app.component.ts +++ b/public/docs/_examples/cb-a1-a2-quick-reference/ts/app/app.component.ts @@ -1,10 +1,10 @@ -import {Component} from '@angular/core'; -import {RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS} from '@angular/router-deprecated'; +import { Component } from '@angular/core'; +import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from '@angular/router-deprecated'; -import {MovieListComponent} from './movie-list.component'; -import {MovieService} from './movie.service'; -import {IMovie} from './movie'; -import {StringSafeDatePipe} from './date.pipe'; +import { MovieListComponent } from './movie-list.component'; +import { MovieService } from './movie.service'; +import { IMovie } from './movie'; +import { StringSafeDatePipe } from './date.pipe'; @Component({ selector: 'my-app', diff --git a/public/docs/_examples/cb-a1-a2-quick-reference/ts/app/date.pipe.ts b/public/docs/_examples/cb-a1-a2-quick-reference/ts/app/date.pipe.ts index 64a5ab80e5..c04e64247d 100644 --- a/public/docs/_examples/cb-a1-a2-quick-reference/ts/app/date.pipe.ts +++ b/public/docs/_examples/cb-a1-a2-quick-reference/ts/app/date.pipe.ts @@ -1,5 +1,5 @@ -import {Injectable, Pipe} from '@angular/core'; -import {DatePipe} from '@angular/common'; +import { Injectable, Pipe } from '@angular/core'; +import { DatePipe } from '@angular/common'; @Injectable() // #docregion date-pipe diff --git a/public/docs/_examples/cb-a1-a2-quick-reference/ts/app/main.ts b/public/docs/_examples/cb-a1-a2-quick-reference/ts/app/main.ts index 38cc516baa..52b47899ef 100644 --- a/public/docs/_examples/cb-a1-a2-quick-reference/ts/app/main.ts +++ b/public/docs/_examples/cb-a1-a2-quick-reference/ts/app/main.ts @@ -1,5 +1,6 @@ // #docregion -import {bootstrap} from '@angular/platform-browser-dynamic'; -import {AppComponent} from './app.component'; +import { bootstrap } from '@angular/platform-browser-dynamic'; + +import { AppComponent } from './app.component'; bootstrap(AppComponent); diff --git a/public/docs/_examples/cb-a1-a2-quick-reference/ts/app/movie-list.component.ts b/public/docs/_examples/cb-a1-a2-quick-reference/ts/app/movie-list.component.ts index 87d99f291c..99f0699410 100644 --- a/public/docs/_examples/cb-a1-a2-quick-reference/ts/app/movie-list.component.ts +++ b/public/docs/_examples/cb-a1-a2-quick-reference/ts/app/movie-list.component.ts @@ -1,11 +1,11 @@ // #docplaster // #docregion import -import {Component} from '@angular/core'; -import {ROUTER_DIRECTIVES} from '@angular/router-deprecated'; +import { Component } from '@angular/core'; +import { ROUTER_DIRECTIVES } from '@angular/router-deprecated'; // #enddocregion import -import {MovieService} from './movie.service'; -import {IMovie} from './movie'; -import {StringSafeDatePipe} from './date.pipe'; +import { MovieService } from './movie.service'; +import { IMovie } from './movie'; +import { StringSafeDatePipe } from './date.pipe'; // #docregion component diff --git a/public/docs/_examples/cb-a1-a2-quick-reference/ts/app/movie.service.ts b/public/docs/_examples/cb-a1-a2-quick-reference/ts/app/movie.service.ts index 30d283bc68..404fd4454c 100644 --- a/public/docs/_examples/cb-a1-a2-quick-reference/ts/app/movie.service.ts +++ b/public/docs/_examples/cb-a1-a2-quick-reference/ts/app/movie.service.ts @@ -1,5 +1,6 @@ -import {Injectable} from '@angular/core'; -import {IMovie} from './movie'; +import { Injectable } from '@angular/core'; + +import { IMovie } from './movie'; @Injectable() export class MovieService { diff --git a/public/docs/_examples/cb-a1-a2-quick-reference/ts/index.html b/public/docs/_examples/cb-a1-a2-quick-reference/ts/index.html index ad1a9b93f3..f6c564313f 100644 --- a/public/docs/_examples/cb-a1-a2-quick-reference/ts/index.html +++ b/public/docs/_examples/cb-a1-a2-quick-reference/ts/index.html @@ -18,7 +18,7 @@ diff --git a/public/docs/_examples/cb-component-communication/ts/app/app.component.ts b/public/docs/_examples/cb-component-communication/ts/app/app.component.ts index 61e92738ae..c4d191b196 100644 --- a/public/docs/_examples/cb-component-communication/ts/app/app.component.ts +++ b/public/docs/_examples/cb-component-communication/ts/app/app.component.ts @@ -1,11 +1,12 @@ -import {Component} from '@angular/core'; -import {HeroParentComponent} from './hero-parent.component'; -import {NameParentComponent} from './name-parent.component'; -import {VersionParentComponent} from './version-parent.component'; -import {VoteTakerComponent} from './votetaker.component'; -import {CountdownLocalVarParentComponent, - CountdownViewChildParentComponent} from './countdown-parent.component'; -import {MissionControlComponent} from './missioncontrol.component'; +import { Component } from '@angular/core'; + +import { HeroParentComponent } from './hero-parent.component'; +import { NameParentComponent } from './name-parent.component'; +import { VersionParentComponent } from './version-parent.component'; +import { VoteTakerComponent } from './votetaker.component'; +import { CountdownLocalVarParentComponent, + CountdownViewChildParentComponent } from './countdown-parent.component'; +import { MissionControlComponent } from './missioncontrol.component'; @Component({ selector: 'app', diff --git a/public/docs/_examples/cb-component-communication/ts/app/astronaut.component.ts b/public/docs/_examples/cb-component-communication/ts/app/astronaut.component.ts index 7f8a195333..7bda2b100f 100644 --- a/public/docs/_examples/cb-component-communication/ts/app/astronaut.component.ts +++ b/public/docs/_examples/cb-component-communication/ts/app/astronaut.component.ts @@ -1,7 +1,8 @@ // #docregion -import {Component, Input, OnDestroy} from '@angular/core'; -import {MissionService} from './mission.service'; -import {Subscription} from 'rxjs/Subscription'; +import { Component, Input, OnDestroy } from '@angular/core'; + +import { MissionService } from './mission.service'; +import { Subscription } from 'rxjs/Subscription'; @Component({ selector: 'my-astronaut', diff --git a/public/docs/_examples/cb-component-communication/ts/app/countdown-parent.component.ts b/public/docs/_examples/cb-component-communication/ts/app/countdown-parent.component.ts index 8c9761a442..95425deef2 100644 --- a/public/docs/_examples/cb-component-communication/ts/app/countdown-parent.component.ts +++ b/public/docs/_examples/cb-component-communication/ts/app/countdown-parent.component.ts @@ -1,9 +1,9 @@ // #docplaster // #docregion vc -import {AfterViewInit, ViewChild} from '@angular/core'; +import { AfterViewInit, ViewChild } from '@angular/core'; // #docregion lv -import {Component} from '@angular/core'; -import {CountdownTimerComponent} from './countdown-timer.component'; +import { Component } from '@angular/core'; +import { CountdownTimerComponent } from './countdown-timer.component'; // #enddocregion lv // #enddocregion vc @@ -42,7 +42,7 @@ export class CountdownLocalVarParentComponent { } export class CountdownViewChildParentComponent implements AfterViewInit { @ViewChild(CountdownTimerComponent) - private _timerComponent:CountdownTimerComponent; + private timerComponent:CountdownTimerComponent; seconds() { return 0; } @@ -50,10 +50,10 @@ export class CountdownViewChildParentComponent implements AfterViewInit { // Redefine `seconds()` to get from the `CountdownTimerComponent.seconds` ... // but wait a tick first to avoid one-time devMode // unidirectional-data-flow-violation error - setTimeout(() => this.seconds = () => this._timerComponent.seconds, 0) + setTimeout(() => this.seconds = () => this.timerComponent.seconds, 0) } - start(){ this._timerComponent.start(); } - stop() { this._timerComponent.stop(); } + start(){ this.timerComponent.start(); } + stop() { this.timerComponent.stop(); } } // #enddocregion vc diff --git a/public/docs/_examples/cb-component-communication/ts/app/countdown-timer.component.ts b/public/docs/_examples/cb-component-communication/ts/app/countdown-timer.component.ts index efd294685c..83f5751d5b 100644 --- a/public/docs/_examples/cb-component-communication/ts/app/countdown-timer.component.ts +++ b/public/docs/_examples/cb-component-communication/ts/app/countdown-timer.component.ts @@ -1,5 +1,5 @@ // #docregion -import {Component, OnInit, OnDestroy} from '@angular/core'; +import { Component, OnDestroy, OnInit } from '@angular/core'; @Component({ selector:'countdown-timer', @@ -16,13 +16,13 @@ export class CountdownTimerComponent implements OnInit, OnDestroy { ngOnInit() { this.start(); } ngOnDestroy() { this.clearTimer(); } - start() { this._countDown(); } + start() { this.countDown(); } stop() { this.clearTimer(); this.message = `Holding at T-${this.seconds} seconds`; } - private _countDown() { + private countDown() { this.clearTimer(); this.intervalId = setInterval(()=>{ this.seconds -= 1; @@ -34,4 +34,4 @@ export class CountdownTimerComponent implements OnInit, OnDestroy { } }, 1000); } -} \ No newline at end of file +} diff --git a/public/docs/_examples/cb-component-communication/ts/app/hero-child.component.ts b/public/docs/_examples/cb-component-communication/ts/app/hero-child.component.ts index c33ce43826..7447542a74 100644 --- a/public/docs/_examples/cb-component-communication/ts/app/hero-child.component.ts +++ b/public/docs/_examples/cb-component-communication/ts/app/hero-child.component.ts @@ -1,6 +1,7 @@ // #docregion -import {Component, Input} from '@angular/core'; -import {Hero} from './hero'; +import { Component, Input } from '@angular/core'; + +import { Hero } from './hero'; @Component({ selector: 'hero-child', diff --git a/public/docs/_examples/cb-component-communication/ts/app/hero-parent.component.ts b/public/docs/_examples/cb-component-communication/ts/app/hero-parent.component.ts index ef9544c472..6d82f53a4d 100644 --- a/public/docs/_examples/cb-component-communication/ts/app/hero-parent.component.ts +++ b/public/docs/_examples/cb-component-communication/ts/app/hero-parent.component.ts @@ -1,7 +1,8 @@ // #docregion -import {Component} from '@angular/core'; -import {HeroChildComponent} from './hero-child.component'; -import {HEROES} from './hero'; +import { Component } from '@angular/core'; + +import { HeroChildComponent } from './hero-child.component'; +import { HEROES } from './hero'; @Component({ selector: 'hero-parent', diff --git a/public/docs/_examples/cb-component-communication/ts/app/main.ts b/public/docs/_examples/cb-component-communication/ts/app/main.ts index d14f9ff611..9451f9b495 100644 --- a/public/docs/_examples/cb-component-communication/ts/app/main.ts +++ b/public/docs/_examples/cb-component-communication/ts/app/main.ts @@ -1,4 +1,5 @@ -import {bootstrap} from '@angular/platform-browser-dynamic'; -import {AppComponent} from './app.component'; +import { bootstrap } from '@angular/platform-browser-dynamic'; + +import { AppComponent } from './app.component'; bootstrap(AppComponent); \ No newline at end of file diff --git a/public/docs/_examples/cb-component-communication/ts/app/mission.service.ts b/public/docs/_examples/cb-component-communication/ts/app/mission.service.ts index e754acc1cc..0c284389b6 100644 --- a/public/docs/_examples/cb-component-communication/ts/app/mission.service.ts +++ b/public/docs/_examples/cb-component-communication/ts/app/mission.service.ts @@ -1,25 +1,25 @@ // #docregion -import {Injectable} from '@angular/core' -import {Subject} from 'rxjs/Subject'; +import { Injectable } from '@angular/core' +import { Subject } from 'rxjs/Subject'; @Injectable() export class MissionService { // Observable string sources - private _missionAnnouncedSource = new Subject(); - private _missionConfirmedSource = new Subject(); + private missionAnnouncedSource = new Subject(); + private missionConfirmedSource = new Subject(); // Observable string streams - missionAnnounced$ = this._missionAnnouncedSource.asObservable(); - missionConfirmed$ = this._missionConfirmedSource.asObservable(); + missionAnnounced$ = this.missionAnnouncedSource.asObservable(); + missionConfirmed$ = this.missionConfirmedSource.asObservable(); // Service message commands announceMission(mission: string) { - this._missionAnnouncedSource.next(mission) + this.missionAnnouncedSource.next(mission) } confirmMission(astronaut: string) { - this._missionConfirmedSource.next(astronaut); + this.missionConfirmedSource.next(astronaut); } } // #enddocregion diff --git a/public/docs/_examples/cb-component-communication/ts/app/missioncontrol.component.ts b/public/docs/_examples/cb-component-communication/ts/app/missioncontrol.component.ts index de13aef360..eff2b229c9 100644 --- a/public/docs/_examples/cb-component-communication/ts/app/missioncontrol.component.ts +++ b/public/docs/_examples/cb-component-communication/ts/app/missioncontrol.component.ts @@ -1,7 +1,8 @@ // #docregion -import {Component} from '@angular/core'; -import {AstronautComponent} from './astronaut.component'; -import {MissionService} from './mission.service'; +import { Component } from '@angular/core'; + +import { AstronautComponent } from './astronaut.component'; +import { MissionService } from './mission.service'; @Component({ selector: 'mission-control', @@ -41,4 +42,4 @@ export class MissionControlComponent { if (this.nextMission >= this.missions.length) { this.nextMission = 0; } } } -// #enddocregion \ No newline at end of file +// #enddocregion diff --git a/public/docs/_examples/cb-component-communication/ts/app/name-child.component.ts b/public/docs/_examples/cb-component-communication/ts/app/name-child.component.ts index 366a54345d..8e826075b0 100644 --- a/public/docs/_examples/cb-component-communication/ts/app/name-child.component.ts +++ b/public/docs/_examples/cb-component-communication/ts/app/name-child.component.ts @@ -1,5 +1,5 @@ // #docregion -import {Component, Input} from '@angular/core'; +import { Component, Input } from '@angular/core'; @Component({ selector: 'name-child', diff --git a/public/docs/_examples/cb-component-communication/ts/app/name-parent.component.ts b/public/docs/_examples/cb-component-communication/ts/app/name-parent.component.ts index 16a3fbe4a6..aa7382503a 100644 --- a/public/docs/_examples/cb-component-communication/ts/app/name-parent.component.ts +++ b/public/docs/_examples/cb-component-communication/ts/app/name-parent.component.ts @@ -1,6 +1,7 @@ // #docregion -import {Component} from '@angular/core'; -import {NameChildComponent} from './name-child.component'; +import { Component } from '@angular/core'; + +import { NameChildComponent } from './name-child.component'; @Component({ selector: 'name-parent', diff --git a/public/docs/_examples/cb-component-communication/ts/app/version-child.component.ts b/public/docs/_examples/cb-component-communication/ts/app/version-child.component.ts index 3d5a8a56e7..91f5d547f7 100644 --- a/public/docs/_examples/cb-component-communication/ts/app/version-child.component.ts +++ b/public/docs/_examples/cb-component-communication/ts/app/version-child.component.ts @@ -1,6 +1,6 @@ /* tslint:disable:forin */ // #docregion -import {Component, Input, OnChanges, SimpleChange} from '@angular/core'; +import { Component, Input, OnChanges, SimpleChange } from '@angular/core'; @Component({ selector: 'version-child', diff --git a/public/docs/_examples/cb-component-communication/ts/app/version-parent.component.ts b/public/docs/_examples/cb-component-communication/ts/app/version-parent.component.ts index 8357f97a82..cdb590b87a 100644 --- a/public/docs/_examples/cb-component-communication/ts/app/version-parent.component.ts +++ b/public/docs/_examples/cb-component-communication/ts/app/version-parent.component.ts @@ -1,6 +1,7 @@ // #docregion -import {Component} from '@angular/core'; -import {VersionChildComponent} from './version-child.component'; +import { Component } from '@angular/core'; + +import { VersionChildComponent } from './version-child.component'; @Component({ selector: 'version-parent', diff --git a/public/docs/_examples/cb-component-communication/ts/app/voter.component.ts b/public/docs/_examples/cb-component-communication/ts/app/voter.component.ts index 14a99665e3..c68409a73a 100644 --- a/public/docs/_examples/cb-component-communication/ts/app/voter.component.ts +++ b/public/docs/_examples/cb-component-communication/ts/app/voter.component.ts @@ -1,5 +1,5 @@ // #docregion -import {Component, EventEmitter, Input, Output} from '@angular/core'; +import { Component, EventEmitter, Input, Output } from '@angular/core'; @Component({ selector: 'my-voter', diff --git a/public/docs/_examples/cb-component-communication/ts/app/votetaker.component.ts b/public/docs/_examples/cb-component-communication/ts/app/votetaker.component.ts index 1101e8a8f7..3e2970b691 100644 --- a/public/docs/_examples/cb-component-communication/ts/app/votetaker.component.ts +++ b/public/docs/_examples/cb-component-communication/ts/app/votetaker.component.ts @@ -1,6 +1,7 @@ // #docregion -import {Component} from '@angular/core'; -import {VoterComponent} from './voter.component'; +import { Component } from '@angular/core'; + +import { VoterComponent } from './voter.component'; @Component({ selector: 'vote-taker', diff --git a/public/docs/_examples/cb-component-communication/ts/index.html b/public/docs/_examples/cb-component-communication/ts/index.html index ac9730a939..20c75e04a5 100644 --- a/public/docs/_examples/cb-component-communication/ts/index.html +++ b/public/docs/_examples/cb-component-communication/ts/index.html @@ -18,7 +18,7 @@ diff --git a/public/docs/_examples/cb-dependency-injection/ts/app/date-logger.service.ts b/public/docs/_examples/cb-dependency-injection/ts/app/date-logger.service.ts index 67ccbbee30..e5b597db02 100644 --- a/public/docs/_examples/cb-dependency-injection/ts/app/date-logger.service.ts +++ b/public/docs/_examples/cb-dependency-injection/ts/app/date-logger.service.ts @@ -1,6 +1,7 @@ /* tslint:disable:one-line:check-open-brace*/ // #docregion import { Injectable } from '@angular/core'; + import { LoggerService } from './logger.service'; // #docregion minimal-logger diff --git a/public/docs/_examples/cb-dependency-injection/ts/app/hero-bio.component.ts b/public/docs/_examples/cb-dependency-injection/ts/app/hero-bio.component.ts index 840ca07c09..b4d122bfe4 100644 --- a/public/docs/_examples/cb-dependency-injection/ts/app/hero-bio.component.ts +++ b/public/docs/_examples/cb-dependency-injection/ts/app/hero-bio.component.ts @@ -1,8 +1,8 @@ // #docregion -import {Component, Input, OnInit} from '@angular/core'; +import { Component, Input, OnInit } from '@angular/core'; -import {Hero} from './hero'; -import {HeroCacheService} from './hero-cache.service'; +import { Hero } from './hero'; +import { HeroCacheService } from './hero-cache.service'; // #docregion component @Component({ @@ -20,10 +20,10 @@ export class HeroBioComponent implements OnInit { @Input() heroId:number; - constructor(private _heroCache:HeroCacheService) { } + constructor(private heroCache:HeroCacheService) { } - ngOnInit() { this._heroCache.fetchCachedHero(this.heroId); } + ngOnInit() { this.heroCache.fetchCachedHero(this.heroId); } - get hero() { return this._heroCache.hero; } + get hero() { return this.heroCache.hero; } } // #enddocregion component diff --git a/public/docs/_examples/cb-dependency-injection/ts/app/hero-cache.service.ts b/public/docs/_examples/cb-dependency-injection/ts/app/hero-cache.service.ts index 0f7f48c910..c8e6104666 100644 --- a/public/docs/_examples/cb-dependency-injection/ts/app/hero-cache.service.ts +++ b/public/docs/_examples/cb-dependency-injection/ts/app/hero-cache.service.ts @@ -1,17 +1,18 @@ // #docregion -import {Injectable} from '@angular/core'; -import {Hero} from './hero'; -import {HeroService} from './hero.service'; +import { Injectable } from '@angular/core'; + +import { Hero } from './hero'; +import { HeroService } from './hero.service'; // #docregion service @Injectable() export class HeroCacheService { hero:Hero; - constructor(private _heroService:HeroService){} + constructor(private heroService:HeroService){} fetchCachedHero(id:number){ if (!this.hero) { - this.hero = this._heroService.getHeroById(id); + this.hero = this.heroService.getHeroById(id); } return this.hero } diff --git a/public/docs/_examples/cb-dependency-injection/ts/app/hero-contact.component.ts b/public/docs/_examples/cb-dependency-injection/ts/app/hero-contact.component.ts index acccaaae2b..a91f01b104 100644 --- a/public/docs/_examples/cb-dependency-injection/ts/app/hero-contact.component.ts +++ b/public/docs/_examples/cb-dependency-injection/ts/app/hero-contact.component.ts @@ -1,8 +1,9 @@ // #docplaster // #docregion -import {Component, ElementRef, Host, Inject, Optional} from '@angular/core'; -import {HeroCacheService} from './hero-cache.service'; -import {LoggerService} from './logger.service'; +import { Component, ElementRef, Host, Inject, Optional } from '@angular/core'; + +import { HeroCacheService } from './hero-cache.service'; +import { LoggerService } from './logger.service'; // #docregion component @Component({ @@ -18,22 +19,22 @@ export class HeroContactComponent { constructor( // #docregion ctor-params @Host() // limit to the host component's instance of the HeroCacheService - private _heroCache: HeroCacheService, + private heroCache: HeroCacheService, @Host() // limit search for logger; hides the application-wide logger @Optional() // ok if the logger doesn't exist - private _loggerService: LoggerService + private loggerService: LoggerService // #enddocregion ctor-params ) { - if (_loggerService) { + if (loggerService) { this.hasLogger = true; - _loggerService.logInfo('HeroContactComponent can log!'); + loggerService.logInfo('HeroContactComponent can log!'); } // #docregion ctor } // #enddocregion ctor - get phoneNumber() { return this._heroCache.hero.phone; } + get phoneNumber() { return this.heroCache.hero.phone; } } // #enddocregion component diff --git a/public/docs/_examples/cb-dependency-injection/ts/app/hero-data.ts b/public/docs/_examples/cb-dependency-injection/ts/app/hero-data.ts index 18133fd771..decccdbf72 100644 --- a/public/docs/_examples/cb-dependency-injection/ts/app/hero-data.ts +++ b/public/docs/_examples/cb-dependency-injection/ts/app/hero-data.ts @@ -1,5 +1,5 @@ // #docregion -import {Hero} from './hero'; +import { Hero } from './hero'; export class HeroData { createDb() { diff --git a/public/docs/_examples/cb-dependency-injection/ts/app/hero-of-the-month.component.ts b/public/docs/_examples/cb-dependency-injection/ts/app/hero-of-the-month.component.ts index 2a27906215..6b9646d3e9 100644 --- a/public/docs/_examples/cb-dependency-injection/ts/app/hero-of-the-month.component.ts +++ b/public/docs/_examples/cb-dependency-injection/ts/app/hero-of-the-month.component.ts @@ -1,7 +1,7 @@ /* tslint:disable:one-line:check-open-brace*/ // #docplaster // #docregion opaque-token -import {OpaqueToken} from '@angular/core'; +import { OpaqueToken } from '@angular/core'; export const TITLE = new OpaqueToken('title'); // #enddocregion opaque-token diff --git a/public/docs/_examples/cb-dependency-injection/ts/app/hero.service.ts b/public/docs/_examples/cb-dependency-injection/ts/app/hero.service.ts index 108ee56eb6..0222f6cd32 100644 --- a/public/docs/_examples/cb-dependency-injection/ts/app/hero.service.ts +++ b/public/docs/_examples/cb-dependency-injection/ts/app/hero.service.ts @@ -1,22 +1,22 @@ // #docregion -import {Injectable} from '@angular/core'; -import {Hero} from './hero'; +import { Injectable } from '@angular/core'; +import { Hero } from './hero'; @Injectable() export class HeroService { //TODO move to database - private _heroes:Array = [ + private heroes:Array = [ new Hero(1, 'RubberMan','Hero of many talents', '123-456-7899'), new Hero(2, 'Magma','Hero of all trades', '555-555-5555'), new Hero(3, 'Mr. Nice','The name says it all','111-222-3333') ]; getHeroById(id:number):Hero{ - return this._heroes.filter(hero => hero.id === id)[0]; + return this.heroes.filter(hero => hero.id === id)[0]; } getAllHeroes():Array{ - return this._heroes; + return this.heroes; } } diff --git a/public/docs/_examples/cb-dependency-injection/ts/app/highlight.directive.ts b/public/docs/_examples/cb-dependency-injection/ts/app/highlight.directive.ts index 66e4a2df90..69bd1a1577 100644 --- a/public/docs/_examples/cb-dependency-injection/ts/app/highlight.directive.ts +++ b/public/docs/_examples/cb-dependency-injection/ts/app/highlight.directive.ts @@ -1,6 +1,6 @@ // #docplaster // #docregion -import {Directive, ElementRef, Input} from '@angular/core'; +import { Directive, ElementRef, Input } from '@angular/core'; @Directive({ selector: '[myHighlight]', @@ -13,16 +13,16 @@ export class HighlightDirective { @Input('myHighlight') highlightColor: string; - private _el: HTMLElement; + private el: HTMLElement; constructor(el: ElementRef) { - this._el = el.nativeElement; + this.el = el.nativeElement; } - onMouseEnter() { this._highlight(this.highlightColor || 'cyan'); } - onMouseLeave() { this._highlight(null); } + onMouseEnter() { this.highlight(this.highlightColor || 'cyan'); } + onMouseLeave() { this.highlight(null); } - private _highlight(color: string) { - this._el.style.backgroundColor = color; + private highlight(color: string) { + this.el.style.backgroundColor = color; } } diff --git a/public/docs/_examples/cb-dependency-injection/ts/app/logger.service.ts b/public/docs/_examples/cb-dependency-injection/ts/app/logger.service.ts index bf609d9819..df8ee6b9c7 100644 --- a/public/docs/_examples/cb-dependency-injection/ts/app/logger.service.ts +++ b/public/docs/_examples/cb-dependency-injection/ts/app/logger.service.ts @@ -1,5 +1,5 @@ // #docregion -import {Injectable} from '@angular/core'; +import { Injectable } from '@angular/core'; @Injectable() export class LoggerService { diff --git a/public/docs/_examples/cb-dependency-injection/ts/app/main.ts b/public/docs/_examples/cb-dependency-injection/ts/app/main.ts index f26f41a7e5..508177e81b 100644 --- a/public/docs/_examples/cb-dependency-injection/ts/app/main.ts +++ b/public/docs/_examples/cb-dependency-injection/ts/app/main.ts @@ -2,9 +2,7 @@ import { bootstrap } from '@angular/platform-browser-dynamic'; import { provide } from '@angular/core'; import { XHRBackend } from '@angular/http'; - import { ROUTER_PROVIDERS } from '@angular/router-deprecated'; - import { LocationStrategy, HashLocationStrategy } from '@angular/common'; diff --git a/public/docs/_examples/cb-dependency-injection/ts/app/runners-up.ts b/public/docs/_examples/cb-dependency-injection/ts/app/runners-up.ts index 4105c1fbcb..0bc3069883 100644 --- a/public/docs/_examples/cb-dependency-injection/ts/app/runners-up.ts +++ b/public/docs/_examples/cb-dependency-injection/ts/app/runners-up.ts @@ -1,8 +1,9 @@ // #docplaster // #docregion -import {OpaqueToken} from '@angular/core'; -import {Hero} from './hero'; -import {HeroService} from './hero.service'; +import { OpaqueToken } from '@angular/core'; + +import { Hero } from './hero'; +import { HeroService } from './hero.service'; // #docregion runners-up export const RUNNERS_UP = new OpaqueToken('RunnersUp'); diff --git a/public/docs/_examples/cb-dependency-injection/ts/app/sorted-heroes.component.ts b/public/docs/_examples/cb-dependency-injection/ts/app/sorted-heroes.component.ts index ac236e3e12..8cb6e3c69c 100644 --- a/public/docs/_examples/cb-dependency-injection/ts/app/sorted-heroes.component.ts +++ b/public/docs/_examples/cb-dependency-injection/ts/app/sorted-heroes.component.ts @@ -1,8 +1,9 @@ // #docplaster // #docregion -import {Component, OnInit} from '@angular/core'; -import {Hero} from './hero'; -import {HeroService} from './hero.service'; +import { Component, OnInit } from '@angular/core'; + +import { Hero } from './hero'; +import { HeroService } from './hero.service'; /////// HeroesBaseComponent ///// // #docregion heroes-base, injection @@ -12,18 +13,18 @@ import {HeroService} from './hero.service'; providers: [HeroService] }) export class HeroesBaseComponent implements OnInit { - constructor(private _heroService: HeroService) { } + constructor(private heroService: HeroService) { } // #enddocregion injection heroes: Array; ngOnInit() { - this.heroes = this._heroService.getAllHeroes(); - this._afterGetHeroes(); + this.heroes = this.heroService.getAllHeroes(); + this.afterGetHeroes(); } // Post-process heroes in derived class override. - protected _afterGetHeroes() {} + protected afterGetHeroes() {} // #docregion injection } @@ -41,7 +42,7 @@ export class SortedHeroesComponent extends HeroesBaseComponent { super(heroService); } - protected _afterGetHeroes() { + protected afterGetHeroes() { this.heroes = this.heroes.sort((h1, h2) => { return h1.name < h2.name ? -1 : (h1.name > h2.name ? 1 : 0); diff --git a/public/docs/_examples/cb-dependency-injection/ts/app/user-context.service.ts b/public/docs/_examples/cb-dependency-injection/ts/app/user-context.service.ts index c03b768b40..782e65043d 100644 --- a/public/docs/_examples/cb-dependency-injection/ts/app/user-context.service.ts +++ b/public/docs/_examples/cb-dependency-injection/ts/app/user-context.service.ts @@ -1,8 +1,9 @@ // #docplaster // #docregion -import {Injectable} from '@angular/core'; -import {LoggerService} from './logger.service'; -import {UserService} from './user.service'; +import { Injectable } from '@angular/core'; + +import { LoggerService } from './logger.service'; +import { UserService } from './user.service'; // #docregion injectables, injectable @Injectable() @@ -13,7 +14,7 @@ export class UserContextService { loggedInSince:Date; // #docregion ctor, injectables - constructor(private _userService:UserService, private _loggerService:LoggerService){ + constructor(private userService:UserService, private loggerService:LoggerService){ // #enddocregion ctor, injectables this.loggedInSince = new Date(); // #docregion ctor, injectables @@ -21,11 +22,11 @@ export class UserContextService { // #enddocregion ctor, injectables loadUser(userId:number){ - let user = this._userService.getUserById(userId); + let user = this.userService.getUserById(userId); this.name = user.name; this.role = user.role; - this._loggerService.logDebug('loaded User'); + this.loggerService.logDebug('loaded User'); } // #docregion injectables, injectable } diff --git a/public/docs/_examples/cb-dependency-injection/ts/app/user.service.ts b/public/docs/_examples/cb-dependency-injection/ts/app/user.service.ts index 8c2e191ec2..d4ca4fda2a 100644 --- a/public/docs/_examples/cb-dependency-injection/ts/app/user.service.ts +++ b/public/docs/_examples/cb-dependency-injection/ts/app/user.service.ts @@ -1,5 +1,5 @@ // #docregion -import {Injectable} from '@angular/core'; +import { Injectable } from '@angular/core'; @Injectable() export class UserService { @@ -7,4 +7,4 @@ export class UserService { getUserById(userId:number):any{ return {name:'Bombasto',role:'Admin'}; } -} \ No newline at end of file +} diff --git a/public/docs/_examples/cb-dependency-injection/ts/index.html b/public/docs/_examples/cb-dependency-injection/ts/index.html index 0ad85b5a5e..744fd81a26 100644 --- a/public/docs/_examples/cb-dependency-injection/ts/index.html +++ b/public/docs/_examples/cb-dependency-injection/ts/index.html @@ -19,7 +19,7 @@ diff --git a/public/docs/_examples/cb-dynamic-form/ts/app/app.component.ts b/public/docs/_examples/cb-dynamic-form/ts/app/app.component.ts index 86c7a786e6..01a5401003 100644 --- a/public/docs/_examples/cb-dynamic-form/ts/app/app.component.ts +++ b/public/docs/_examples/cb-dynamic-form/ts/app/app.component.ts @@ -1,7 +1,8 @@ // #docregion -import {Component} from '@angular/core' -import {DynamicForm} from './dynamic-form.component'; -import {QuestionService} from './question.service'; +import { Component } from '@angular/core' + +import { DynamicForm } from './dynamic-form.component'; +import { QuestionService } from './question.service'; @Component({ selector: 'my-app', diff --git a/public/docs/_examples/cb-dynamic-form/ts/app/dynamic-form-question.component.ts b/public/docs/_examples/cb-dynamic-form/ts/app/dynamic-form-question.component.ts index 2ffee4c636..d039931f61 100644 --- a/public/docs/_examples/cb-dynamic-form/ts/app/dynamic-form-question.component.ts +++ b/public/docs/_examples/cb-dynamic-form/ts/app/dynamic-form-question.component.ts @@ -1,7 +1,8 @@ // #docregion -import {Component, Input} from '@angular/core'; -import {ControlGroup} from '@angular/common'; -import {QuestionBase} from './question-base'; +import { Component, Input } from '@angular/core'; +import { ControlGroup } from '@angular/common'; + +import { QuestionBase } from './question-base'; @Component({ selector:'df-question', diff --git a/public/docs/_examples/cb-dynamic-form/ts/app/dynamic-form.component.ts b/public/docs/_examples/cb-dynamic-form/ts/app/dynamic-form.component.ts index 486179acc9..68aafc839b 100644 --- a/public/docs/_examples/cb-dynamic-form/ts/app/dynamic-form.component.ts +++ b/public/docs/_examples/cb-dynamic-form/ts/app/dynamic-form.component.ts @@ -1,10 +1,10 @@ // #docregion -import {Component, Input, OnInit} from '@angular/core'; -import {ControlGroup} from '@angular/common'; +import { Component, Input, OnInit } from '@angular/core'; +import { ControlGroup } from '@angular/common'; -import {QuestionBase} from './question-base'; -import {QuestionControlService} from './question-control.service'; -import {DynamicFormQuestionComponent} from './dynamic-form-question.component'; +import { QuestionBase } from './question-base'; +import { QuestionControlService } from './question-control.service'; +import { DynamicFormQuestionComponent } from './dynamic-form-question.component'; @Component({ selector:'dynamic-form', @@ -18,10 +18,10 @@ export class DynamicForm { form: ControlGroup; payLoad = ''; - constructor(private _qcs: QuestionControlService) { } + constructor(private qcs: QuestionControlService) { } ngOnInit(){ - this.form = this._qcs.toControlGroup(this.questions); + this.form = this.qcs.toControlGroup(this.questions); } onSubmit() { diff --git a/public/docs/_examples/cb-dynamic-form/ts/app/main.ts b/public/docs/_examples/cb-dynamic-form/ts/app/main.ts index 23bf0638ee..aca0a06056 100644 --- a/public/docs/_examples/cb-dynamic-form/ts/app/main.ts +++ b/public/docs/_examples/cb-dynamic-form/ts/app/main.ts @@ -1,5 +1,6 @@ -import {bootstrap} from '@angular/platform-browser-dynamic'; -import {AppComponent} from './app.component'; +import { bootstrap } from '@angular/platform-browser-dynamic'; + +import { AppComponent } from './app.component'; bootstrap(AppComponent, []) .catch((err:any) => console.error(err)); diff --git a/public/docs/_examples/cb-dynamic-form/ts/app/question-control.service.ts b/public/docs/_examples/cb-dynamic-form/ts/app/question-control.service.ts index efc30b7add..d4cf25951c 100644 --- a/public/docs/_examples/cb-dynamic-form/ts/app/question-control.service.ts +++ b/public/docs/_examples/cb-dynamic-form/ts/app/question-control.service.ts @@ -1,18 +1,18 @@ // #docregion -import {Injectable} from '@angular/core'; -import {ControlGroup, FormBuilder, Validators} from '@angular/common'; -import {QuestionBase} from './question-base'; +import { Injectable } from '@angular/core'; +import { ControlGroup, FormBuilder, Validators } from '@angular/common'; +import { QuestionBase } from './question-base'; @Injectable() export class QuestionControlService { - constructor(private _fb:FormBuilder){ } + constructor(private fb:FormBuilder){ } toControlGroup(questions:QuestionBase[] ) { let group = {}; questions.forEach(question => { - group[question.key] = question.required ? [question.value || '', Validators.required] : []; + group[question.key] = question.required ? [question.value || '', Validators.required] : [question.value || '']; }); - return this._fb.group(group); + return this.fb.group(group); } } diff --git a/public/docs/_examples/cb-dynamic-form/ts/app/question-dropdown.ts b/public/docs/_examples/cb-dynamic-form/ts/app/question-dropdown.ts index 1c3ca2807a..50b5d64a1d 100644 --- a/public/docs/_examples/cb-dynamic-form/ts/app/question-dropdown.ts +++ b/public/docs/_examples/cb-dynamic-form/ts/app/question-dropdown.ts @@ -1,5 +1,5 @@ // #docregion -import {QuestionBase} from './question-base'; +import { QuestionBase } from './question-base'; export class DropdownQuestion extends QuestionBase{ controlType = 'dropdown'; diff --git a/public/docs/_examples/cb-dynamic-form/ts/app/question-textbox.ts b/public/docs/_examples/cb-dynamic-form/ts/app/question-textbox.ts index 573209d944..a1c9980de5 100644 --- a/public/docs/_examples/cb-dynamic-form/ts/app/question-textbox.ts +++ b/public/docs/_examples/cb-dynamic-form/ts/app/question-textbox.ts @@ -1,5 +1,5 @@ // #docregion -import {QuestionBase} from './question-base'; +import { QuestionBase } from './question-base'; export class TextboxQuestion extends QuestionBase{ controlType = 'textbox'; diff --git a/public/docs/_examples/cb-dynamic-form/ts/app/question.service.ts b/public/docs/_examples/cb-dynamic-form/ts/app/question.service.ts index 7350e55dd8..52b4fc70ff 100644 --- a/public/docs/_examples/cb-dynamic-form/ts/app/question.service.ts +++ b/public/docs/_examples/cb-dynamic-form/ts/app/question.service.ts @@ -1,9 +1,10 @@ // #docregion -import {Injectable} from '@angular/core'; -import {QuestionBase} from './question-base'; -import {DynamicForm} from './dynamic-form.component'; -import {TextboxQuestion} from './question-textbox'; -import {DropdownQuestion} from './question-dropdown'; +import { Injectable } from '@angular/core'; + +import { QuestionBase } from './question-base'; +import { DynamicForm } from './dynamic-form.component'; +import { TextboxQuestion } from './question-textbox'; +import { DropdownQuestion } from './question-dropdown'; @Injectable() export class QuestionService { diff --git a/public/docs/_examples/cb-dynamic-form/ts/index.html b/public/docs/_examples/cb-dynamic-form/ts/index.html index da7eef68e9..33998c478e 100644 --- a/public/docs/_examples/cb-dynamic-form/ts/index.html +++ b/public/docs/_examples/cb-dynamic-form/ts/index.html @@ -19,7 +19,7 @@ diff --git a/public/docs/_examples/cb-set-document-title/ts/app/app.component.ts b/public/docs/_examples/cb-set-document-title/ts/app/app.component.ts index 09ed0d77c1..f1905e635d 100644 --- a/public/docs/_examples/cb-set-document-title/ts/app/app.component.ts +++ b/public/docs/_examples/cb-set-document-title/ts/app/app.component.ts @@ -20,10 +20,10 @@ template: }) // #docregion class export class AppComponent { - public constructor(private _titleService: Title ) { } + public constructor(private titleService: Title ) { } public setTitle( newTitle: string) { - this._titleService.setTitle( newTitle ); + this.titleService.setTitle( newTitle ); } } // #enddocregion class diff --git a/public/docs/_examples/cb-set-document-title/ts/app/main.ts b/public/docs/_examples/cb-set-document-title/ts/app/main.ts index f81cd0e262..c5134d3214 100644 --- a/public/docs/_examples/cb-set-document-title/ts/app/main.ts +++ b/public/docs/_examples/cb-set-document-title/ts/app/main.ts @@ -1,5 +1,6 @@ // #docregion import { bootstrap } from '@angular/platform-browser-dynamic'; + import { AppComponent } from './app.component'; // While Angular supplies a Title service for setting the HTML document title diff --git a/public/docs/_examples/cb-ts-to-js/ts/app/data.service.ts b/public/docs/_examples/cb-ts-to-js/ts/app/data.service.ts index efeb0b27b3..7e9c7456c6 100644 --- a/public/docs/_examples/cb-ts-to-js/ts/app/data.service.ts +++ b/public/docs/_examples/cb-ts-to-js/ts/app/data.service.ts @@ -1,4 +1,4 @@ -import {Injectable} from '@angular/core'; +import { Injectable } from '@angular/core'; @Injectable() export class DataService { diff --git a/public/docs/_examples/cb-ts-to-js/ts/app/hero-di-inject.component.ts b/public/docs/_examples/cb-ts-to-js/ts/app/hero-di-inject.component.ts index 1b07042a28..5d78a5cbbf 100644 --- a/public/docs/_examples/cb-ts-to-js/ts/app/hero-di-inject.component.ts +++ b/public/docs/_examples/cb-ts-to-js/ts/app/hero-di-inject.component.ts @@ -1,4 +1,4 @@ -import {Component, Inject} from '@angular/core'; +import { Component, Inject } from '@angular/core'; // #docregion @Component({ diff --git a/public/docs/_examples/cb-ts-to-js/ts/app/hero-di.component.ts b/public/docs/_examples/cb-ts-to-js/ts/app/hero-di.component.ts index e0d51596e4..e6b81b6af7 100644 --- a/public/docs/_examples/cb-ts-to-js/ts/app/hero-di.component.ts +++ b/public/docs/_examples/cb-ts-to-js/ts/app/hero-di.component.ts @@ -1,5 +1,6 @@ -import {Component} from '@angular/core'; -import {DataService} from './data.service'; +import { Component } from '@angular/core'; + +import { DataService } from './data.service'; // #docregion @Component({ diff --git a/public/docs/_examples/cb-ts-to-js/ts/app/hero-io.component.ts b/public/docs/_examples/cb-ts-to-js/ts/app/hero-io.component.ts index 7c0ab6e76d..936bf2854e 100644 --- a/public/docs/_examples/cb-ts-to-js/ts/app/hero-io.component.ts +++ b/public/docs/_examples/cb-ts-to-js/ts/app/hero-io.component.ts @@ -1,4 +1,4 @@ -import {Component, EventEmitter, Input, Output} from '@angular/core'; +import { Component, EventEmitter, Input, Output } from '@angular/core'; // #docregion @Component({ diff --git a/public/docs/_examples/cb-ts-to-js/ts/app/hero-lifecycle.component.ts b/public/docs/_examples/cb-ts-to-js/ts/app/hero-lifecycle.component.ts index a87c895a11..94d79274fc 100644 --- a/public/docs/_examples/cb-ts-to-js/ts/app/hero-lifecycle.component.ts +++ b/public/docs/_examples/cb-ts-to-js/ts/app/hero-lifecycle.component.ts @@ -1,6 +1,6 @@ // #docplaster // #docregion -import {Component, OnInit} +import { Component, OnInit } from '@angular/core'; // #enddocregion diff --git a/public/docs/_examples/cb-ts-to-js/ts/app/hero.component.ts b/public/docs/_examples/cb-ts-to-js/ts/app/hero.component.ts index 10c644bcb6..85d2772c63 100644 --- a/public/docs/_examples/cb-ts-to-js/ts/app/hero.component.ts +++ b/public/docs/_examples/cb-ts-to-js/ts/app/hero.component.ts @@ -1,6 +1,6 @@ // #docplaster // #docregion metadata -import {Component} from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'hero-view', diff --git a/public/docs/_examples/cb-ts-to-js/ts/app/heroes-bindings.component.ts b/public/docs/_examples/cb-ts-to-js/ts/app/heroes-bindings.component.ts index 6fb4347298..317d434b9d 100644 --- a/public/docs/_examples/cb-ts-to-js/ts/app/heroes-bindings.component.ts +++ b/public/docs/_examples/cb-ts-to-js/ts/app/heroes-bindings.component.ts @@ -1,10 +1,10 @@ -import {Component, HostBinding, HostListener} from '@angular/core'; +import { Component, HostBinding, HostListener } from '@angular/core'; // #docregion @Component({ selector: 'heroes-bindings', template: `

- Tour of Heroes + Tour ofHeroes

` }) export class HeroesComponent { diff --git a/public/docs/_examples/cb-ts-to-js/ts/app/main.ts b/public/docs/_examples/cb-ts-to-js/ts/app/main.ts index ac116c873b..74befc103d 100644 --- a/public/docs/_examples/cb-ts-to-js/ts/app/main.ts +++ b/public/docs/_examples/cb-ts-to-js/ts/app/main.ts @@ -1,7 +1,7 @@ // #docregion ng2import -import {provide} +import { provide } from '@angular/core'; -import {bootstrap} +import { bootstrap } from '@angular/platform-browser-dynamic'; import { } from '@angular/router'; @@ -12,18 +12,18 @@ import { // #enddocregion ng2import // #docregion appimport -import {HeroComponent} +import { HeroComponent } from './hero.component'; // #enddocregion appimport -import {HeroComponent as HeroLifecycleComponent} from './hero-lifecycle.component'; -import {HeroComponent as HeroDIComponent} from './hero-di.component'; -import {HeroComponent as HeroDIInjectComponent} from './hero-di-inject.component'; -import {AppComponent as AppDIInjectAdditionalComponent} from './hero-di-inject-additional.component'; -import {AppComponent as AppIOComponent} from './hero-io.component'; -import {HeroesComponent as HeroesHostBindingsComponent} from './heroes-bindings.component'; -import {HeroesQueriesComponent} from './heroes-queries.component'; +import { HeroComponent as HeroLifecycleComponent } from './hero-lifecycle.component'; +import { HeroComponent as HeroDIComponent } from './hero-di.component'; +import { HeroComponent as HeroDIInjectComponent } from './hero-di-inject.component'; +import { AppComponent as AppDIInjectAdditionalComponent } from './hero-di-inject-additional.component'; +import { AppComponent as AppIOComponent } from './hero-io.component'; +import { HeroesComponent as HeroesHostBindingsComponent } from './heroes-bindings.component'; +import { HeroesQueriesComponent } from './heroes-queries.component'; -import {DataService} from './data.service'; +import { DataService } from './data.service'; bootstrap(HeroComponent); bootstrap(HeroLifecycleComponent); diff --git a/public/docs/_examples/cb-ts-to-js/ts/index.html b/public/docs/_examples/cb-ts-to-js/ts/index.html index 0c29ab3ff7..80fa73d326 100644 --- a/public/docs/_examples/cb-ts-to-js/ts/index.html +++ b/public/docs/_examples/cb-ts-to-js/ts/index.html @@ -15,7 +15,7 @@ diff --git a/public/docs/_examples/component-styles/dart/lib/hero.dart b/public/docs/_examples/component-styles/dart/lib/hero.dart new file mode 100755 index 0000000000..cdfecf4d79 --- /dev/null +++ b/public/docs/_examples/component-styles/dart/lib/hero.dart @@ -0,0 +1,8 @@ +class Hero { + bool active = false; + + final String name; + final List team; + + Hero(this.name, this.team); +} diff --git a/public/docs/_examples/component-styles/dart/lib/hero_app_component.dart b/public/docs/_examples/component-styles/dart/lib/hero_app_component.dart new file mode 100755 index 0000000000..bba326e603 --- /dev/null +++ b/public/docs/_examples/component-styles/dart/lib/hero_app_component.dart @@ -0,0 +1,21 @@ +import 'package:angular2/core.dart'; +import 'hero.dart'; +import 'hero_app_main_component.dart'; + +// #docregion +@Component( + selector: 'hero-app', + template: ''' +

Tour of Heroes

+ ''', + styles: const ['h1 { font-weight: normal; }'], + directives: const [HeroAppMainComponent]) +class HeroAppComponent { +// #enddocregion + Hero hero = + new Hero('Human Torch', ['Mister Fantastic', 'Invisible Woman', 'Thing']); + + @HostBinding('class') + String get themeClass => 'theme-light'; +// #docregion +} diff --git a/public/docs/_examples/component-styles/dart/lib/hero_app_main_component.dart b/public/docs/_examples/component-styles/dart/lib/hero_app_main_component.dart new file mode 100755 index 0000000000..ddec19537b --- /dev/null +++ b/public/docs/_examples/component-styles/dart/lib/hero_app_main_component.dart @@ -0,0 +1,22 @@ +import 'package:angular2/core.dart'; + +import 'hero.dart'; +import 'hero_details_component.dart'; +import 'hero_controls_component.dart'; +import 'quest_summary_component.dart'; + +@Component( + selector: 'hero-app-main', + template: ''' + + + + ''', + directives: const [ + HeroDetailsComponent, + HeroControlsComponent, + QuestSummaryComponent + ]) +class HeroAppMainComponent { + @Input() Hero hero; +} diff --git a/public/docs/_examples/component-styles/dart/lib/hero_controls_component.dart b/public/docs/_examples/component-styles/dart/lib/hero_controls_component.dart new file mode 100755 index 0000000000..52ec2e1acb --- /dev/null +++ b/public/docs/_examples/component-styles/dart/lib/hero_controls_component.dart @@ -0,0 +1,23 @@ +import 'package:angular2/core.dart'; +import 'hero.dart'; + +// #docregion inlinestyles +@Component( + selector: 'hero-controls', + template: ''' + +

Controls

+ ''') +class HeroControlsComponent { + @Input() + Hero hero; + + void activate() { + hero.active = true; + } +} diff --git a/public/docs/_examples/component-styles/dart/lib/hero_details_box.css b/public/docs/_examples/component-styles/dart/lib/hero_details_box.css new file mode 100755 index 0000000000..443c863cb4 --- /dev/null +++ b/public/docs/_examples/component-styles/dart/lib/hero_details_box.css @@ -0,0 +1,6 @@ +:host { + padding: 10px; +} +h3 { + background-color: yellow; +} diff --git a/public/docs/_examples/component-styles/dart/lib/hero_details_component.css b/public/docs/_examples/component-styles/dart/lib/hero_details_component.css new file mode 100755 index 0000000000..6e4cd2bb26 --- /dev/null +++ b/public/docs/_examples/component-styles/dart/lib/hero_details_component.css @@ -0,0 +1,32 @@ +/* #docregion import */ +/* pub build fails on + @ import 'hero_details_box.css'; + See https://github.com/angular/angular/issues/8518 */ + +@import '/packages/component_styles/hero_details_box.css'; +/* #enddocregion import */ + +/* #docregion host */ +:host { + display: block; + border: 1px solid black; +} +/* #enddocregion host */ + +/* #docregion hostfunction */ +:host(.active) { + border-width: 3px; +} +/* #enddocregion hostfunction */ + +/* #docregion hostcontext */ +:host-context(.theme-light) h2 { + background-color: #eef; +} +/* #enddocregion hostcontext */ + +/* #docregion deep */ +:host /deep/ h3 { + font-style: italic; +} +/* #enddocregion deep */ diff --git a/public/docs/_examples/component-styles/dart/lib/hero_details_component.dart b/public/docs/_examples/component-styles/dart/lib/hero_details_component.dart new file mode 100755 index 0000000000..023cc1c170 --- /dev/null +++ b/public/docs/_examples/component-styles/dart/lib/hero_details_component.dart @@ -0,0 +1,18 @@ +import 'package:angular2/core.dart'; +import 'hero.dart'; +import 'hero_team_component.dart'; + +// #docregion styleurls +@Component( + selector: 'hero-details', + template: ''' +

{{hero.name}}

+ + ''', + styleUrls: const ['hero_details_component.css'], + directives: const [HeroTeamComponent]) +class HeroDetailsComponent { + // #enddocregion styleurls + @Input() Hero hero; + // #docregion styleurls +} diff --git a/public/docs/_examples/component-styles/dart/lib/hero_team_component.css b/public/docs/_examples/component-styles/dart/lib/hero_team_component.css new file mode 100755 index 0000000000..b87679886b --- /dev/null +++ b/public/docs/_examples/component-styles/dart/lib/hero_team_component.css @@ -0,0 +1,3 @@ +li { + list-style-type: square; +} diff --git a/public/docs/_examples/component-styles/dart/lib/hero_team_component.dart b/public/docs/_examples/component-styles/dart/lib/hero_team_component.dart new file mode 100755 index 0000000000..ec8323b633 --- /dev/null +++ b/public/docs/_examples/component-styles/dart/lib/hero_team_component.dart @@ -0,0 +1,17 @@ +import 'package:angular2/core.dart'; +import 'hero.dart'; + +// #docregion stylelink +@Component( + selector: 'hero-team', + template: ''' + +

Team

+
    +
  • + {{member}} +
  • +
''') +class HeroTeamComponent { + @Input() Hero hero; +} diff --git a/public/docs/_examples/component-styles/dart/lib/quest_summary_component.css b/public/docs/_examples/component-styles/dart/lib/quest_summary_component.css new file mode 100755 index 0000000000..207fa981dd --- /dev/null +++ b/public/docs/_examples/component-styles/dart/lib/quest_summary_component.css @@ -0,0 +1,5 @@ +:host { + display: block; + background-color: green; + color: white; +} diff --git a/public/docs/_examples/component-styles/dart/lib/quest_summary_component.dart b/public/docs/_examples/component-styles/dart/lib/quest_summary_component.dart new file mode 100755 index 0000000000..dbfe8d99d0 --- /dev/null +++ b/public/docs/_examples/component-styles/dart/lib/quest_summary_component.dart @@ -0,0 +1,18 @@ +// #docplaster +import 'package:angular2/core.dart'; + +// #docregion +@Component( + selector: 'quest-summary', +// #docregion urls + templateUrl: 'quest_summary_component.html', + styleUrls: const ['quest_summary_component.css']) +// #enddocregion urls +class QuestSummaryComponent {} +// #enddocregion +/* +// #docregion encapsulation.native + // warning: few browsers support shadow DOM encapsulation at this time + encapsulation: ViewEncapsulation.Native + // #enddocregion encapsulation.native +*/ diff --git a/public/docs/_examples/component-styles/dart/lib/quest_summary_component.html b/public/docs/_examples/component-styles/dart/lib/quest_summary_component.html new file mode 100755 index 0000000000..ace27d2a1c --- /dev/null +++ b/public/docs/_examples/component-styles/dart/lib/quest_summary_component.html @@ -0,0 +1 @@ +

No quests in progress

diff --git a/public/docs/_examples/component-styles/dart/pubspec.yaml b/public/docs/_examples/component-styles/dart/pubspec.yaml new file mode 100755 index 0000000000..39769cb7e5 --- /dev/null +++ b/public/docs/_examples/component-styles/dart/pubspec.yaml @@ -0,0 +1,15 @@ +# #docregion +name: component_styles +description: Component Styles example +version: 0.0.1 +environment: + sdk: '>=1.13.0 <2.0.0' +dependencies: + angular2: 2.0.0-beta.17 + browser: ^0.10.0 + dart_to_js_script_rewriter: ^1.0.1 +transformers: +- angular2: + platform_directives: 'package:angular2/common.dart#COMMON_DIRECTIVES' + entry_points: web/main.dart +- dart_to_js_script_rewriter diff --git a/public/docs/_examples/component-styles/dart/web/index.html b/public/docs/_examples/component-styles/dart/web/index.html new file mode 100755 index 0000000000..a74d581227 --- /dev/null +++ b/public/docs/_examples/component-styles/dart/web/index.html @@ -0,0 +1,21 @@ + + + + Component Styles + + + + + + + + +

External H1 Title for E2E test

+ + +
    +
  • External list for E2E test
  • +
+ + + diff --git a/public/docs/_examples/component-styles/dart/web/main.dart b/public/docs/_examples/component-styles/dart/web/main.dart new file mode 100755 index 0000000000..536b8c155a --- /dev/null +++ b/public/docs/_examples/component-styles/dart/web/main.dart @@ -0,0 +1,6 @@ +import 'package:angular2/platform/browser.dart'; +import 'package:component_styles/hero_app_component.dart'; + +main() { + bootstrap(HeroAppComponent); +} diff --git a/public/docs/_examples/component-styles/ts/app/hero-app-main.component.ts b/public/docs/_examples/component-styles/ts/app/hero-app-main.component.ts index 580ab684f6..fb5b5d9d98 100644 --- a/public/docs/_examples/component-styles/ts/app/hero-app-main.component.ts +++ b/public/docs/_examples/component-styles/ts/app/hero-app-main.component.ts @@ -1,8 +1,9 @@ -import {Component, Input} from '@angular/core'; -import {Hero} from './hero'; -import {HeroDetailsComponent} from './hero-details.component'; -import {HeroControlsComponent} from './hero-controls.component'; -import {QuestSummaryComponent} from './quest-summary.component'; +import { Component, Input } from '@angular/core'; + +import { Hero } from './hero'; +import { HeroDetailsComponent } from './hero-details.component'; +import { HeroControlsComponent } from './hero-controls.component'; +import { QuestSummaryComponent } from './quest-summary.component'; @Component({ selector: 'hero-app-main', diff --git a/public/docs/_examples/component-styles/ts/app/hero-app.component.ts b/public/docs/_examples/component-styles/ts/app/hero-app.component.ts index 4978c75565..b196584abb 100644 --- a/public/docs/_examples/component-styles/ts/app/hero-app.component.ts +++ b/public/docs/_examples/component-styles/ts/app/hero-app.component.ts @@ -1,6 +1,6 @@ -import {Component, HostBinding} from '@angular/core'; -import {Hero} from './hero'; -import {HeroAppMainComponent} from './hero-app-main.component'; +import { Component, HostBinding } from '@angular/core'; +import { Hero } from './hero'; +import { HeroAppMainComponent } from './hero-app-main.component'; // #docregion @Component({ @@ -11,15 +11,16 @@ import {HeroAppMainComponent} from './hero-app-main.component'; styles: ['h1 { font-weight: normal; }'], directives: [HeroAppMainComponent] }) -// #enddocregion export class HeroAppComponent { +// #enddocregion hero = new Hero( 'Human Torch', ['Mister Fantastic', 'Invisible Woman', 'Thing'] ) - + @HostBinding('class') get themeClass() { return 'theme-light'; } - +// #docregion } +// #enddocregion diff --git a/public/docs/_examples/component-styles/ts/app/hero-controls.component.ts b/public/docs/_examples/component-styles/ts/app/hero-controls.component.ts index df8883e50f..5d293596d2 100644 --- a/public/docs/_examples/component-styles/ts/app/hero-controls.component.ts +++ b/public/docs/_examples/component-styles/ts/app/hero-controls.component.ts @@ -1,5 +1,5 @@ -import {Component, Input} from '@angular/core'; -import {Hero} from './hero'; +import { Component, Input } from '@angular/core'; +import { Hero } from './hero'; // #docregion inlinestyles @Component({ @@ -17,7 +17,6 @@ import {Hero} from './hero'; }) // #enddocregion inlinestyles export class HeroControlsComponent { - @Input() hero: Hero; activate() { diff --git a/public/docs/_examples/component-styles/ts/app/hero-details.component.ts b/public/docs/_examples/component-styles/ts/app/hero-details.component.ts index c271e7413c..f530ec0757 100644 --- a/public/docs/_examples/component-styles/ts/app/hero-details.component.ts +++ b/public/docs/_examples/component-styles/ts/app/hero-details.component.ts @@ -1,6 +1,6 @@ -import {Component, Input} from '@angular/core'; -import {Hero} from './hero'; -import {HeroTeamComponent} from './hero-team.component'; +import { Component, Input } from '@angular/core'; +import { Hero } from './hero'; +import { HeroTeamComponent } from './hero-team.component'; // #docregion styleurls @Component({ @@ -14,7 +14,7 @@ import {HeroTeamComponent} from './hero-team.component'; directives: [HeroTeamComponent] }) export class HeroDetailsComponent { -// #enddocregion styleurls - - @Input() hero:Hero; + // #enddocregion styleurls + @Input() hero: Hero; + // #docregion styleurls } diff --git a/public/docs/_examples/component-styles/ts/app/hero-team.component.ts b/public/docs/_examples/component-styles/ts/app/hero-team.component.ts index 51091599b2..4f092d2827 100644 --- a/public/docs/_examples/component-styles/ts/app/hero-team.component.ts +++ b/public/docs/_examples/component-styles/ts/app/hero-team.component.ts @@ -1,5 +1,5 @@ -import {Component, Input} from '@angular/core'; -import {Hero} from './hero'; +import { Component, Input } from '@angular/core'; +import { Hero } from './hero'; // #docregion stylelink @Component({ diff --git a/public/docs/_examples/component-styles/ts/app/main.ts b/public/docs/_examples/component-styles/ts/app/main.ts index 4c53b4ae7a..1d1e75499c 100644 --- a/public/docs/_examples/component-styles/ts/app/main.ts +++ b/public/docs/_examples/component-styles/ts/app/main.ts @@ -1,4 +1,4 @@ -import {bootstrap} from '@angular/platform-browser-dynamic'; -import {HeroAppComponent} from './hero-app.component'; +import { bootstrap } from '@angular/platform-browser-dynamic'; +import { HeroAppComponent } from './hero-app.component'; bootstrap(HeroAppComponent); diff --git a/public/docs/_examples/component-styles/ts/app/quest-summary.component.html b/public/docs/_examples/component-styles/ts/app/quest-summary.component.html index abf63c2542..ace27d2a1c 100644 --- a/public/docs/_examples/component-styles/ts/app/quest-summary.component.html +++ b/public/docs/_examples/component-styles/ts/app/quest-summary.component.html @@ -1 +1 @@ -No quests in progress +

No quests in progress

diff --git a/public/docs/_examples/component-styles/ts/app/quest-summary.component.ts b/public/docs/_examples/component-styles/ts/app/quest-summary.component.ts index 33d86e2fab..9952702ddf 100644 --- a/public/docs/_examples/component-styles/ts/app/quest-summary.component.ts +++ b/public/docs/_examples/component-styles/ts/app/quest-summary.component.ts @@ -1,9 +1,8 @@ /* tslint:disable:no-unused-variable */ // #docplaster -import {Component, ViewEncapsulation} from '@angular/core'; +import { Component, ViewEncapsulation } from '@angular/core'; // #docregion - @Component({ moduleId: module.id, selector: 'quest-summary', @@ -11,6 +10,8 @@ import {Component, ViewEncapsulation} from '@angular/core'; templateUrl: 'quest-summary.component.html', styleUrls: ['quest-summary.component.css'] // #enddocregion urls +}) +export class QuestSummaryComponent { } // #enddocregion /* // #docregion encapsulation.native @@ -18,7 +19,3 @@ import {Component, ViewEncapsulation} from '@angular/core'; encapsulation: ViewEncapsulation.Native // #enddocregion encapsulation.native */ -// #docregion -}) -export class QuestSummaryComponent { } -// #enddocregion diff --git a/public/docs/_examples/component-styles/ts/index.html b/public/docs/_examples/component-styles/ts/index.html index 4af55ec90e..45dd7c73ff 100644 --- a/public/docs/_examples/component-styles/ts/index.html +++ b/public/docs/_examples/component-styles/ts/index.html @@ -15,7 +15,7 @@ diff --git a/public/docs/_examples/dependency-injection/ts/app/app.component.1.ts b/public/docs/_examples/dependency-injection/ts/app/app.component.1.ts index dda2bfb389..2e16a385dd 100644 --- a/public/docs/_examples/dependency-injection/ts/app/app.component.1.ts +++ b/public/docs/_examples/dependency-injection/ts/app/app.component.1.ts @@ -1,9 +1,10 @@ // Early versions // #docregion -import {Component} from '@angular/core'; -import {CarComponent} from './car/car.component'; -import {HeroesComponent} from './heroes/heroes.component.1'; +import { Component } from '@angular/core'; + +import { CarComponent } from './car/car.component'; +import { HeroesComponent } from './heroes/heroes.component.1'; @Component({ selector: 'my-app', diff --git a/public/docs/_examples/dependency-injection/ts/app/app.component.2.ts b/public/docs/_examples/dependency-injection/ts/app/app.component.2.ts index 97bc660e06..b2c17c90ae 100644 --- a/public/docs/_examples/dependency-injection/ts/app/app.component.2.ts +++ b/public/docs/_examples/dependency-injection/ts/app/app.component.2.ts @@ -1,12 +1,12 @@ // #docregion // #docregion imports -import {Component} from '@angular/core'; -import {CarComponent} from './car/car.component'; -import {HeroesComponent} from './heroes/heroes.component.1'; +import { Component } from '@angular/core'; +import { CarComponent } from './car/car.component'; +import { HeroesComponent } from './heroes/heroes.component.1'; -import {provide, Inject} from '@angular/core'; -import {Config, CONFIG} from './app.config'; -import {Logger} from './logger.service'; +import { provide, Inject } from '@angular/core'; +import { Config, CONFIG } from './app.config'; +import { Logger } from './logger.service'; // #enddocregion imports @Component({ diff --git a/public/docs/_examples/dependency-injection/ts/app/app.component.ts b/public/docs/_examples/dependency-injection/ts/app/app.component.ts index e10afd154f..30f2f5f303 100644 --- a/public/docs/_examples/dependency-injection/ts/app/app.component.ts +++ b/public/docs/_examples/dependency-injection/ts/app/app.component.ts @@ -1,20 +1,20 @@ // #docplaster // #docregion // #docregion imports -import {Component, Inject, provide} from '@angular/core'; +import { Component, Inject, provide } from '@angular/core'; -import {CarComponent} from './car/car.component'; -import {HeroesComponent} from './heroes/heroes.component'; +import { CarComponent } from './car/car.component'; +import { HeroesComponent } from './heroes/heroes.component'; -import {APP_CONFIG, - Config, CONFIG} from './app.config'; -import {Logger} from './logger.service'; +import { APP_CONFIG, + Config, CONFIG } from './app.config'; +import { Logger } from './logger.service'; -import {User, UserService} from './user.service'; +import { User, UserService } from './user.service'; // #enddocregion imports -import {InjectorComponent} from './injector.component'; -import {TestComponent} from './test.component'; -import {ProvidersComponent} from './providers.component'; +import { InjectorComponent } from './injector.component'; +import { TestComponent } from './test.component'; +import { ProvidersComponent } from './providers.component'; @Component({ selector: 'my-app', @@ -47,15 +47,15 @@ export class AppComponent { //#docregion ctor constructor( @Inject(APP_CONFIG) config:Config, - private _userService: UserService) { + private userService: UserService) { this.title = config.title; } // #enddocregion ctor get isAuthorized() { return this.user.isAuthorized;} - nextUser() { this._userService.getNewUser(); } - get user() { return this._userService.user; } + nextUser() { this.userService.getNewUser(); } + get user() { return this.userService.user; } get userInfo() { return `Current user, ${this.user.name}, is `+ diff --git a/public/docs/_examples/dependency-injection/ts/app/app.config.ts b/public/docs/_examples/dependency-injection/ts/app/app.config.ts index bf380936ad..0ed6225e86 100644 --- a/public/docs/_examples/dependency-injection/ts/app/app.config.ts +++ b/public/docs/_examples/dependency-injection/ts/app/app.config.ts @@ -1,6 +1,6 @@ //#docregion // #docregion token -import {OpaqueToken} from '@angular/core'; +import { OpaqueToken } from '@angular/core'; export let APP_CONFIG = new OpaqueToken('app.config'); // #enddocregion token diff --git a/public/docs/_examples/dependency-injection/ts/app/car/car-creations.ts b/public/docs/_examples/dependency-injection/ts/app/car/car-creations.ts index b6e56b85eb..2693ba37ca 100644 --- a/public/docs/_examples/dependency-injection/ts/app/car/car-creations.ts +++ b/public/docs/_examples/dependency-injection/ts/app/car/car-creations.ts @@ -1,7 +1,7 @@ // Examples with car and engine variations // #docplaster -import {Car, Engine, Tires} from './car'; +import { Car, Engine, Tires } from './car'; ///////// example 1 //////////// export function simpleCar() { diff --git a/public/docs/_examples/dependency-injection/ts/app/car/car-factory.ts b/public/docs/_examples/dependency-injection/ts/app/car/car-factory.ts index 6d869b6ee3..06daafe63b 100644 --- a/public/docs/_examples/dependency-injection/ts/app/car/car-factory.ts +++ b/public/docs/_examples/dependency-injection/ts/app/car/car-factory.ts @@ -1,5 +1,5 @@ // #docregion -import {Engine, Tires, Car} from './car'; +import { Engine, Tires, Car } from './car'; // BAD pattern! export class CarFactory { diff --git a/public/docs/_examples/dependency-injection/ts/app/car/car-injector.ts b/public/docs/_examples/dependency-injection/ts/app/car/car-injector.ts index 16b81bcd6a..d8e23efe36 100644 --- a/public/docs/_examples/dependency-injection/ts/app/car/car-injector.ts +++ b/public/docs/_examples/dependency-injection/ts/app/car/car-injector.ts @@ -2,8 +2,8 @@ //#docregion import { ReflectiveInjector } from '@angular/core'; -import {Car, Engine, Tires} from './car'; -import {Logger} from '../logger.service'; +import { Car, Engine, Tires } from './car'; +import { Logger } from '../logger.service'; //#docregion injector export function useInjector() { diff --git a/public/docs/_examples/dependency-injection/ts/app/car/car-no-di.ts b/public/docs/_examples/dependency-injection/ts/app/car/car-no-di.ts index 9556bffcab..059dccd4b7 100644 --- a/public/docs/_examples/dependency-injection/ts/app/car/car-no-di.ts +++ b/public/docs/_examples/dependency-injection/ts/app/car/car-no-di.ts @@ -1,5 +1,5 @@ // Car without DI -import {Engine, Tires} from './car'; +import { Engine, Tires } from './car'; //#docregion car export class Car { diff --git a/public/docs/_examples/dependency-injection/ts/app/car/car.component.ts b/public/docs/_examples/dependency-injection/ts/app/car/car.component.ts index 41a45d184d..f9f982ebd0 100644 --- a/public/docs/_examples/dependency-injection/ts/app/car/car.component.ts +++ b/public/docs/_examples/dependency-injection/ts/app/car/car.component.ts @@ -1,8 +1,9 @@ // #docregion -import { Component, Injector} from '@angular/core'; -import { Car, Engine, Tires } from './car'; -import { Car as CarNoDi } from './car-no-di'; -import { CarFactory} from './car-factory'; +import { Component, Injector } from '@angular/core'; + +import { Car, Engine, Tires } from './car'; +import { Car as CarNoDi } from './car-no-di'; +import { CarFactory } from './car-factory'; import { testCar, simpleCar, diff --git a/public/docs/_examples/dependency-injection/ts/app/car/car.ts b/public/docs/_examples/dependency-injection/ts/app/car/car.ts index 1895dbdf5f..dd7c76c0f2 100644 --- a/public/docs/_examples/dependency-injection/ts/app/car/car.ts +++ b/public/docs/_examples/dependency-injection/ts/app/car/car.ts @@ -1,5 +1,5 @@ // #docregion -import {Injectable} from '@angular/core'; +import { Injectable } from '@angular/core'; // #docregion engine export class Engine { diff --git a/public/docs/_examples/dependency-injection/ts/app/heroes/hero-list.component.1.ts b/public/docs/_examples/dependency-injection/ts/app/heroes/hero-list.component.1.ts index 768000da29..a9e0ce66f5 100644 --- a/public/docs/_examples/dependency-injection/ts/app/heroes/hero-list.component.1.ts +++ b/public/docs/_examples/dependency-injection/ts/app/heroes/hero-list.component.1.ts @@ -1,5 +1,6 @@ // #docregion import { Component } from '@angular/core'; + import { HEROES } from './mock-heroes'; @Component({ diff --git a/public/docs/_examples/dependency-injection/ts/app/heroes/hero-list.component.2.ts b/public/docs/_examples/dependency-injection/ts/app/heroes/hero-list.component.2.ts index 0909cf45d5..bf0b9be7ff 100644 --- a/public/docs/_examples/dependency-injection/ts/app/heroes/hero-list.component.2.ts +++ b/public/docs/_examples/dependency-injection/ts/app/heroes/hero-list.component.2.ts @@ -1,5 +1,6 @@ // #docregion import { Component } from '@angular/core'; + import { Hero } from './hero'; import { HeroService } from './hero.service'; diff --git a/public/docs/_examples/dependency-injection/ts/app/heroes/hero-list.component.ts b/public/docs/_examples/dependency-injection/ts/app/heroes/hero-list.component.ts index 88b5ba9a7c..3e2cb4579a 100644 --- a/public/docs/_examples/dependency-injection/ts/app/heroes/hero-list.component.ts +++ b/public/docs/_examples/dependency-injection/ts/app/heroes/hero-list.component.ts @@ -1,5 +1,6 @@ // #docregion import { Component } from '@angular/core'; + import { Hero } from './hero'; import { HeroService } from './hero.service'; diff --git a/public/docs/_examples/dependency-injection/ts/app/heroes/hero.service.1.ts b/public/docs/_examples/dependency-injection/ts/app/heroes/hero.service.1.ts index ae962bd9b6..1edd6b8582 100644 --- a/public/docs/_examples/dependency-injection/ts/app/heroes/hero.service.1.ts +++ b/public/docs/_examples/dependency-injection/ts/app/heroes/hero.service.1.ts @@ -1,6 +1,6 @@ // #docregion -import {Hero} from './hero'; -import {HEROES} from './mock-heroes'; +import { Hero } from './hero'; +import { HEROES } from './mock-heroes'; export class HeroService { getHeroes() { return HEROES; } diff --git a/public/docs/_examples/dependency-injection/ts/app/heroes/hero.service.2.ts b/public/docs/_examples/dependency-injection/ts/app/heroes/hero.service.2.ts index e64a81f799..0947d60494 100644 --- a/public/docs/_examples/dependency-injection/ts/app/heroes/hero.service.2.ts +++ b/public/docs/_examples/dependency-injection/ts/app/heroes/hero.service.2.ts @@ -1,18 +1,19 @@ // #docregion -import {Injectable} from '@angular/core'; -import {Hero} from './hero'; -import {HEROES} from './mock-heroes'; -import {Logger} from '../logger.service'; +import { Injectable } from '@angular/core'; + +import { Hero } from './hero'; +import { HEROES } from './mock-heroes'; +import { Logger } from '../logger.service'; @Injectable() export class HeroService { //#docregion ctor - constructor(private _logger: Logger) { } + constructor(private logger: Logger) { } //#enddocregion ctor getHeroes() { - this._logger.log('Getting heroes ...') + this.logger.log('Getting heroes ...') return HEROES; } } diff --git a/public/docs/_examples/dependency-injection/ts/app/heroes/hero.service.provider.ts b/public/docs/_examples/dependency-injection/ts/app/heroes/hero.service.provider.ts index 424b0d1f28..861b0446b0 100644 --- a/public/docs/_examples/dependency-injection/ts/app/heroes/hero.service.provider.ts +++ b/public/docs/_examples/dependency-injection/ts/app/heroes/hero.service.provider.ts @@ -1,8 +1,9 @@ // #docregion -import {provide} from '@angular/core'; -import {HeroService} from './hero.service'; -import {Logger} from '../logger.service'; -import {UserService} from '../user.service'; +import { provide } from '@angular/core'; + +import { HeroService } from './hero.service'; +import { Logger } from '../logger.service'; +import { UserService } from '../user.service'; // #docregion factory let heroServiceFactory = (logger: Logger, userService: UserService) => { diff --git a/public/docs/_examples/dependency-injection/ts/app/heroes/hero.service.ts b/public/docs/_examples/dependency-injection/ts/app/heroes/hero.service.ts index feee9f14fa..7e84ae5058 100644 --- a/public/docs/_examples/dependency-injection/ts/app/heroes/hero.service.ts +++ b/public/docs/_examples/dependency-injection/ts/app/heroes/hero.service.ts @@ -1,8 +1,9 @@ // #docregion -import {Injectable} from '@angular/core'; -import {Hero} from './hero'; -import {HEROES} from './mock-heroes'; -import {Logger} from '../logger.service'; +import { Injectable } from '@angular/core'; + +import { Hero } from './hero'; +import { HEROES } from './mock-heroes'; +import { Logger } from '../logger.service'; @Injectable() export class HeroService { @@ -10,13 +11,13 @@ export class HeroService { // #docregion internals constructor( - private _logger: Logger, - private _isAuthorized: boolean) { } + private logger: Logger, + private isAuthorized: boolean) { } getHeroes() { - let auth = this._isAuthorized ? 'authorized ': 'unauthorized'; - this._logger.log(`Getting heroes for ${auth} user.`); - return HEROES.filter(hero => this._isAuthorized || !hero.isSecret); + let auth = this.isAuthorized ? 'authorized ': 'unauthorized'; + this.logger.log(`Getting heroes for ${auth} user.`); + return HEROES.filter(hero => this.isAuthorized || !hero.isSecret); } // #enddocregion internals } diff --git a/public/docs/_examples/dependency-injection/ts/app/heroes/heroes.component.1.ts b/public/docs/_examples/dependency-injection/ts/app/heroes/heroes.component.1.ts index 6504c35f5c..7f431d6d19 100644 --- a/public/docs/_examples/dependency-injection/ts/app/heroes/heroes.component.1.ts +++ b/public/docs/_examples/dependency-injection/ts/app/heroes/heroes.component.1.ts @@ -2,6 +2,7 @@ // #docregion // #docregion v1 import { Component } from '@angular/core'; + import { HeroListComponent } from './hero-list.component'; // #enddocregion v1 import { HeroService } from './hero.service'; diff --git a/public/docs/_examples/dependency-injection/ts/app/heroes/heroes.component.ts b/public/docs/_examples/dependency-injection/ts/app/heroes/heroes.component.ts index 89b3c85c03..de46be16c3 100644 --- a/public/docs/_examples/dependency-injection/ts/app/heroes/heroes.component.ts +++ b/public/docs/_examples/dependency-injection/ts/app/heroes/heroes.component.ts @@ -1,5 +1,6 @@ // #docregion import { Component } from '@angular/core'; + import { HeroListComponent } from './hero-list.component'; import { heroServiceProvider} from './hero.service.provider'; diff --git a/public/docs/_examples/dependency-injection/ts/app/injector.component.ts b/public/docs/_examples/dependency-injection/ts/app/injector.component.ts index 2c9214cc2b..7938a5b8ed 100644 --- a/public/docs/_examples/dependency-injection/ts/app/injector.component.ts +++ b/public/docs/_examples/dependency-injection/ts/app/injector.component.ts @@ -1,11 +1,11 @@ // #docplaster //#docregion -import {Component, Injector} from '@angular/core'; +import { Component, Injector } from '@angular/core'; -import {Car, Engine, Tires} from './car/car'; -import {HeroService} from './heroes/hero.service'; -import {heroServiceProvider} from './heroes/hero.service.provider'; -import {Logger} from './logger.service'; +import { Car, Engine, Tires } from './car/car'; +import { HeroService } from './heroes/hero.service'; +import { heroServiceProvider } from './heroes/hero.service.provider'; +import { Logger } from './logger.service'; //#docregion injector @Component({ @@ -16,21 +16,22 @@ import {Logger} from './logger.service';
{{hero.name}}
{{rodent}}
`, + providers: [Car, Engine, Tires, heroServiceProvider, Logger] }) export class InjectorComponent { - constructor(private _injector: Injector) { } + constructor(private injector: Injector) { } - car:Car = this._injector.get(Car); + car:Car = this.injector.get(Car); //#docregion get-hero-service - heroService:HeroService = this._injector.get(HeroService); + heroService:HeroService = this.injector.get(HeroService); //#enddocregion get-hero-service hero = this.heroService.getHeroes()[0]; get rodent() { - let rous = this._injector.get(ROUS, null); + let rous = this.injector.get(ROUS, null); if (rous) { throw new Error('Aaaargh!') } diff --git a/public/docs/_examples/dependency-injection/ts/app/logger.service.ts b/public/docs/_examples/dependency-injection/ts/app/logger.service.ts index 9d1df91ee4..7efb25ba4d 100644 --- a/public/docs/_examples/dependency-injection/ts/app/logger.service.ts +++ b/public/docs/_examples/dependency-injection/ts/app/logger.service.ts @@ -1,5 +1,5 @@ // #docregion -import {Injectable} from '@angular/core'; +import { Injectable } from '@angular/core'; @Injectable() export class Logger { diff --git a/public/docs/_examples/dependency-injection/ts/app/main.1.ts b/public/docs/_examples/dependency-injection/ts/app/main.1.ts index 981a6bef30..a8c48c2d28 100644 --- a/public/docs/_examples/dependency-injection/ts/app/main.1.ts +++ b/public/docs/_examples/dependency-injection/ts/app/main.1.ts @@ -1,6 +1,6 @@ -import {bootstrap} from '@angular/platform-browser-dynamic'; -import {AppComponent} from './app.component'; -import {HeroService} from './heroes/hero.service'; +import { bootstrap } from '@angular/platform-browser-dynamic'; +import { AppComponent } from './app.component'; +import { HeroService } from './heroes/hero.service'; //#docregion bootstrap bootstrap(AppComponent, diff --git a/public/docs/_examples/dependency-injection/ts/app/main.ts b/public/docs/_examples/dependency-injection/ts/app/main.ts index 878274eb61..2919d89387 100644 --- a/public/docs/_examples/dependency-injection/ts/app/main.ts +++ b/public/docs/_examples/dependency-injection/ts/app/main.ts @@ -1,9 +1,9 @@ //#docregion -import {bootstrap} from '@angular/platform-browser-dynamic'; -import {AppComponent} from './app.component'; -import {ProvidersComponent} from './providers.component'; +import { bootstrap } from '@angular/platform-browser-dynamic'; +import { AppComponent } from './app.component'; +import { ProvidersComponent } from './providers.component'; //#docregion bootstrap bootstrap(AppComponent); //#enddocregion bootstrap -bootstrap(ProvidersComponent); \ No newline at end of file +bootstrap(ProvidersComponent); diff --git a/public/docs/_examples/dependency-injection/ts/app/providers.component.ts b/public/docs/_examples/dependency-injection/ts/app/providers.component.ts index 96e2721fe4..e0426ae9d0 100644 --- a/public/docs/_examples/dependency-injection/ts/app/providers.component.ts +++ b/public/docs/_examples/dependency-injection/ts/app/providers.component.ts @@ -1,15 +1,15 @@ // Examples of provider arrays //#docplaster import { Component, Host, Inject, Injectable, - provide, Provider} from '@angular/core'; + provide, Provider } from '@angular/core'; import { APP_CONFIG, - Config, CONFIG } from './app.config'; + Config, CONFIG } from './app.config'; -import { HeroService} from './heroes/hero.service'; -import { heroServiceProvider } from './heroes/hero.service.provider'; -import { Logger } from './logger.service'; -import { User, UserService } from './user.service'; +import { HeroService } from './heroes/hero.service'; +import { heroServiceProvider } from './heroes/hero.service.provider'; +import { Logger } from './logger.service'; +import { User, UserService } from './user.service'; let template = '{{log}}'; @@ -89,10 +89,10 @@ export class ProviderComponent4 { class EvenBetterLogger { logs:string[] = []; - constructor(private _userService: UserService) { } + constructor(private userService: UserService) { } log(message:string){ - message = `Message to ${this._userService.user.name}: ${message}.`; + message = `Message to ${this.userService.user.name}: ${message}.`; console.log(message); this.logs.push(message); } @@ -230,17 +230,17 @@ export class ProviderComponent9a { /* // #docregion provider-9a-ctor-interface // FAIL! Can't inject using the interface as the parameter type - constructor(private _config: Config){ } + constructor(private config: Config){ } // #enddocregion provider-9a-ctor-interface */ // #docregion provider-9a-ctor // @Inject(token) to inject the dependency - constructor(@Inject('app.config') private _config: Config){ } + constructor(@Inject('app.config') private config: Config){ } // #enddocregion provider-9a-ctor ngOnInit() { - this.log = '"app.config" Application title is ' + this._config.title; + this.log = '"app.config" Application title is ' + this.config.title; } } @@ -254,11 +254,11 @@ export class ProviderComponent9a { export class ProviderComponent9b { log: string; // #docregion provider-9b-ctor - constructor(@Inject(APP_CONFIG) private _config: Config){ } + constructor(@Inject(APP_CONFIG) private config: Config){ } // #enddocregion provider-9b-ctor ngOnInit() { - this.log = 'APP_CONFIG Application title is ' + this._config.title; + this.log = 'APP_CONFIG Application title is ' + this.config.title; } } ////////////////////////////////////////// @@ -290,27 +290,27 @@ import {Optional} from '@angular/core'; export class ProviderComponent10b { // #docregion provider-10-ctor log:string; - constructor(@Optional() private _logger:Logger) { } + constructor(@Optional() private logger:Logger) { } // #enddocregion provider-10-ctor ngOnInit() { // #docregion provider-10-logger // No logger? Make one! - if (!this._logger) { - this._logger = { - log: (msg:string)=> this._logger.logs.push(msg), + if (!this.logger) { + this.logger = { + log: (msg:string)=> this.logger.logs.push(msg), logs: [] } - // #enddocregion provider-10-logger - this._logger.log("Optional logger was not available.") - // #docregion provider-10-logger + // #enddocregion provider-10-logger + this.logger.log("Optional logger was not available.") + // #docregion provider-10-logger } // #enddocregion provider-10-logger else { - this._logger.log('Hello from the injected logger.') - this.log = this._logger.logs[0]; + this.logger.log('Hello from the injected logger.') + this.log = this.logger.logs[0]; } - this.log = this._logger.logs[0]; + this.log = this.logger.logs[0]; } } @@ -349,4 +349,4 @@ export class ProviderComponent10b { ProviderComponent10b, ], }) -export class ProvidersComponent { } \ No newline at end of file +export class ProvidersComponent { } diff --git a/public/docs/_examples/dependency-injection/ts/app/test.component.ts b/public/docs/_examples/dependency-injection/ts/app/test.component.ts index 72db98de57..48466c91d2 100644 --- a/public/docs/_examples/dependency-injection/ts/app/test.component.ts +++ b/public/docs/_examples/dependency-injection/ts/app/test.component.ts @@ -1,9 +1,10 @@ // Simulate a simple test // Reader should look to the testing chapter for the real thing -import {Component} from '@angular/core'; -import { HeroService } from './heroes/hero.service'; -import { HeroListComponent } from './heroes/hero-list.component'; +import { Component } from '@angular/core'; + +import { HeroService } from './heroes/hero.service'; +import { HeroListComponent } from './heroes/hero-list.component'; @Component({ selector: 'my-tests', @@ -50,4 +51,4 @@ function expect(actual:any) { function it(label:string, test: () => void) { testName = label; test(); -} \ No newline at end of file +} diff --git a/public/docs/_examples/dependency-injection/ts/index.html b/public/docs/_examples/dependency-injection/ts/index.html index 9127c5a14a..74708a8852 100644 --- a/public/docs/_examples/dependency-injection/ts/index.html +++ b/public/docs/_examples/dependency-injection/ts/index.html @@ -16,7 +16,7 @@ diff --git a/public/docs/_examples/displaying-data/ts/app/app-ctor.component.ts b/public/docs/_examples/displaying-data/ts/app/app-ctor.component.ts index 103a34d49d..ed59b40b2c 100644 --- a/public/docs/_examples/displaying-data/ts/app/app-ctor.component.ts +++ b/public/docs/_examples/displaying-data/ts/app/app-ctor.component.ts @@ -1,4 +1,4 @@ -import {Component} from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'my-app-ctor', diff --git a/public/docs/_examples/displaying-data/ts/app/app.component.1.ts b/public/docs/_examples/displaying-data/ts/app/app.component.1.ts index 2e676d5b47..1cbeb0f731 100644 --- a/public/docs/_examples/displaying-data/ts/app/app.component.1.ts +++ b/public/docs/_examples/displaying-data/ts/app/app.component.1.ts @@ -1,5 +1,5 @@ // #docregion -import {Component} from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'my-app', diff --git a/public/docs/_examples/displaying-data/ts/app/app.component.2.ts b/public/docs/_examples/displaying-data/ts/app/app.component.2.ts index 93aabd17b2..506215b36e 100644 --- a/public/docs/_examples/displaying-data/ts/app/app.component.2.ts +++ b/public/docs/_examples/displaying-data/ts/app/app.component.2.ts @@ -1,5 +1,5 @@ // #docregion -import {Component} from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'my-app', diff --git a/public/docs/_examples/displaying-data/ts/app/app.component.3.ts b/public/docs/_examples/displaying-data/ts/app/app.component.3.ts index bed5639a27..301343f851 100644 --- a/public/docs/_examples/displaying-data/ts/app/app.component.3.ts +++ b/public/docs/_examples/displaying-data/ts/app/app.component.3.ts @@ -1,7 +1,7 @@ // #docregion -import {Component} from '@angular/core'; +import { Component} from '@angular/core'; // #docregion import-hero -import {Hero} from './hero'; +import { Hero} from './hero'; // #enddocregion import-hero @Component({ diff --git a/public/docs/_examples/displaying-data/ts/app/app.component.ts b/public/docs/_examples/displaying-data/ts/app/app.component.ts index 931ceba823..1ba40c62c9 100644 --- a/public/docs/_examples/displaying-data/ts/app/app.component.ts +++ b/public/docs/_examples/displaying-data/ts/app/app.component.ts @@ -1,9 +1,9 @@ // #docplaster // #docregion final // #docregion imports -import {Component} from '@angular/core'; +import { Component } from '@angular/core'; // #enddocregion imports -import {Hero} from './hero'; +import { Hero } from './hero'; @Component({ selector: 'my-app', @@ -17,7 +17,8 @@ import {Hero} from './hero'; // #docregion message -

There are many heroes!

+

There are many heroes!

// #enddocregion message ` }) diff --git a/public/docs/_examples/displaying-data/ts/app/main.1.ts b/public/docs/_examples/displaying-data/ts/app/main.1.ts index 1027d45de5..2e0a4bc6f4 100644 --- a/public/docs/_examples/displaying-data/ts/app/main.1.ts +++ b/public/docs/_examples/displaying-data/ts/app/main.1.ts @@ -1,10 +1,11 @@ -import {bootstrap} from '@angular/platform-browser-dynamic'; -import {AppCtorComponent} from './app-ctor.component'; -import {AppComponent as v1} from './app.component.1'; -import {AppComponent as v2} from './app.component.2'; -import {AppComponent as v3} from './app.component.3'; +import { bootstrap } from '@angular/platform-browser-dynamic'; -import {AppComponent as final} from './app.component'; +import { AppCtorComponent } from './app-ctor.component'; +import { AppComponent as v1 } from './app.component.1'; +import { AppComponent as v2 } from './app.component.2'; +import { AppComponent as v3 } from './app.component.3'; + +import { AppComponent as final } from './app.component'; // pick one //bootstrap(v1); @@ -13,4 +14,4 @@ import {AppComponent as final} from './app.component'; bootstrap(final); // for doc testing -bootstrap(AppCtorComponent); \ No newline at end of file +bootstrap(AppCtorComponent); diff --git a/public/docs/_examples/displaying-data/ts/app/main.ts b/public/docs/_examples/displaying-data/ts/app/main.ts index 38cc516baa..52b47899ef 100644 --- a/public/docs/_examples/displaying-data/ts/app/main.ts +++ b/public/docs/_examples/displaying-data/ts/app/main.ts @@ -1,5 +1,6 @@ // #docregion -import {bootstrap} from '@angular/platform-browser-dynamic'; -import {AppComponent} from './app.component'; +import { bootstrap } from '@angular/platform-browser-dynamic'; + +import { AppComponent } from './app.component'; bootstrap(AppComponent); diff --git a/public/docs/_examples/displaying-data/ts/index.html b/public/docs/_examples/displaying-data/ts/index.html index 47300dcfe7..7b96075c09 100644 --- a/public/docs/_examples/displaying-data/ts/index.html +++ b/public/docs/_examples/displaying-data/ts/index.html @@ -15,7 +15,7 @@ diff --git a/public/docs/_examples/forms/ts/app/app.component.ts b/public/docs/_examples/forms/ts/app/app.component.ts index f6d7a2d3d8..b8551a0520 100644 --- a/public/docs/_examples/forms/ts/app/app.component.ts +++ b/public/docs/_examples/forms/ts/app/app.component.ts @@ -1,6 +1,6 @@ // #docregion -import {Component} from '@angular/core'; -import {HeroFormComponent} from './hero-form.component' +import { Component } from '@angular/core'; +import { HeroFormComponent } from './hero-form.component' @Component({ selector: 'my-app', diff --git a/public/docs/_examples/forms/ts/app/hero-form.component.ts b/public/docs/_examples/forms/ts/app/hero-form.component.ts index 04fbd90e67..c4876d8203 100644 --- a/public/docs/_examples/forms/ts/app/hero-form.component.ts +++ b/public/docs/_examples/forms/ts/app/hero-form.component.ts @@ -1,8 +1,9 @@ // #docplaster // #docregion // #docregion first, final -import {Component} from '@angular/core'; -import {NgForm} from '@angular/common'; +import { Component } from '@angular/core'; +import { NgForm } from '@angular/common'; + import { Hero } from './hero'; @Component({ diff --git a/public/docs/_examples/forms/ts/app/main.ts b/public/docs/_examples/forms/ts/app/main.ts index 1bb870eea0..5338161d66 100644 --- a/public/docs/_examples/forms/ts/app/main.ts +++ b/public/docs/_examples/forms/ts/app/main.ts @@ -1,5 +1,6 @@ // #docregion -import {bootstrap} from '@angular/platform-browser-dynamic'; -import {AppComponent} from './app.component'; +import { bootstrap } from '@angular/platform-browser-dynamic'; + +import { AppComponent } from './app.component'; bootstrap(AppComponent); diff --git a/public/docs/_examples/forms/ts/index.html b/public/docs/_examples/forms/ts/index.html index 39f5c544ba..ac457e8f82 100644 --- a/public/docs/_examples/forms/ts/index.html +++ b/public/docs/_examples/forms/ts/index.html @@ -23,7 +23,7 @@ diff --git a/public/docs/_examples/hierarchical-dependency-injection/ts/app/hero-card.component.ts b/public/docs/_examples/hierarchical-dependency-injection/ts/app/hero-card.component.ts index b7416ccd9d..a888168848 100644 --- a/public/docs/_examples/hierarchical-dependency-injection/ts/app/hero-card.component.ts +++ b/public/docs/_examples/hierarchical-dependency-injection/ts/app/hero-card.component.ts @@ -1,6 +1,7 @@ // #docregion -import {Component, Input} from '@angular/core'; -import {Hero} from './hero'; +import { Component, Input } from '@angular/core'; + +import { Hero } from './hero'; @Component({ selector: 'hero-card', diff --git a/public/docs/_examples/hierarchical-dependency-injection/ts/app/hero-editor.component.ts b/public/docs/_examples/hierarchical-dependency-injection/ts/app/hero-editor.component.ts index 74ae9222e1..65f0b7f066 100644 --- a/public/docs/_examples/hierarchical-dependency-injection/ts/app/hero-editor.component.ts +++ b/public/docs/_examples/hierarchical-dependency-injection/ts/app/hero-editor.component.ts @@ -1,7 +1,8 @@ // #docregion -import {Component, Input, Output, EventEmitter} from '@angular/core'; -import {RestoreService} from './restore.service'; -import {Hero} from './hero'; +import { Component, EventEmitter, Input, Output } from '@angular/core'; + +import { RestoreService } from './restore.service'; +import { Hero } from './hero'; @Component({ selector: 'hero-editor', diff --git a/public/docs/_examples/hierarchical-dependency-injection/ts/app/heroes-list.component.ts b/public/docs/_examples/hierarchical-dependency-injection/ts/app/heroes-list.component.ts index 7330ed758e..0fef36e205 100644 --- a/public/docs/_examples/hierarchical-dependency-injection/ts/app/heroes-list.component.ts +++ b/public/docs/_examples/hierarchical-dependency-injection/ts/app/heroes-list.component.ts @@ -1,10 +1,11 @@ // #docregion -import {Component} from '@angular/core'; -import {EditItem} from './edit-item'; -import {HeroesService} from './heroes.service'; -import {HeroCardComponent} from './hero-card.component'; -import {HeroEditorComponent} from './hero-editor.component'; -import {Hero} from './hero'; +import { Component } from '@angular/core'; + +import { EditItem } from './edit-item'; +import { HeroesService } from './heroes.service'; +import { HeroCardComponent } from './hero-card.component'; +import { HeroEditorComponent } from './hero-editor.component'; +import { Hero } from './hero'; @Component({ selector: 'heroes-list', diff --git a/public/docs/_examples/hierarchical-dependency-injection/ts/app/heroes.service.ts b/public/docs/_examples/hierarchical-dependency-injection/ts/app/heroes.service.ts index e4f9e2d213..b863ee7af8 100644 --- a/public/docs/_examples/hierarchical-dependency-injection/ts/app/heroes.service.ts +++ b/public/docs/_examples/hierarchical-dependency-injection/ts/app/heroes.service.ts @@ -1,4 +1,4 @@ -import {Hero} from './hero'; +import { Hero } from './hero'; export class HeroesService { heroes: Array = [ diff --git a/public/docs/_examples/hierarchical-dependency-injection/ts/app/main.ts b/public/docs/_examples/hierarchical-dependency-injection/ts/app/main.ts index 547806e01a..5a96ae391b 100644 --- a/public/docs/_examples/hierarchical-dependency-injection/ts/app/main.ts +++ b/public/docs/_examples/hierarchical-dependency-injection/ts/app/main.ts @@ -1,7 +1,8 @@ // #docregion -import {bootstrap} from '@angular/platform-browser-dynamic'; -import {HeroesListComponent} from './heroes-list.component'; -import {HeroesService} from './heroes.service'; +import { bootstrap } from '@angular/platform-browser-dynamic'; + +import { HeroesListComponent } from './heroes-list.component'; +import { HeroesService } from './heroes.service'; bootstrap(HeroesListComponent, [HeroesService]) @@ -10,4 +11,4 @@ bootstrap(HeroesListComponent, [HeroesService]) // Don't do this! bootstrap(HeroesListComponent, [HeroesService, RestoreService]) // #enddocregion bad-alternative -*/ \ No newline at end of file +*/ diff --git a/public/docs/_examples/hierarchical-dependency-injection/ts/index.html b/public/docs/_examples/hierarchical-dependency-injection/ts/index.html index 8cf0393a39..a4109a1625 100644 --- a/public/docs/_examples/hierarchical-dependency-injection/ts/index.html +++ b/public/docs/_examples/hierarchical-dependency-injection/ts/index.html @@ -15,7 +15,7 @@ diff --git a/public/docs/_examples/homepage-hello-world/ts/app/hello_world.ts b/public/docs/_examples/homepage-hello-world/ts/app/hello_world.ts index 6c3969ea7e..67850d5749 100644 --- a/public/docs/_examples/homepage-hello-world/ts/app/hello_world.ts +++ b/public/docs/_examples/homepage-hello-world/ts/app/hello_world.ts @@ -1,5 +1,5 @@ // #docregion -import {Component} from '@angular/core'; +import { Component } from '@angular/core'; @Component({ // Declare the tag name in index.html to where the component attaches diff --git a/public/docs/_examples/homepage-hello-world/ts/app/main.ts b/public/docs/_examples/homepage-hello-world/ts/app/main.ts index 7a10b8b99a..625a9c338f 100644 --- a/public/docs/_examples/homepage-hello-world/ts/app/main.ts +++ b/public/docs/_examples/homepage-hello-world/ts/app/main.ts @@ -1,5 +1,6 @@ // #docregion -import {bootstrap} from '@angular/platform-browser-dynamic'; -import {HelloWorld} from './hello_world'; +import { bootstrap } from '@angular/platform-browser-dynamic'; -bootstrap(HelloWorld); \ No newline at end of file +import { HelloWorld } from './hello_world'; + +bootstrap(HelloWorld); diff --git a/public/docs/_examples/homepage-hello-world/ts/index.html b/public/docs/_examples/homepage-hello-world/ts/index.html index 7c8bfed12c..246cecc85d 100644 --- a/public/docs/_examples/homepage-hello-world/ts/index.html +++ b/public/docs/_examples/homepage-hello-world/ts/index.html @@ -16,7 +16,7 @@ diff --git a/public/docs/_examples/homepage-tabs/ts/app/di_demo.ts b/public/docs/_examples/homepage-tabs/ts/app/di_demo.ts index f0e73f9706..1e170bcd6f 100644 --- a/public/docs/_examples/homepage-tabs/ts/app/di_demo.ts +++ b/public/docs/_examples/homepage-tabs/ts/app/di_demo.ts @@ -1,6 +1,7 @@ // #docregion -import {Component} from '@angular/core'; -import {UiTabs, UiPane} from './ui_tabs'; +import { Component } from '@angular/core'; + +import { UiTabs, UiPane } from './ui_tabs'; class Detail { title: string; diff --git a/public/docs/_examples/homepage-tabs/ts/app/main.ts b/public/docs/_examples/homepage-tabs/ts/app/main.ts index deb3f56527..b7904fd356 100644 --- a/public/docs/_examples/homepage-tabs/ts/app/main.ts +++ b/public/docs/_examples/homepage-tabs/ts/app/main.ts @@ -1,5 +1,6 @@ // #docregion -import {bootstrap} from '@angular/platform-browser-dynamic'; -import {DiDemo} from './di_demo'; +import { bootstrap } from '@angular/platform-browser-dynamic'; + +import { DiDemo } from './di_demo'; bootstrap(DiDemo); diff --git a/public/docs/_examples/homepage-tabs/ts/app/ui_tabs.ts b/public/docs/_examples/homepage-tabs/ts/app/ui_tabs.ts index 17c6bc4103..a9798d07e6 100644 --- a/public/docs/_examples/homepage-tabs/ts/app/ui_tabs.ts +++ b/public/docs/_examples/homepage-tabs/ts/app/ui_tabs.ts @@ -1,6 +1,6 @@ // #docregion -import {Component, Directive, Input, QueryList, - ViewContainerRef, TemplateRef, ContentChildren} from '@angular/core'; +import { Component, Directive, Input, QueryList, + ViewContainerRef, TemplateRef, ContentChildren } from '@angular/core'; @Directive({ selector: '[ui-pane]' diff --git a/public/docs/_examples/homepage-tabs/ts/index.html b/public/docs/_examples/homepage-tabs/ts/index.html index e635f45ba1..9abb036d3a 100644 --- a/public/docs/_examples/homepage-tabs/ts/index.html +++ b/public/docs/_examples/homepage-tabs/ts/index.html @@ -17,7 +17,7 @@ diff --git a/public/docs/_examples/homepage-todo/ts/app/main.ts b/public/docs/_examples/homepage-todo/ts/app/main.ts index 661568820e..1beb139138 100644 --- a/public/docs/_examples/homepage-todo/ts/app/main.ts +++ b/public/docs/_examples/homepage-todo/ts/app/main.ts @@ -1,5 +1,6 @@ // #docregion -import {bootstrap} from '@angular/platform-browser-dynamic'; -import {TodoApp} from './todo_app'; +import { bootstrap } from '@angular/platform-browser-dynamic'; -bootstrap(TodoApp); \ No newline at end of file +import { TodoApp } from './todo_app'; + +bootstrap(TodoApp); diff --git a/public/docs/_examples/homepage-todo/ts/app/todo_app.ts b/public/docs/_examples/homepage-todo/ts/app/todo_app.ts index 99e303a17a..96cb759eeb 100644 --- a/public/docs/_examples/homepage-todo/ts/app/todo_app.ts +++ b/public/docs/_examples/homepage-todo/ts/app/todo_app.ts @@ -1,8 +1,9 @@ // #docregion -import {Component} from '@angular/core'; -import {Todo} from './todo'; -import {TodoList} from './todo_list'; -import {TodoForm} from './todo_form'; +import { Component } from '@angular/core'; + +import { Todo } from './todo'; +import { TodoList } from './todo_list'; +import { TodoForm } from './todo_form'; @Component({ selector: 'todo-app', diff --git a/public/docs/_examples/homepage-todo/ts/app/todo_form.ts b/public/docs/_examples/homepage-todo/ts/app/todo_form.ts index 5e381ed4bf..ecc8596772 100644 --- a/public/docs/_examples/homepage-todo/ts/app/todo_form.ts +++ b/public/docs/_examples/homepage-todo/ts/app/todo_form.ts @@ -1,6 +1,6 @@ // #docregion -import {Component, Output, EventEmitter} from '@angular/core'; -import {Todo} from './todo'; +import { Component, Output, EventEmitter } from '@angular/core'; +import { Todo } from './todo'; @Component({ selector: 'todo-form', diff --git a/public/docs/_examples/homepage-todo/ts/app/todo_list.ts b/public/docs/_examples/homepage-todo/ts/app/todo_list.ts index 68cebb4e4a..bdeff74a27 100644 --- a/public/docs/_examples/homepage-todo/ts/app/todo_list.ts +++ b/public/docs/_examples/homepage-todo/ts/app/todo_list.ts @@ -1,6 +1,6 @@ // #docregion -import {Component, Input} from '@angular/core'; -import {Todo} from './todo'; +import { Component, Input } from '@angular/core'; +import { Todo } from './todo'; @Component({ selector: 'todo-list', diff --git a/public/docs/_examples/homepage-todo/ts/index.html b/public/docs/_examples/homepage-todo/ts/index.html index e43f04a1f9..738fed01b9 100644 --- a/public/docs/_examples/homepage-todo/ts/index.html +++ b/public/docs/_examples/homepage-todo/ts/index.html @@ -17,7 +17,7 @@ diff --git a/public/docs/_examples/lifecycle-hooks/dart/lib/after_content_component.dart b/public/docs/_examples/lifecycle-hooks/dart/lib/after_content_component.dart new file mode 100644 index 0000000000..4e11dc702b --- /dev/null +++ b/public/docs/_examples/lifecycle-hooks/dart/lib/after_content_component.dart @@ -0,0 +1,115 @@ +// #docplaster +// #docregion +import 'package:angular2/core.dart'; + +import 'logger_service.dart'; + +////////////////// +@Component( + selector: 'my-child', + template: '') +class ChildComponent { + String hero = 'Magneta'; +} + +////////////////////// +@Component( + selector: 'after-content', +// #docregion template + template: ''' +
-- projected content begins --
+ +
-- projected content ends --
+

{{comment}}

+ ''' +// #enddocregion template + ) +// #docregion hooks +class AfterContentComponent implements AfterContentChecked, AfterContentInit { + String _prevHero = ''; + String comment = ''; + + // Query for a CONTENT child of type `ChildComponent` + @ContentChild(ChildComponent) ChildComponent contentChild; + +// #enddocregion hooks + final LoggerService _logger; + + AfterContentComponent(this._logger) { + _logIt('AfterContent constructor'); + } + +// #docregion hooks + ngAfterContentInit() { + // contentChild is set after the content has been initialized + _logIt('AfterContentInit'); + _doSomething(); + } + + ngAfterContentChecked() { + // contentChild is updated after the content has been checked + if (_prevHero == contentChild?.hero) { + _logIt('AfterContentChecked (no change)'); + } else { + _prevHero = contentChild?.hero; + _logIt('AfterContentChecked'); + _doSomething(); + } + } +// #enddocregion hooks +// #docregion do-something + /// This surrogate for real business logic; sets the `comment` + void _doSomething() { + comment = contentChild.hero.length > 10 ? "That's a long name" : ''; + } +// #enddocregion do-something + + void _logIt(String method) { + var child = contentChild; + var message = "${method}: ${child?.hero ?? 'no'} child content"; + _logger.log(message); + } +// #docregion hooks + // ... +} +// #enddocregion hooks + +////////////// +@Component( + selector: 'after-content-parent', +// #docregion parent-template + template: ''' +
+

AfterContent

+ +
+ + + +
+ +

-- AfterContent Logs --

+

+
{{msg}}
+
+ ''', +// #enddocregion parent-template + styles: const ['.parent {background: burlywood}'], + providers: const [LoggerService], + directives: const [AfterContentComponent, ChildComponent]) +class AfterContentParentComponent { + final LoggerService _logger; + bool show = true; + + AfterContentParentComponent(this._logger); + + List get logs => _logger.logs; + + void reset() { + logs.clear(); + // quickly remove and reload AfterViewComponent which recreates it + show = false; + _logger.tick().then((_) { show = true; }); + } + +} diff --git a/public/docs/_examples/lifecycle-hooks/dart/lib/after_content_parent.dart b/public/docs/_examples/lifecycle-hooks/dart/lib/after_content_parent.dart deleted file mode 100644 index 64cad0a49c..0000000000 --- a/public/docs/_examples/lifecycle-hooks/dart/lib/after_content_parent.dart +++ /dev/null @@ -1,95 +0,0 @@ -// #docregion -import 'package:angular2/core.dart'; - -import 'child_component.dart'; -import 'logger_service.dart'; - -@Component( - selector: 'after-content', - template: ''' -
-
-- child content begins --
- - - -
-- child content ends --
-
- ''', - styles: const ['.after-content {background: LightCyan; padding: 8px;}']) -class AfterContentComponent - implements AfterContentChecked, AfterContentInit, AfterViewInit { - LoggerService _logger; - - // Query for a CONTENT child of type `ChildComponent` - @ContentChild(ChildComponent) ChildComponent contentChild; - - // Query for a VIEW child of type`ChildComponent` - // No such VIEW child exists! - // This component holds content but no view of that type. - @ViewChild(ChildComponent) ChildComponent viewChild; - - String _prevHero; - - AfterContentComponent(this._logger) { - _logger.log('AfterContent ctor: $message'); - } - - ///// Hooks - ngAfterContentInit() { - // contentChild is set after the content has been initialized - _logger.log('AfterContentInit: $message'); - } - - get hasViewChild => viewChild != null; - - ngAfterViewInit() { - _logger - .log('AfterViewInit: There is ${hasViewChild ? 'a' : 'no'} view child'); - } - - ngAfterContentChecked() { - // contentChild is updated after the content has been checked - // Called frequently; only report when the hero changes - if (!hasContentChild || _prevHero == contentChild.hero) return; - _prevHero = contentChild.hero; - _logger.log('AfterContentChecked: $message'); - } - - bool get hasContentChild => contentChild != null; - - String get message => hasContentChild - ? '"${contentChild.hero}" child content' - : 'no child content'; -} - -@Component( - selector: 'after-content-parent', - template: ''' -
-

AfterContent

- - - - - - - - -

-- Lifecycle Hook Log --

-
{{msg}}
-
- ''', - styles: const [ - '.parent {background: powderblue; padding: 8px; margin:100px 8px;}' - ], - directives: const [AfterContentComponent, ChildComponent], - providers: const [LoggerService]) -class AfterContentParentComponent { - List hookLog; - String hero = 'Magneta'; - bool showChild = true; - - AfterContentParentComponent(LoggerService logger) { - hookLog = logger.logs; - } -} diff --git a/public/docs/_examples/lifecycle-hooks/dart/lib/after_view_component.dart b/public/docs/_examples/lifecycle-hooks/dart/lib/after_view_component.dart index 9fa67a74f0..308e36d9cd 100644 --- a/public/docs/_examples/lifecycle-hooks/dart/lib/after_view_component.dart +++ b/public/docs/_examples/lifecycle-hooks/dart/lib/after_view_component.dart @@ -1,77 +1,117 @@ +// #docplaster // #docregion import 'package:angular2/core.dart'; -import 'child_component.dart'; import 'logger_service.dart'; +////////////////// +// #docregion child-view @Component( - selector: 'after-view-parent', - template: ''' -
-

AfterView

- -
- - - - -
- -

-- Lifecycle Hook Log --

-
{{msg}}
-
- ''', - styles: const [ - '.parent {background: burlywood; padding: 8px; margin:100px 8px;}' - ], - directives: const [ChildComponent], - providers: const [LoggerService]) -class AfterViewParentComponent - implements AfterContentInit, AfterViewChecked, AfterViewInit { - LoggerService _logger; - List hookLog; + selector: 'my-child', + template: '') +class ChildViewComponent { String hero = 'Magneta'; - bool showChild = true; +} +// #enddocregion child-view - // Query for a CONTENT child of type `ChildComponent` - // No such CONTENT child exists! - // This component holds a view but no content of that type. - @ContentChild(ChildComponent) - ChildComponent contentChild; +////////////////////// +@Component( + selector: 'after-view', +// #docregion template + template: ''' +
-- child view begins --
+ +
-- child view ends --
+

{{comment}}

''', +// #enddocregion template + directives: const [ChildViewComponent]) +// #docregion hooks +class AfterViewComponent implements AfterViewChecked, AfterViewInit { + var _prevHero = ''; + + // Query for a VIEW child of type `ChildViewComponent` + @ViewChild(ChildViewComponent) ChildViewComponent viewChild; + +// #enddocregion hooks + final LoggerService _logger; - // Query for a VIEW child of type `ChildComponent` - @ViewChild(ChildComponent) - ChildComponent viewChild; - - String _prevHero; - - AfterViewParentComponent(this._logger) { - hookLog = _logger.logs; - _logger.log('AfterView ctor: $message'); - } - - bool get _hasContentChild => contentChild != null; - bool get _hasViewChild => viewChild != null; - - ///// Hooks - ngAfterContentInit() { - _logger.log( - 'AfterContentInit: There is ${ _hasContentChild ? 'a' : 'no'} content child'); + AfterViewComponent(this._logger) { + _logIt('AfterView constructor'); } +// #docregion hooks ngAfterViewInit() { // viewChild is set after the view has been initialized - _logger.log('AfterViewInit: $message'); + _logIt('AfterViewInit'); + _doSomething(); } ngAfterViewChecked() { // viewChild is updated after the view has been checked - // Called frequently; only report when the hero changes - if (!_hasViewChild || _prevHero == viewChild.hero) return; - _prevHero = viewChild.hero; - _logger.log('AfterViewChecked: $message'); + if (_prevHero == viewChild.hero) { + _logIt('AfterViewChecked (no change)'); + } else { + _prevHero = viewChild.hero; + _logIt('AfterViewChecked'); + _doSomething(); + } + } +// #enddocregion hooks + + String comment = ''; + +// #docregion do-something + // This surrogate for real business logic sets the `comment` + void _doSomething() { + var c = viewChild.hero.length > 10 ? "That's a long name" : ''; + if (c != comment) { + // Wait a tick because the component's view has already been checked + _logger.tick().then((_) { comment = c; }); + } + } +// #enddocregion do-something + + void _logIt(String method) { + var child = viewChild; + var message = "${method}: ${child != null ? child.hero:'no'} child view"; + _logger.log(message); + } +// #docregion hooks + // ... +} +// #enddocregion hooks + +////////////// +@Component( + selector: 'after-view-parent', + template: ''' +
+

AfterView

+ + + +

-- AfterView Logs --

+

+
{{msg}}
+
+ ''', + styles: const ['.parent {background: burlywood}'], + providers: const [LoggerService], + directives: const [AfterViewComponent]) +class AfterViewParentComponent { + final LoggerService _logger; + bool show = true; + + AfterViewParentComponent(this._logger); + + List get logs => _logger.logs; + + void reset() { + logs.clear(); + // quickly remove and reload AfterViewComponent which recreates it + show = false; + _logger.tick().then((_) { show = true; }); } - String get message => - _hasViewChild ? '"${viewChild.hero}" child view' : 'no child view'; } +// #enddocregion diff --git a/public/docs/_examples/lifecycle-hooks/dart/lib/app_component.dart b/public/docs/_examples/lifecycle-hooks/dart/lib/app_component.dart index 3c6b7d6cfb..36a2667f9e 100644 --- a/public/docs/_examples/lifecycle-hooks/dart/lib/app_component.dart +++ b/public/docs/_examples/lifecycle-hooks/dart/lib/app_component.dart @@ -1,29 +1,24 @@ // #docregion import 'package:angular2/core.dart'; -import 'after_content_parent.dart'; +import 'after_content_component.dart'; import 'after_view_component.dart'; import 'counter_component.dart'; +import 'do_check_component.dart'; import 'on_changes_component.dart'; import 'peek_a_boo_parent_component.dart'; import 'spy_component.dart'; @Component( selector: 'my-app', - template: ''' - - - - - - - ''', + templateUrl: 'app_component.html', directives: const [ - PeekABooParentComponent, - OnChangesParentComponent, - AfterViewParentComponent, AfterContentParentComponent, + AfterViewParentComponent, + CounterParentComponent, + DoCheckParentComponent, + OnChangesParentComponent, + PeekABooParentComponent, SpyParentComponent, - CounterParentComponent ]) class AppComponent {} diff --git a/public/docs/_examples/lifecycle-hooks/dart/lib/app_component.html b/public/docs/_examples/lifecycle-hooks/dart/lib/app_component.html new file mode 100644 index 0000000000..d0692e28ac --- /dev/null +++ b/public/docs/_examples/lifecycle-hooks/dart/lib/app_component.html @@ -0,0 +1,37 @@ + +

Component Lifecycle Hooks

+Peek-a-boo: (most) lifecycle hooks
+OnChanges
+DoCheck
+AfterViewInit & AfterViewChecked
+AfterContentInit & AfterContentChecked
+Spy: directive with OnInit & OnDestroy
+Counter: OnChanges + Spy directive
+ + + +back to top + + + +back to top + + + +back to top + + + +back to top + + + +back to top + + + +back to top + + + +back to top diff --git a/public/docs/_examples/lifecycle-hooks/dart/lib/child_component.dart b/public/docs/_examples/lifecycle-hooks/dart/lib/child_component.dart deleted file mode 100644 index 83eebabd6e..0000000000 --- a/public/docs/_examples/lifecycle-hooks/dart/lib/child_component.dart +++ /dev/null @@ -1,19 +0,0 @@ -// #docregion -import 'package:angular2/core.dart'; - -@Component( - selector: 'my-child', - template: ''' -
-
-- child view begins --
-
{{hero}} is my hero.
-
-- child view ends --
-
- ''', - styles: const [ - '.child {background: Yellow; padding: 8px; }', - '.my-child {background: LightYellow; padding: 8px; margin-top: 8px}' - ]) -class ChildComponent { - @Input() String hero; -} diff --git a/public/docs/_examples/lifecycle-hooks/dart/lib/counter_component.dart b/public/docs/_examples/lifecycle-hooks/dart/lib/counter_component.dart index 3113e65392..65ae6d00f6 100644 --- a/public/docs/_examples/lifecycle-hooks/dart/lib/counter_component.dart +++ b/public/docs/_examples/lifecycle-hooks/dart/lib/counter_component.dart @@ -30,10 +30,10 @@ class MyCounter implements OnChanges { } // A change to `counter` is the only change we care about - SimpleChange prop = changes['counter']; - var prev = prop.isFirstChange() ? "{}" : prop.previousValue; - changeLog.add( - 'counter: currentValue = ${prop.currentValue}, previousValue = $prev'); + SimpleChange chng = changes['counter']; + var cur = chng.currentValue; + var prev = chng.isFirstChange() ? "{}" : chng.previousValue; + changeLog.add('counter: currentValue = $cur, previousValue = $prev'); } } @@ -49,29 +49,30 @@ class MyCounter implements OnChanges {

-- Spy Lifecycle Hook Log --

-
{{msg}}
+
{{msg}}
''', - styles: const [ - '.parent {background: gold; padding: 10px; margin:100px 8px;}' - ], + styles: const ['.parent {background: gold;}'], directives: const [MyCounter], providers: const [LoggerService]) class CounterParentComponent { + final LoggerService _logger; num value; - List spyLog = []; - - LoggerService _logger; CounterParentComponent(this._logger) { - spyLog = _logger.logs; reset(); } - updateCounter() => value += 1; + List get logs => _logger.logs; - reset() { + void updateCounter() { + value += 1; + _logger.tick(); + } + + void reset() { _logger.log('-- reset --'); value = 0; + _logger.tick(); } } diff --git a/public/docs/_examples/lifecycle-hooks/dart/lib/do_check_component.dart b/public/docs/_examples/lifecycle-hooks/dart/lib/do_check_component.dart new file mode 100644 index 0000000000..5483b9be8f --- /dev/null +++ b/public/docs/_examples/lifecycle-hooks/dart/lib/do_check_component.dart @@ -0,0 +1,114 @@ +// #docregion +import 'dart:convert'; + +import 'package:angular2/core.dart'; + +class Hero { + String name; + Hero(this.name); + Map toJson() => {'name': name}; +} + +@Component( + selector: 'do-check', + template: ''' +
+

{{hero.name}} can {{power}}

+ +

-- Change Log --

+
{{chg}}
+
+ ''', + styles: const [ + '.hero {background: LightYellow; padding: 8px; margin-top: 8px}', + 'p {background: Yellow; padding: 8px; margin-top: 8px}' + ]) +class DoCheckComponent implements DoCheck, OnChanges { + @Input() + Hero hero; + @Input() + String power; + + bool changeDetected = false; + List changeLog = []; + + String oldHeroName = ''; + String oldPower = ''; + int oldLogLength = 0; + int noChangeCount = 0; + + // #docregion ng-do-check + ngDoCheck() { + if (hero.name != oldHeroName) { + changeDetected = true; + changeLog.add( + 'DoCheck: Hero name changed to "${hero.name}" from "$oldHeroName"'); + oldHeroName = hero.name; + } + + if (power != oldPower) { + changeDetected = true; + changeLog.add('DoCheck: Power changed to "$power" from "$oldPower"'); + oldPower = power; + } + + if (changeDetected) { + noChangeCount = 0; + } else { + // log that hook was called when there was no relevant change. + var count = noChangeCount += 1; + var noChangeMsg = + 'DoCheck called ${count}x when no change to hero or power'; + if (count == 1) { + // add new "no change" message + changeLog.add(noChangeMsg); + } else { + // update last "no change" message + changeLog[changeLog.length - 1] = noChangeMsg; + } + } + + changeDetected = false; + } + // #enddocregion ng-do-check + + // Copied from OnChangesComponent + ngOnChanges(Map changes) { + changes.forEach((String propName, SimpleChange change) { + String cur = JSON.encode(change.currentValue); + String prev = + change.isFirstChange() ? "{}" : JSON.encode(change.previousValue); + changeLog.add('$propName: currentValue = $cur, previousValue = $prev'); + }); + } + + void reset() { + changeDetected = true; + changeLog.clear(); + } +} + +/***************************************/ + +@Component( + selector: 'do-check-parent', + templateUrl: 'on_changes_parent_component.html', + styles: const ['.parent {background: Lavender}'], + directives: const [DoCheckComponent]) +class DoCheckParentComponent { + Hero hero; + String power; + String title = 'DoCheck'; + @ViewChild(DoCheckComponent) + DoCheckComponent childView; + + DoCheckParentComponent() { + reset(); + } + + void reset() { + hero = new Hero('Windstorm'); + power = 'sing'; + childView?.reset(); + } +} diff --git a/public/docs/_examples/lifecycle-hooks/dart/lib/logger_service.dart b/public/docs/_examples/lifecycle-hooks/dart/lib/logger_service.dart index 4809990529..cc048579e0 100644 --- a/public/docs/_examples/lifecycle-hooks/dart/lib/logger_service.dart +++ b/public/docs/_examples/lifecycle-hooks/dart/lib/logger_service.dart @@ -5,15 +5,23 @@ import 'package:angular2/core.dart'; @Injectable() class LoggerService { List logs = []; + String _prevMsg = ''; + int _prevMsgCount = 1; - log(String msg, [bool noTick = false]) { - if (!noTick) { - tick(); + void log(String msg) { + if (msg == _prevMsg) { + // Repeat message; update last log entry with count. + logs[logs.length - 1] = "$msg (${_prevMsgCount += 1}x)"; + } else { + // New message; log it. + _prevMsg = msg; + _prevMsgCount = 1; + logs.add(msg); } - logs.add(msg); } - clear() => logs.clear(); + void clear() => logs.clear(); + // schedules a view refresh to ensure display catches up tick() => new Future(() {}); } diff --git a/public/docs/_examples/lifecycle-hooks/dart/lib/on_changes_component.dart b/public/docs/_examples/lifecycle-hooks/dart/lib/on_changes_component.dart index d133e89a9c..06b9824aaa 100644 --- a/public/docs/_examples/lifecycle-hooks/dart/lib/on_changes_component.dart +++ b/public/docs/_examples/lifecycle-hooks/dart/lib/on_changes_component.dart @@ -6,12 +6,11 @@ import 'package:angular2/core.dart'; class Hero { String name; Hero(this.name); - - Map toJson() => {'name': name}; + Map toJson() => {'name': name}; } @Component( - selector: 'my-hero', + selector: 'on-changes', template: '''

{{hero.name}} can {{power}}

@@ -24,58 +23,48 @@ class Hero { '.hero {background: LightYellow; padding: 8px; margin-top: 8px}', 'p {background: Yellow; padding: 8px; margin-top: 8px}' ]) -class MyHeroComponent implements OnChanges { +class OnChangesComponent implements OnChanges { +// #docregion inputs @Input() Hero hero; @Input() String power; - @Input() bool reset; +// #enddocregion inputs + List changeLog = []; + // #docregion ng-on-changes ngOnChanges(Map changes) { - // Empty the changeLog whenever 'reset' property changes - // hint: this is a way to respond programmatically to external value changes. - if (changes.containsKey('reset')) changeLog.clear(); - - changes.forEach((String key, SimpleChange change) { + changes.forEach((String propName, SimpleChange change) { String cur = JSON.encode(change.currentValue); String prev = change.isFirstChange() ? "{}" : JSON.encode(change.previousValue); - changeLog.add('$key: currentValue = ${cur}, previousValue = $prev'); + changeLog.add('$propName: currentValue = $cur, previousValue = $prev'); }); } + // #enddocregion ng-on-changes + + void reset() { changeLog.clear(); } } @Component( selector: 'on-changes-parent', - template: ''' -
-

OnChanges

- -
Hero.name: does NOT trigger onChanges
-
Power: DOES trigger onChanges
-
triggers onChanges and clears the change log
- - -
- ''', - styles: const [ - '.parent {background: Lavender; padding: 10px; margin:100px 8px;}' - ], - directives: const [MyHeroComponent]) + templateUrl: 'on_changes_parent_component.html', + styles: const ['.parent {background: Lavender}'], + directives: const [OnChangesComponent]) class OnChangesParentComponent { Hero hero; String power; - bool resetTrigger = false; + String title = 'OnChanges'; + @ViewChild(OnChangesComponent) OnChangesComponent childView; OnChangesParentComponent() { reset(); } - reset() { + void reset() { // new Hero object every time; triggers onChange hero = new Hero('Windstorm'); // setting power only triggers onChange if this value is different power = 'sing'; - // always triggers onChange ... which is interpreted as a reset - resetTrigger = !resetTrigger; + childView?.reset(); } } diff --git a/public/docs/_examples/lifecycle-hooks/dart/lib/on_changes_parent_component.html b/public/docs/_examples/lifecycle-hooks/dart/lib/on_changes_parent_component.html new file mode 100644 index 0000000000..7889ce8e91 --- /dev/null +++ b/public/docs/_examples/lifecycle-hooks/dart/lib/on_changes_parent_component.html @@ -0,0 +1,14 @@ +
+

{{title}}

+ + + + +
Power:
Hero.name:
+

+ + + + + +
diff --git a/public/docs/_examples/lifecycle-hooks/dart/lib/peek_a_boo_component.dart b/public/docs/_examples/lifecycle-hooks/dart/lib/peek_a_boo_component.dart index 0a5db8914f..5ce146ea51 100644 --- a/public/docs/_examples/lifecycle-hooks/dart/lib/peek_a_boo_component.dart +++ b/public/docs/_examples/lifecycle-hooks/dart/lib/peek_a_boo_component.dart @@ -4,16 +4,37 @@ import 'package:angular2/core.dart'; import 'logger_service.dart'; -int nextId = 1; +int _nextId = 1; + +// #docregion ngOnInit +class PeekABoo implements OnInit { + final LoggerService _logger; + + PeekABoo(this._logger); + + // implement OnInit's `ngOnInit` method + void ngOnInit() { _logIt('OnInit'); } + + void _logIt(String msg) { + // Don't tick or else + // the AfterContentChecked and AfterViewChecked recurse. + // Let parent call tick() + _logger.log("#${_nextId++} $msg"); + } +} +// #enddocregion ngOnInit @Component( selector: 'peek-a-boo', template: '

Now you see my hero, {{name}}

', styles: const ['p {background: LightYellow; padding: 8px}']) -class PeekABooComponent +// Don't HAVE to mention the Lifecycle Hook interfaces +// unless we want typing and tool support. +class PeekABooComponent extends PeekABoo implements OnChanges, OnInit, + DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit, @@ -23,12 +44,13 @@ class PeekABooComponent int _afterContentCheckedCounter = 1; int _afterViewCheckedCounter = 1; - int _id = nextId++; - LoggerService _logger; int _onChangesCounter = 1; String _verb = 'initialized'; - PeekABooComponent(this._logger); + PeekABooComponent(LoggerService logger) : super(logger) { + var _is = name != null ? 'is' : 'is not'; + _logIt('name $_is known at construction'); + } // Only called if there is an @input variable set by parent. ngOnChanges(Map changes) { @@ -38,41 +60,28 @@ class PeekABooComponent var name = changes['name'].currentValue; messages.add('name $_verb to "$name"'); } else { - messages.add('$propName $_verb'); + messages.add('$propName $_verb'); } }); - _logIt('onChanges (${_onChangesCounter++}): ${messages.join('; ')}'); + _logIt('OnChanges (${_onChangesCounter++}): ${messages.join('; ')}'); _verb = 'changed'; // Next time it will be a change } - ngOnInit() => _logIt('onInit'); - - ngAfterContentInit() => _logIt('afterContentInit'); - - // Called after every change detection check - // of the component (directive) CONTENT // Beware! Called frequently! - ngAfterContentChecked() { - int counter = _afterContentCheckedCounter++; - _logIt('afterContentChecked (${counter})'); - } + // Called in every change detection cycle anywhere on the page + ngDoCheck() => _logIt('DoCheck'); - ngAfterViewInit() => _logIt('afterViewInit'); + ngAfterContentInit() => _logIt('AfterContentInit'); - // Called after every change detection check - // of the component (directive) VIEW // Beware! Called frequently! - ngAfterViewChecked() { - int counter = _afterViewCheckedCounter++; - _logIt('afterViewChecked ($counter)'); - } + // Called in every change detection cycle anywhere on the page + ngAfterContentChecked() { _logIt('AfterContentChecked (${_afterContentCheckedCounter++})'); } - ngOnDestroy() => _logIt('onDestroy'); + ngAfterViewInit() => _logIt('AfterViewInit'); - _logIt(String msg) { - // Don't tick or else - // the AfterContentChecked and AfterViewChecked recurse. - // Let parent call tick() - _logger.log("#$_id $msg", true); - } + // Beware! Called frequently! + // Called in every change detection cycle anywhere on the page + ngAfterViewChecked() { _logIt('AfterViewChecked (${_afterViewCheckedCounter++})'); } + + ngOnDestroy() => _logIt('OnDestroy'); } diff --git a/public/docs/_examples/lifecycle-hooks/dart/lib/peek_a_boo_parent_component.dart b/public/docs/_examples/lifecycle-hooks/dart/lib/peek_a_boo_parent_component.dart index 047ab3b439..a1e4c397d9 100644 --- a/public/docs/_examples/lifecycle-hooks/dart/lib/peek_a_boo_parent_component.dart +++ b/public/docs/_examples/lifecycle-hooks/dart/lib/peek_a_boo_parent_component.dart @@ -19,24 +19,20 @@ import 'peek_a_boo_component.dart';

-- Lifecycle Hook Log --

-
{{msg}}
+
{{msg}}
''', - styles: const [ - '.parent {background: moccasin; padding: 10px; margin:100px 8px}' - ], + styles: const ['.parent {background: moccasin}'], directives: const [PeekABooComponent], providers: const [LoggerService]) class PeekABooParentComponent { + final LoggerService _logger; bool hasChild = false; - List hookLog; - String heroName = 'Windstorm'; - LoggerService _logger; - PeekABooParentComponent(this._logger) { - hookLog = _logger.logs; - } + PeekABooParentComponent(this._logger); + + List get logs => _logger.logs; toggleChild() { hasChild = !hasChild; diff --git a/public/docs/_examples/lifecycle-hooks/dart/lib/spy_component.dart b/public/docs/_examples/lifecycle-hooks/dart/lib/spy_component.dart index f22793d8b6..815c8441d1 100644 --- a/public/docs/_examples/lifecycle-hooks/dart/lib/spy_component.dart +++ b/public/docs/_examples/lifecycle-hooks/dart/lib/spy_component.dart @@ -6,48 +6,35 @@ import 'spy_directive.dart'; @Component( selector: 'spy-parent', - template: ''' -
-

Spy Directive

- - - - - -

-
- {{hero}} -
- -

-- Spy Lifecycle Hook Log --

-
{{msg}}
-
- ''', + templateUrl: 'spy_component.html', styles: const [ - '.parent {background: khaki; padding: 10px; margin:100px 8px}', + '.parent {background: khaki}', '.heroes {background: LightYellow; padding: 0 8px}' ], directives: const [Spy], providers: const [LoggerService]) class SpyParentComponent { + final LoggerService _logger; String newName = 'Herbie'; List heroes = ['Windstorm', 'Magneta']; - List spyLog; - LoggerService _logger; - SpyParentComponent(this._logger) { - spyLog = _logger.logs; - } + SpyParentComponent(this._logger); + + List get logs => _logger.logs; addHero() { if (newName.trim().isNotEmpty) { heroes.add(newName.trim()); newName = ''; + _logger.tick(); } } - reset() { + // removeHero(String hero) { } is not used. + + void reset() { _logger.log('-- reset --'); heroes.clear(); + _logger.tick(); } } diff --git a/public/docs/_examples/lifecycle-hooks/dart/lib/spy_component.html b/public/docs/_examples/lifecycle-hooks/dart/lib/spy_component.html new file mode 100644 index 0000000000..0207792703 --- /dev/null +++ b/public/docs/_examples/lifecycle-hooks/dart/lib/spy_component.html @@ -0,0 +1,16 @@ +
+

Spy Directive

+ + + + + +

+ +
+ {{hero}} +
+ +

-- Spy Lifecycle Hook Log --

+
{{msg}}
+
diff --git a/public/docs/_examples/lifecycle-hooks/dart/lib/spy_directive.dart b/public/docs/_examples/lifecycle-hooks/dart/lib/spy_directive.dart index f7c0b4335f..42db9f591a 100644 --- a/public/docs/_examples/lifecycle-hooks/dart/lib/spy_directive.dart +++ b/public/docs/_examples/lifecycle-hooks/dart/lib/spy_directive.dart @@ -3,14 +3,14 @@ import 'package:angular2/core.dart'; import 'logger_service.dart'; -int nextId = 1; +int _nextId = 1; +// #docregion spy-directive // Spy on any element to which it is applied. // Usage:
...
@Directive(selector: '[mySpy]') class Spy implements OnInit, OnDestroy { - int _id = nextId++; - LoggerService _logger; + final LoggerService _logger; Spy(this._logger); @@ -18,5 +18,6 @@ class Spy implements OnInit, OnDestroy { ngOnDestroy() => _logIt('onDestroy'); - _logIt(String msg) => _logger.log('Spy #$_id $msg'); + _logIt(String msg) => _logger.log('Spy #${_nextId++} $msg'); } +// #enddocregion spy-directive diff --git a/public/docs/_examples/lifecycle-hooks/dart/web/index.html b/public/docs/_examples/lifecycle-hooks/dart/web/index.html index ae668dd2e9..e698da98bc 100644 --- a/public/docs/_examples/lifecycle-hooks/dart/web/index.html +++ b/public/docs/_examples/lifecycle-hooks/dart/web/index.html @@ -4,7 +4,11 @@ Angular 2 Lifecycle Hooks + + + + diff --git a/public/docs/_examples/lifecycle-hooks/dart/web/sample.css b/public/docs/_examples/lifecycle-hooks/dart/web/sample.css new file mode 100644 index 0000000000..df17c897c6 --- /dev/null +++ b/public/docs/_examples/lifecycle-hooks/dart/web/sample.css @@ -0,0 +1,13 @@ +.parent { + color: #666; + margin: 14px 0; + padding: 8px; +} +input { + margin: 4px; + padding: 4px; +} +.comment { + color: red; + font-style: italic; +} diff --git a/public/docs/_examples/lifecycle-hooks/ts/app/after-content.component.ts b/public/docs/_examples/lifecycle-hooks/ts/app/after-content.component.ts index 77b17183e4..6d970f8aa0 100644 --- a/public/docs/_examples/lifecycle-hooks/ts/app/after-content.component.ts +++ b/public/docs/_examples/lifecycle-hooks/ts/app/after-content.component.ts @@ -1,6 +1,6 @@ // #docplaster // #docregion -import {Component, AfterContentChecked, AfterContentInit, ContentChild} from '@angular/core'; +import { AfterContentChecked, AfterContentInit, Component, ContentChild } from '@angular/core'; import {LoggerService} from './logger.service'; @@ -29,49 +29,47 @@ export class ChildComponent { ` }) // #docregion hooks -export class AfterContentComponent implements AfterContentChecked, AfterContentInit { - private _prevHero = ''; +export class AfterContentComponent implements AfterContentChecked, AfterContentInit { + private prevHero = ''; comment = ''; // Query for a CONTENT child of type `ChildComponent` @ContentChild(ChildComponent) contentChild: ChildComponent; // #enddocregion hooks - constructor(private _logger: LoggerService) { - this._logIt('AfterContent constructor'); + constructor(private logger: LoggerService) { + this.logIt('AfterContent constructor'); } // #docregion hooks ngAfterContentInit() { - // viewChild is set after the view has been initialized - this._logIt('AfterContentInit'); - this._doSomething(); + // contentChild is set after the content has been initialized + this.logIt('AfterContentInit'); + this.doSomething(); } ngAfterContentChecked() { - // viewChild is updated after the view has been checked - if (this._prevHero === this.contentChild.hero) { - this._logIt('AfterContentChecked (no change)'); + // contentChild is updated after the content has been checked + if (this.prevHero === this.contentChild.hero) { + this.logIt('AfterContentChecked (no change)'); } else { - this._prevHero = this.contentChild.hero; - this._logIt('AfterContentChecked'); - this._doSomething(); + this.prevHero = this.contentChild.hero; + this.logIt('AfterContentChecked'); + this.doSomething(); } } // #enddocregion hooks - - // #docregion do-something // This surrogate for real business logic sets the `comment` - private _doSomething() { + private doSomething() { this.comment = this.contentChild.hero.length > 10 ? 'That\'s a long name' : ''; } - private _logIt(method: string) { - let vc = this.contentChild; - let message = `${method}: ${vc ? vc.hero : 'no'} child view`; - this._logger.log(message); + private logIt(method: string) { + let child = this.contentChild; + let message = `${method}: ${child ? child.hero : 'no'} child content`; + this.logger.log(message); } // #docregion hooks // ... @@ -85,7 +83,7 @@ export class AfterContentComponent implements AfterContentChecked, AfterContent

AfterContent

-
` + +
` + // #docregion parent-template ` @@ -106,7 +104,7 @@ export class AfterContentParentComponent { logs: string[]; show = true; - constructor(logger: LoggerService) { + constructor(private logger: LoggerService) { this.logs = logger.logs; } @@ -114,6 +112,6 @@ export class AfterContentParentComponent { this.logs.length = 0; // quickly remove and reload AfterContentComponent which recreates it this.show = false; - setTimeout(() => this.show = true, 0); + this.logger.tick_then(() => this.show = true); } } diff --git a/public/docs/_examples/lifecycle-hooks/ts/app/after-view.component.ts b/public/docs/_examples/lifecycle-hooks/ts/app/after-view.component.ts index 66196d54ad..800a43fcc3 100644 --- a/public/docs/_examples/lifecycle-hooks/ts/app/after-view.component.ts +++ b/public/docs/_examples/lifecycle-hooks/ts/app/after-view.component.ts @@ -1,6 +1,6 @@ // #docplaster // #docregion -import {Component, AfterViewChecked, AfterViewInit, ViewChild} from '@angular/core'; +import { AfterViewChecked, AfterViewInit, Component, ViewChild } from '@angular/core'; import {LoggerService} from './logger.service'; @@ -29,36 +29,35 @@ export class ChildViewComponent { {{comment}}

`, - directives: [ChildViewComponent] }) // #docregion hooks export class AfterViewComponent implements AfterViewChecked, AfterViewInit { - private _prevHero = ''; + private prevHero = ''; // Query for a VIEW child of type `ChildViewComponent` @ViewChild(ChildViewComponent) viewChild: ChildViewComponent; // #enddocregion hooks - constructor(private _logger:LoggerService){ - this._logIt('AfterView constructor'); + constructor(private logger:LoggerService){ + this.logIt('AfterView constructor'); } // #docregion hooks ngAfterViewInit() { // viewChild is set after the view has been initialized - this._logIt('AfterViewInit'); - this._doSomething(); + this.logIt('AfterViewInit'); + this.doSomething(); } ngAfterViewChecked() { // viewChild is updated after the view has been checked - if (this._prevHero === this.viewChild.hero) { - this._logIt('AfterViewChecked (no change)'); + if (this.prevHero === this.viewChild.hero) { + this.logIt('AfterViewChecked (no change)'); } else { - this._prevHero = this.viewChild.hero; - this._logIt('AfterViewChecked'); - this._doSomething(); + this.prevHero = this.viewChild.hero; + this.logIt('AfterViewChecked'); + this.doSomething(); } } // #enddocregion hooks @@ -67,19 +66,19 @@ export class AfterViewComponent implements AfterViewChecked, AfterViewInit { // #docregion do-something // This surrogate for real business logic sets the `comment` - private _doSomething() { + private doSomething() { let c = this.viewChild.hero.length > 10 ? "That's a long name" : ''; if (c !== this.comment) { // Wait a tick because the component's view has already been checked - setTimeout(() => this.comment = c, 0); + this.logger.tick_then(() => this.comment = c); } } // #enddocregion do-something - private _logIt(method:string){ - let vc = this.viewChild; - let message = `${method}: ${vc ? vc.hero:'no'} child view` - this._logger.log(message); + private logIt(method:string){ + let child = this.viewChild; + let message = `${method}: ${child ? child.hero:'no'} child view` + this.logger.log(message); } // #docregion hooks // ... @@ -108,7 +107,7 @@ export class AfterViewParentComponent { logs:string[]; show = true; - constructor(logger:LoggerService){ + constructor(private logger: LoggerService) { this.logs = logger.logs; } @@ -116,6 +115,6 @@ export class AfterViewParentComponent { this.logs.length=0; // quickly remove and reload AfterViewComponent which recreates it this.show = false; - setTimeout(() => this.show = true, 0) + this.logger.tick_then(() => this.show = true); } } diff --git a/public/docs/_examples/lifecycle-hooks/ts/app/app.component.ts b/public/docs/_examples/lifecycle-hooks/ts/app/app.component.ts index 8663cdf633..b3d5e45b76 100644 --- a/public/docs/_examples/lifecycle-hooks/ts/app/app.component.ts +++ b/public/docs/_examples/lifecycle-hooks/ts/app/app.component.ts @@ -1,13 +1,13 @@ // #docregion -import {Component} from '@angular/core'; +import { Component } from '@angular/core'; -import {AfterContentParentComponent} from './after-content.component'; -import {AfterViewParentComponent} from './after-view.component'; -import {CounterParentComponent} from './counter.component'; -import {DoCheckParentComponent} from './do-check.component'; -import {OnChangesParentComponent} from './on-changes.component'; -import {PeekABooParentComponent} from './peek-a-boo-parent.component'; -import {SpyParentComponent} from './spy.component'; +import { AfterContentParentComponent } from './after-content.component'; +import { AfterViewParentComponent } from './after-view.component'; +import { CounterParentComponent } from './counter.component'; +import { DoCheckParentComponent } from './do-check.component'; +import { OnChangesParentComponent } from './on-changes.component'; +import { PeekABooParentComponent } from './peek-a-boo-parent.component'; +import { SpyParentComponent } from './spy.component'; @Component({ selector: 'my-app', diff --git a/public/docs/_examples/lifecycle-hooks/ts/app/counter.component.ts b/public/docs/_examples/lifecycle-hooks/ts/app/counter.component.ts index 1c5d3e5cb3..5abf4c6656 100644 --- a/public/docs/_examples/lifecycle-hooks/ts/app/counter.component.ts +++ b/public/docs/_examples/lifecycle-hooks/ts/app/counter.component.ts @@ -4,8 +4,8 @@ import { OnChanges, SimpleChange, } from '@angular/core'; -import {Spy} from './spy.directive'; -import {LoggerService} from './logger.service'; +import { Spy } from './spy.directive'; +import { LoggerService } from './logger.service'; @Component({ selector: 'my-counter', @@ -33,9 +33,9 @@ export class MyCounter implements OnChanges { } // A change to `counter` is the only change we care about - let prop = changes['counter']; - let cur = prop.currentValue; - let prev = JSON.stringify(prop.previousValue); // first time is {}; after is integer + let chng = changes['counter']; + let cur = chng.currentValue; + let prev = JSON.stringify(chng.previousValue); // first time is {}; after is integer this.changeLog.push(`counter: currentValue = ${cur}, previousValue = ${prev}`); } @@ -66,23 +66,23 @@ export class CounterParentComponent { value: number; spyLog: string[] = []; - private _logger: LoggerService; + private logger: LoggerService; constructor(logger: LoggerService) { - this._logger = logger; + this.logger = logger; this.spyLog = logger.logs; this.reset(); } updateCounter() { this.value += 1; - this._logger.tick(); + this.logger.tick(); } reset() { - this._logger.log('-- reset --'); + this.logger.log('-- reset --'); this.value = 0; - this._logger.tick(); + this.logger.tick(); } } diff --git a/public/docs/_examples/lifecycle-hooks/ts/app/do-check.component.ts b/public/docs/_examples/lifecycle-hooks/ts/app/do-check.component.ts index acf604698a..64b998c25a 100644 --- a/public/docs/_examples/lifecycle-hooks/ts/app/do-check.component.ts +++ b/public/docs/_examples/lifecycle-hooks/ts/app/do-check.component.ts @@ -1,6 +1,6 @@ /* tslint:disable:forin */ // #docregion -import {Component, DoCheck, OnChanges, Input, SimpleChange, ViewChild} from '@angular/core'; +import { Component, DoCheck, Input, OnChanges, SimpleChange, ViewChild } from '@angular/core'; class Hero { constructor(public name: string) {} @@ -69,9 +69,9 @@ export class DoCheckComponent implements DoCheck, OnChanges { // Copied from OnChangesComponent ngOnChanges(changes: {[propertyName: string]: SimpleChange}) { for (let propName in changes) { - let prop = changes[propName]; - let cur = JSON.stringify(prop.currentValue); - let prev = JSON.stringify(prop.previousValue); + let chng = changes[propName]; + let cur = JSON.stringify(chng.currentValue); + let prev = JSON.stringify(chng.previousValue); this.changeLog.push(`OnChanges: ${propName}: currentValue = ${cur}, previousValue = ${prev}`); } } diff --git a/public/docs/_examples/lifecycle-hooks/ts/app/logger.service.ts b/public/docs/_examples/lifecycle-hooks/ts/app/logger.service.ts index e345663bfd..56ddaf9063 100644 --- a/public/docs/_examples/lifecycle-hooks/ts/app/logger.service.ts +++ b/public/docs/_examples/lifecycle-hooks/ts/app/logger.service.ts @@ -1,4 +1,4 @@ -import {Injectable} from '@angular/core'; +import { Injectable } from '@angular/core'; @Injectable() export class LoggerService { @@ -21,9 +21,6 @@ export class LoggerService { clear() { this.logs.length = 0; } // schedules a view refresh to ensure display catches up - tick() { - setTimeout(() => { - // console.log('tick') - }, 0); - } + tick() { this.tick_then(() => { }); } + tick_then(fn: () => any) { setTimeout(fn, 0); } } diff --git a/public/docs/_examples/lifecycle-hooks/ts/app/main.ts b/public/docs/_examples/lifecycle-hooks/ts/app/main.ts index d593721c00..1e9be2601e 100644 --- a/public/docs/_examples/lifecycle-hooks/ts/app/main.ts +++ b/public/docs/_examples/lifecycle-hooks/ts/app/main.ts @@ -1,4 +1,5 @@ -import {bootstrap} from '@angular/platform-browser-dynamic'; -import {AppComponent} from './app.component'; +import { bootstrap } from '@angular/platform-browser-dynamic'; + +import { AppComponent } from './app.component'; bootstrap(AppComponent).catch(err => console.error(err)); diff --git a/public/docs/_examples/lifecycle-hooks/ts/app/on-changes.component.ts b/public/docs/_examples/lifecycle-hooks/ts/app/on-changes.component.ts index 8000e803cb..81de85633a 100644 --- a/public/docs/_examples/lifecycle-hooks/ts/app/on-changes.component.ts +++ b/public/docs/_examples/lifecycle-hooks/ts/app/on-changes.component.ts @@ -1,8 +1,8 @@ /* tslint:disable:forin */ // #docregion import { - Component, Input, ViewChild, - OnChanges, SimpleChange + Component, Input, OnChanges, + SimpleChange, ViewChild } from '@angular/core'; @@ -36,9 +36,9 @@ export class OnChangesComponent implements OnChanges { // #docregion ng-on-changes ngOnChanges(changes: {[propertyName: string]: SimpleChange}) { for (let propName in changes) { - let prop = changes[propName]; - let cur = JSON.stringify(prop.currentValue); - let prev = JSON.stringify(prop.previousValue); + let chng = changes[propName]; + let cur = JSON.stringify(chng.currentValue); + let prev = JSON.stringify(chng.previousValue); this.changeLog.push(`${propName}: currentValue = ${cur}, previousValue = ${prev}`); } } diff --git a/public/docs/_examples/lifecycle-hooks/ts/app/peek-a-boo-parent.component.ts b/public/docs/_examples/lifecycle-hooks/ts/app/peek-a-boo-parent.component.ts index 5d7ff28047..e218dc3fc5 100644 --- a/public/docs/_examples/lifecycle-hooks/ts/app/peek-a-boo-parent.component.ts +++ b/public/docs/_examples/lifecycle-hooks/ts/app/peek-a-boo-parent.component.ts @@ -1,7 +1,8 @@ // #docregion -import {Component} from '@angular/core'; -import {PeekABooComponent} from './peek-a-boo.component'; -import {LoggerService} from './logger.service'; +import { Component } from '@angular/core'; + +import { PeekABooComponent } from './peek-a-boo.component'; +import { LoggerService } from './logger.service'; @Component({ selector: 'peek-a-boo-parent', @@ -31,10 +32,10 @@ export class PeekABooParentComponent { hookLog: string[]; heroName = 'Windstorm'; - private _logger: LoggerService; + private logger: LoggerService; constructor(logger: LoggerService) { - this._logger = logger; + this.logger = logger; this.hookLog = logger.logs; } @@ -42,13 +43,13 @@ export class PeekABooParentComponent { this.hasChild = !this.hasChild; if (this.hasChild) { this.heroName = 'Windstorm'; - this._logger.clear(); // clear log on create + this.logger.clear(); // clear log on create } - this._logger.tick(); + this.logger.tick(); } updateHero() { this.heroName += '!'; - this._logger.tick(); + this.logger.tick(); } } diff --git a/public/docs/_examples/lifecycle-hooks/ts/app/peek-a-boo.component.ts b/public/docs/_examples/lifecycle-hooks/ts/app/peek-a-boo.component.ts index 2c6bfd5647..1485f2992a 100644 --- a/public/docs/_examples/lifecycle-hooks/ts/app/peek-a-boo.component.ts +++ b/public/docs/_examples/lifecycle-hooks/ts/app/peek-a-boo.component.ts @@ -1,12 +1,13 @@ import { - OnChanges, SimpleChange, - OnInit, - DoCheck, - AfterContentInit, AfterContentChecked, - AfterViewInit, + AfterContentInit, AfterViewChecked, - OnDestroy + AfterViewInit, + DoCheck, + OnChanges, + OnDestroy, + OnInit, + SimpleChange } from '@angular/core'; import {Component, Input} from '@angular/core'; import {LoggerService} from './logger.service'; @@ -15,13 +16,13 @@ let nextId = 1; // #docregion ngOnInit export class PeekABoo implements OnInit { - constructor(private _logger: LoggerService) { } + constructor(private logger: LoggerService) { } // implement OnInit's `ngOnInit` method - ngOnInit() { this._logIt(`OnInit`); } + ngOnInit() { this.logIt(`OnInit`); } - protected _logIt(msg: string) { - this._logger.log(`#${nextId++} ${msg}`); + protected logIt(msg: string) { + this.logger.log(`#${nextId++} ${msg}`); } } // #enddocregion ngOnInit @@ -40,13 +41,13 @@ export class PeekABooComponent extends PeekABoo implements OnDestroy { @Input() name: string; - private _verb = 'initialized'; + private verb = 'initialized'; constructor(logger: LoggerService) { super(logger); let is = this.name ? 'is' : 'is not'; - this._logIt(`name ${is} known at construction`); + this.logIt(`name ${is} known at construction`); } // only called for/if there is an @input variable set by parent. @@ -55,30 +56,30 @@ export class PeekABooComponent extends PeekABoo implements for (let propName in changes) { if (propName === 'name') { let name = changes['name'].currentValue; - changesMsgs.push(`name ${this._verb} to "${name}"`); + changesMsgs.push(`name ${this.verb} to "${name}"`); } else { - changesMsgs.push(propName + ' ' + this._verb); + changesMsgs.push(propName + ' ' + this.verb); } } - this._logIt(`OnChanges: ${changesMsgs.join('; ')}`); - this._verb = 'changed'; // next time it will be a change + this.logIt(`OnChanges: ${changesMsgs.join('; ')}`); + this.verb = 'changed'; // next time it will be a change } // Beware! Called frequently! // Called in every change detection cycle anywhere on the page - ngDoCheck() { this._logIt(`DoCheck`); } + ngDoCheck() { this.logIt(`DoCheck`); } - ngAfterContentInit() { this._logIt(`AfterContentInit`); } + ngAfterContentInit() { this.logIt(`AfterContentInit`); } // Beware! Called frequently! // Called in every change detection cycle anywhere on the page - ngAfterContentChecked() { this._logIt(`AfterContentChecked`); } + ngAfterContentChecked() { this.logIt(`AfterContentChecked`); } - ngAfterViewInit() { this._logIt(`AfterViewInit`); } + ngAfterViewInit() { this.logIt(`AfterViewInit`); } // Beware! Called frequently! // Called in every change detection cycle anywhere on the page - ngAfterViewChecked() { this._logIt(`AfterViewChecked`); } + ngAfterViewChecked() { this.logIt(`AfterViewChecked`); } - ngOnDestroy() { this._logIt(`OnDestroy`); } + ngOnDestroy() { this.logIt(`OnDestroy`); } } diff --git a/public/docs/_examples/lifecycle-hooks/ts/app/spy.component.html b/public/docs/_examples/lifecycle-hooks/ts/app/spy.component.html new file mode 100644 index 0000000000..782435b961 --- /dev/null +++ b/public/docs/_examples/lifecycle-hooks/ts/app/spy.component.html @@ -0,0 +1,16 @@ +
+

Spy Directive

+ + + + + +

+ +
+ {{hero}} +
+ +

-- Spy Lifecycle Hook Log --

+
{{msg}}
+
diff --git a/public/docs/_examples/lifecycle-hooks/ts/app/spy.component.ts b/public/docs/_examples/lifecycle-hooks/ts/app/spy.component.ts index d7eef1597e..9711fd31bb 100644 --- a/public/docs/_examples/lifecycle-hooks/ts/app/spy.component.ts +++ b/public/docs/_examples/lifecycle-hooks/ts/app/spy.component.ts @@ -1,29 +1,12 @@ // #docregion -import {Component} from '@angular/core'; -import {LoggerService} from './logger.service'; -import {Spy} from './spy.directive'; +import { Component } from '@angular/core'; + +import { LoggerService } from './logger.service'; +import { Spy } from './spy.directive'; @Component({ selector: 'spy-parent', - template: ` -
-

Spy Directive

-

- - - -

` + -// #docregion template - `
- {{hero}} -
` -// #enddocregion template -+ `

-- Spy Lifecycle Hook Log --

-
{{msg}}
-
- `, + templateUrl: 'app/spy.component.html', styles: [ '.parent {background: khaki;}', '.heroes {background: LightYellow; padding: 0 8px}' @@ -36,24 +19,24 @@ export class SpyParentComponent { heroes: string[] = ['Windstorm', 'Magneta']; spyLog: string[]; - constructor(private _logger: LoggerService) { - this.spyLog = _logger.logs; + constructor(private logger: LoggerService) { + this.spyLog = logger.logs; } addHero() { if (this.newName.trim()) { this.heroes.push(this.newName.trim()); this.newName = ''; - this._logger.tick(); + this.logger.tick(); } } removeHero(hero: string) { this.heroes.splice(this.heroes.indexOf(hero), 1); - this._logger.tick(); + this.logger.tick(); } reset() { - this._logger.log('-- reset --'); + this.logger.log('-- reset --'); this.heroes.length = 0; - this._logger.tick(); + this.logger.tick(); } } diff --git a/public/docs/_examples/lifecycle-hooks/ts/app/spy.directive.ts b/public/docs/_examples/lifecycle-hooks/ts/app/spy.directive.ts index 5eb311aadf..ba7582ea50 100644 --- a/public/docs/_examples/lifecycle-hooks/ts/app/spy.directive.ts +++ b/public/docs/_examples/lifecycle-hooks/ts/app/spy.directive.ts @@ -1,6 +1,7 @@ // #docregion import {Directive, OnInit, OnDestroy} from '@angular/core'; -import {LoggerService} from './logger.service'; + +import {LoggerService} from './logger.service'; let nextId = 1; @@ -10,14 +11,14 @@ let nextId = 1; @Directive({selector: '[mySpy]'}) export class Spy implements OnInit, OnDestroy { - constructor(private _logger: LoggerService) { } + constructor(private logger: LoggerService) { } - ngOnInit() { this._logIt(`onInit`); } + ngOnInit() { this.logIt(`onInit`); } - ngOnDestroy() { this._logIt(`onDestroy`); } + ngOnDestroy() { this.logIt(`onDestroy`); } - private _logIt(msg: string) { - this._logger.log(`Spy #${nextId++} ${msg}`); + private logIt(msg: string) { + this.logger.log(`Spy #${nextId++} ${msg}`); } } // #enddocregion spy-directive diff --git a/public/docs/_examples/lifecycle-hooks/ts/index.html b/public/docs/_examples/lifecycle-hooks/ts/index.html index 68c0618721..41ad4848b0 100644 --- a/public/docs/_examples/lifecycle-hooks/ts/index.html +++ b/public/docs/_examples/lifecycle-hooks/ts/index.html @@ -17,7 +17,7 @@ diff --git a/public/docs/_examples/package.json b/public/docs/_examples/package.json index f1017685de..fa3fa42886 100644 --- a/public/docs/_examples/package.json +++ b/public/docs/_examples/package.json @@ -13,47 +13,64 @@ "tsc": "tsc", "tsc:w": "tsc -w", "typings": "typings", - "webdriver:update": "webdriver-manager update" + "webdriver:update": "webdriver-manager update", + "start:webpack": "webpack-dev-server --inline --progress --port 8080", + "test:webpack": "karma start karma.webpack.conf.js", + "build:webpack": "rimraf dist && webpack --config config/webpack.prod.js --progress --profile --bail" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { - "@angular/common": "2.0.0-rc.0", - "@angular/compiler": "2.0.0-rc.0", - "@angular/core": "2.0.0-rc.0", - "@angular/http": "2.0.0-rc.0", - "@angular/platform-browser": "2.0.0-rc.0", - "@angular/platform-browser-dynamic": "2.0.0-rc.0", - "@angular/router-deprecated": "2.0.0-rc.0", - "@angular/upgrade": "2.0.0-rc.0", - + "@angular/common": "2.0.0-rc.1", + "@angular/compiler": "2.0.0-rc.1", + "@angular/core": "2.0.0-rc.1", + "@angular/http": "2.0.0-rc.1", + "@angular/platform-browser": "2.0.0-rc.1", + "@angular/platform-browser-dynamic": "2.0.0-rc.1", + "@angular/router": "2.0.0-rc.1", + "@angular/router-deprecated": "2.0.0-rc.1", + "@angular/upgrade": "2.0.0-rc.1", "systemjs": "0.19.27", "es6-shim": "^0.35.0", "reflect-metadata": "^0.1.3", "rxjs": "5.0.0-beta.6", "zone.js": "^0.6.12", - - "angular2-in-memory-web-api": "0.0.6", + "angular2-in-memory-web-api": "0.0.7", "bootstrap": "^3.3.6" }, "devDependencies": { - "concurrently": "^2.0.0", - "lite-server": "^2.2.0", - "typescript": "^1.8.10", - "typings": "^0.8.1", - "canonical-path": "0.0.2", + "concurrently": "^2.0.0", + "css-loader": "^0.23.1", + "extract-text-webpack-plugin": "^1.0.1", + "file-loader": "^0.8.5", + "html-loader": "^0.4.3", + "html-webpack-plugin": "^2.16.1", "http-server": "^0.9.0", - "lodash": "^4.11.1", - "jasmine-core": "~2.4.1", + "jasmine-core": "^2.4.1", "karma": "^0.13.22", "karma-chrome-launcher": "^0.2.3", "karma-cli": "^0.1.2", "karma-htmlfile-reporter": "^0.2.2", "karma-jasmine": "^0.3.8", + "karma-phantomjs-launcher": "^1.0.0", + "karma-sourcemap-loader": "^0.3.7", + "karma-webpack": "^1.7.0", + "lite-server": "^2.2.0", + "lodash": "^4.11.1", + "null-loader": "^0.1.1", + "phantomjs-prebuilt": "^2.1.7", "protractor": "^3.3.0", - "rimraf": "^2.5.2" + "raw-loader": "^0.5.1", + "rimraf": "^2.5.2", + "style-loader": "^0.13.1", + "ts-loader": "^0.8.2", + "typescript": "^1.8.10", + "typings": "^0.8.1", + "webpack": "^1.13.0", + "webpack-dev-server": "^1.14.1", + "webpack-merge": "^0.12.0" }, "repository": {} } diff --git a/public/docs/_examples/pipes/dart/example-config.json b/public/docs/_examples/pipes/dart/example-config.json new file mode 100644 index 0000000000..e69de29bb2 diff --git a/public/docs/_examples/pipes/dart/lib/app_component.dart b/public/docs/_examples/pipes/dart/lib/app_component.dart index 1edd92c0f4..85b32279a2 100644 --- a/public/docs/_examples/pipes/dart/lib/app_component.dart +++ b/public/docs/_examples/pipes/dart/lib/app_component.dart @@ -1,20 +1,26 @@ +// #docregion import 'package:angular2/angular2.dart'; +import 'flying_heroes_component.dart'; import 'hero_async_message_component.dart'; +import 'hero_birthday1_component.dart'; import 'hero_birthday2_component.dart'; import 'hero_list_component.dart'; -import 'power_booster.dart'; -import 'power_boost_calculator.dart'; +import 'power_boost_calculator_component.dart'; +import 'power_booster_component.dart'; @Component( selector: 'my-app', templateUrl: 'app_component.html', directives: const [ + FlyingHeroesComponent, + FlyingHeroesImpureComponent, HeroAsyncMessageComponent, HeroBirthday, + HeroBirthday2, HeroListComponent, + PowerBoostCalculator, PowerBooster, - PowerBoostCalculator ]) class AppComponent { DateTime birthday = new DateTime(1988, 4, 15); // April 15, 1988 diff --git a/public/docs/_examples/pipes/dart/lib/app_component.html b/public/docs/_examples/pipes/dart/lib/app_component.html index feed0f1908..a27d587fcd 100644 --- a/public/docs/_examples/pipes/dart/lib/app_component.html +++ b/public/docs/_examples/pipes/dart/lib/app_component.html @@ -1,36 +1,83 @@ + +

Pipes

+Happy Birthday v1
+Birthday DatePipe
+Happy Birthday v2
+Birthday Pipe Chaining
+Power Booster custom pipe
+Power Boost Calculator custom pipe with params
+Flying Heroes filter pipe (pure)
+Flying Heroes filter pipe (impure)
+Async Hero Message and AsyncPipe
+Hero List with caching FetchJsonPipe
+ +
+ +

Hero Birthday v1

+ + +
+ +

Birthday DatePipe

+ +

The hero's birthday is {{ birthday | date }}

+ + + +

The hero's birthday is {{ birthday | date:"MM/dd/yy" }}

+ + +
+ +

Hero Birthday v2

+ + +
+ +

Birthday Pipe Chaining

+

+ + The chained hero's birthday is + {{ birthday | date | uppercase}} + +

+ +

+ + The chained hero's birthday is + {{ birthday | date:'fullDate' | uppercase}} + +

+

+ + The chained hero's birthday is + {{ ( birthday | date:'fullDate' ) | uppercase}} + +

+
+ + + +
+ +loading + +
+ + + +
+ + + +
+
+ -
-

The hero's birthday is {{ birthday | date }}

- -

The hero's birthday is {{ birthday | date:"MM/dd/yy" }}

- -
-

Hero Birthday v.2

-loading... -
- - -

- The chained hero's birthday is - {{ birthday | date | uppercase}} -

- -

- The chained hero's birthday is - {{ birthday | date:'fullDate' | uppercase}} -

-

- The chained hero's birthday is - {{ ( birthday | date:'fullDate' ) | uppercase}} -

-
-loading... - -
-loading .. +
diff --git a/public/docs/_examples/pipes/dart/lib/exponential_strength_pipe.dart b/public/docs/_examples/pipes/dart/lib/exponential_strength_pipe.dart index 6e047a77b8..1e66b9c791 100644 --- a/public/docs/_examples/pipes/dart/lib/exponential_strength_pipe.dart +++ b/public/docs/_examples/pipes/dart/lib/exponential_strength_pipe.dart @@ -1,5 +1,5 @@ +// #docregion import 'dart:math' as math; - import 'package:angular2/angular2.dart'; /* @@ -13,11 +13,13 @@ import 'package:angular2/angular2.dart'; */ @Pipe(name: 'exponentialStrength') class ExponentialStrengthPipe extends PipeTransform { - transform(dynamic value, [List args]) { - var v = int.parse(value.toString(), onError: (source) => 0); - var p = args.isEmpty + num transform(dynamic _value, [List args]) { + var exponent = args.isEmpty ? 1 - : int.parse(args.first.toString(), onError: (source) => 1); - return math.pow(v, p); + : args.first is num + ? args.first + : num.parse(args.first.toString(), (_) => 1); + var value = _value is num ? _value : num.parse(_value.toString(), (_) => 0); + return math.pow(value, exponent); } } diff --git a/public/docs/_examples/pipes/dart/lib/fetch_json_pipe.dart b/public/docs/_examples/pipes/dart/lib/fetch_json_pipe.dart index 748f515f2a..4ff5eab8d9 100644 --- a/public/docs/_examples/pipes/dart/lib/fetch_json_pipe.dart +++ b/public/docs/_examples/pipes/dart/lib/fetch_json_pipe.dart @@ -1,7 +1,6 @@ // #docregion -import 'dart:html'; -import 'dart:async'; import 'dart:convert'; +import 'dart:html'; import 'package:angular2/angular2.dart'; @@ -9,15 +8,17 @@ import 'package:angular2/angular2.dart'; @Pipe(name: 'fetch', pure: false) // #enddocregion pipe-metadata class FetchJsonPipe extends PipeTransform { - dynamic _fetchedValue; - Future _fetchPromise; + dynamic _fetchedJson; + String _prevUrl; - transform(dynamic url, [List args]) { - if (_fetchPromise == null) { - _fetchPromise = new Future(() async { - _fetchedValue = JSON.decode(await HttpRequest.getString(url)); - }); + dynamic transform(dynamic url, [List args]) { + if (url != _prevUrl) { + _prevUrl = url; + _fetchedJson = null; + HttpRequest.getString(url).then((s) { + _fetchedJson = JSON.decode(s); + }); } - return _fetchedValue; + return _fetchedJson; } } diff --git a/public/docs/_examples/pipes/dart/lib/flying_heroes_component.dart b/public/docs/_examples/pipes/dart/lib/flying_heroes_component.dart new file mode 100644 index 0000000000..040bc6ae37 --- /dev/null +++ b/public/docs/_examples/pipes/dart/lib/flying_heroes_component.dart @@ -0,0 +1,66 @@ +// #docplaster +// #docregion +import 'package:angular2/angular2.dart'; +import 'flying_heroes_pipe.dart'; +import 'heroes.dart'; + +@Component( + selector: 'flying-heroes', + templateUrl: 'flying_heroes_component.html', + styles: const ['#flyers, #all {font-style: italic}'], + pipes: const [FlyingHeroesPipe]) +// #docregion v1 +class FlyingHeroesComponent { + List heroes; + bool canFly = true; + // #enddocregion v1 + bool mutate = true; + String title = 'Flying Heroes (pure pipe)'; + + // #docregion v1 + FlyingHeroesComponent() { + reset(); + } + + void addHero(String name) { + name = name.trim(); + if (name.isEmpty) return; + + var hero = new Hero(name, canFly); + // #enddocregion v1 + if (mutate) { + // Pure pipe won't update display because heroes list + // reference is unchanged; Impure pipe will display. + // #docregion v1, push + heroes.add(hero); + // #enddocregion v1, push + } else { + // Pipe updates display because heroes list is a new object + // #docregion concat + heroes = new List.from(heroes)..add(hero); + // #enddocregion concat + } + // #docregion v1 + } + + void reset() { + heroes = new List.from(mockHeroes); + } +} +// #enddocregion v1 + +//\\\\ Identical except for impure pipe \\\\\\ +// #docregion impure-component +@Component( + selector: 'flying-heroes-impure', + templateUrl: 'flying_heroes_component.html', + // #enddocregion impure-component + styles: const ['.flyers, .all {font-style: italic}'], + // #docregion impure-component + pipes: const [FlyingHeroesImpurePipe]) +class FlyingHeroesImpureComponent extends FlyingHeroesComponent { + FlyingHeroesImpureComponent() { + title = 'Flying Heroes (impure pipe)'; + } +} +// #docregion impure-component diff --git a/public/docs/_examples/pipes/dart/lib/flying_heroes_component.html b/public/docs/_examples/pipes/dart/lib/flying_heroes_component.html new file mode 100644 index 0000000000..5d2a5d8a40 --- /dev/null +++ b/public/docs/_examples/pipes/dart/lib/flying_heroes_component.html @@ -0,0 +1,38 @@ + + +

{{title}}

+

+ +New hero: + + + can fly +

+

+ Mutate array + + + +

+ +

Heroes who fly (piped)

+
+ +
+ {{hero.name}} +
+ +
+ +

All Heroes (no pipe)

+
+ + +
+ {{hero.name}} +
+ + +
diff --git a/public/docs/_examples/pipes/dart/lib/flying_heroes_pipe.dart b/public/docs/_examples/pipes/dart/lib/flying_heroes_pipe.dart new file mode 100644 index 0000000000..fe20fe1ea3 --- /dev/null +++ b/public/docs/_examples/pipes/dart/lib/flying_heroes_pipe.dart @@ -0,0 +1,19 @@ +// #docregion +// #docregion pure +import 'package:angular2/angular2.dart'; +import 'heroes.dart'; + +@Pipe(name: 'flyingHeroes') +class FlyingHeroesPipe extends PipeTransform { + // #docregion filter + List transform(dynamic value, [List args]) => + value.where((hero) => hero.canFly).toList(); + // #enddocregion filter +} +// #enddocregion pure + +// Identical except for the pure flag +// #docregion impure, pipe-decorator +@Pipe(name: 'flyingHeroes', pure: false) +// #enddocregion pipe-decorator +class FlyingHeroesImpurePipe extends FlyingHeroesPipe {} diff --git a/public/docs/_examples/pipes/dart/lib/hero_async_message_component.dart b/public/docs/_examples/pipes/dart/lib/hero_async_message_component.dart index 52d1851a86..c3ab0dee94 100644 --- a/public/docs/_examples/pipes/dart/lib/hero_async_message_component.dart +++ b/public/docs/_examples/pipes/dart/lib/hero_async_message_component.dart @@ -1,12 +1,32 @@ +// #docregion import 'dart:async'; import 'package:angular2/angular2.dart'; @Component( - selector: 'hero-message', template: 'Message: {{delayedMessage | async}}') + selector: 'hero-message', + template: ''' +

Async Hero Message and AsyncPipe

+

Message: {{ message | async }}

+ + ''') class HeroAsyncMessageComponent { - Future delayedMessage = - new Future.delayed(new Duration(milliseconds: 500), () { - return 'You are my Hero!'; - }); + static const _msgEventDelay = const Duration(milliseconds: 500); + + Stream message; + + HeroAsyncMessageComponent() { + resend(); + } + + void resend() { + message = + new Stream.periodic(_msgEventDelay, (i) => _msgs[i]).take(_msgs.length); + } + + List _msgs = [ + 'You are my hero!', + 'You are the best hero!', + 'Will you be my hero?' + ]; } diff --git a/public/docs/_examples/pipes/dart/lib/hero_birthday1_component.dart b/public/docs/_examples/pipes/dart/lib/hero_birthday1_component.dart index 4b8f3a33f2..accb756c37 100644 --- a/public/docs/_examples/pipes/dart/lib/hero_birthday1_component.dart +++ b/public/docs/_examples/pipes/dart/lib/hero_birthday1_component.dart @@ -1,10 +1,12 @@ +// #docregion import 'package:angular2/angular2.dart'; @Component( selector: 'hero-birthday', - template: ''' -

The hero's birthday is {{ birthday | date }}

- ''') + // #docregion hero-birthday-template + template: "

The hero's birthday is {{ birthday | date }}

" + // #enddocregion hero-birthday-template + ) class HeroBirthday { DateTime birthday = new DateTime(1988, 4, 15); // April 15, 1988 } diff --git a/public/docs/_examples/pipes/dart/lib/hero_birthday2_component.dart b/public/docs/_examples/pipes/dart/lib/hero_birthday2_component.dart index 032888080e..eb76d84859 100644 --- a/public/docs/_examples/pipes/dart/lib/hero_birthday2_component.dart +++ b/public/docs/_examples/pipes/dart/lib/hero_birthday2_component.dart @@ -1,12 +1,17 @@ +// #docregion import 'package:angular2/angular2.dart'; @Component( - selector: 'hero-birthday', + selector: 'hero-birthday2', + // #docregion template template: '''

The hero's birthday is {{ birthday | date:format }}

- ''') -class HeroBirthday { + ''' + // #enddocregion template + ) +// #docregion class +class HeroBirthday2 { DateTime birthday = new DateTime(1988, 4, 15); // April 15, 1988 bool toggle = true; diff --git a/public/docs/_examples/pipes/dart/lib/hero_list_component.dart b/public/docs/_examples/pipes/dart/lib/hero_list_component.dart index 50ae1a5bf1..6088fa547f 100644 --- a/public/docs/_examples/pipes/dart/lib/hero_list_component.dart +++ b/public/docs/_examples/pipes/dart/lib/hero_list_component.dart @@ -1,19 +1,21 @@ +// #docregion import 'package:angular2/angular2.dart'; import 'fetch_json_pipe.dart'; @Component( selector: 'hero-list', + // #docregion template template: ''' -

Heroes from JSON File

+

Heroes from JSON File

-
- {{hero['name']}} -
+
+ {{hero['name']}} +
-

Heroes as JSON: - {{'heroes.json' | fetch | json}} -

-''', +

Heroes as JSON: + {{'heroes.json' | fetch | json}} +

+ ''', pipes: const [FetchJsonPipe]) class HeroListComponent {} diff --git a/public/docs/_examples/pipes/dart/lib/heroes.dart b/public/docs/_examples/pipes/dart/lib/heroes.dart new file mode 100644 index 0000000000..2c06ca83cc --- /dev/null +++ b/public/docs/_examples/pipes/dart/lib/heroes.dart @@ -0,0 +1,15 @@ +class Hero { + final String name; + final bool canFly; + + const Hero(this.name, this.canFly); + + String toString() => "$name (${canFly ? 'can fly' : 'doesn\'t fly'})"; +} + +const List mockHeroes = const [ + const Hero("Windstorm", true), + const Hero("Bombasto", false), + const Hero("Magneto", false), + const Hero("Tornado", true), +]; diff --git a/public/docs/_examples/pipes/dart/lib/power_boost_calculator.dart b/public/docs/_examples/pipes/dart/lib/power_boost_calculator.dart deleted file mode 100644 index 1d7f9558cd..0000000000 --- a/public/docs/_examples/pipes/dart/lib/power_boost_calculator.dart +++ /dev/null @@ -1,21 +0,0 @@ -import 'package:angular2/angular2.dart'; - -import 'exponential_strength_pipe.dart'; - -@Component( - selector: 'power-boost-calculator', - template: ''' -

Power Boost Calculator

-
Normal power:
-
Boost factor:
-

- Super Hero Power: {{power | exponentialStrength: factor}} -

-''', - pipes: const [ExponentialStrengthPipe], - directives: const [COMMON_DIRECTIVES]) -class PowerBoostCalculator { - // XXX: These should be ints, but that causes exceptions in checked mode. - String power = '5'; - String factor = '1'; -} diff --git a/public/docs/_examples/pipes/dart/lib/power_boost_calculator_component.dart b/public/docs/_examples/pipes/dart/lib/power_boost_calculator_component.dart new file mode 100644 index 0000000000..7c726ce511 --- /dev/null +++ b/public/docs/_examples/pipes/dart/lib/power_boost_calculator_component.dart @@ -0,0 +1,19 @@ +// #docregion +import 'package:angular2/angular2.dart'; +import 'exponential_strength_pipe.dart'; + +@Component( + selector: 'power-boost-calculator', + template: ''' +

Power Boost Calculator

+
Normal power:
+
Boost factor:
+

+ Super Hero Power: {{power | exponentialStrength: factor}} +

+ ''', + pipes: const [ExponentialStrengthPipe]) +class PowerBoostCalculator { + num power = 5; + num factor = 1; +} diff --git a/public/docs/_examples/pipes/dart/lib/power_booster.dart b/public/docs/_examples/pipes/dart/lib/power_booster_component.dart similarity index 64% rename from public/docs/_examples/pipes/dart/lib/power_booster.dart rename to public/docs/_examples/pipes/dart/lib/power_booster_component.dart index 194abe1b0c..9152a2cc52 100644 --- a/public/docs/_examples/pipes/dart/lib/power_booster.dart +++ b/public/docs/_examples/pipes/dart/lib/power_booster_component.dart @@ -1,13 +1,12 @@ +// #docregion import 'package:angular2/angular2.dart'; import 'exponential_strength_pipe.dart'; @Component( selector: 'power-booster', template: ''' -

Power Booster

-

- Super power boost: {{2 | exponentialStrength: 10}} -

-''', +

Power Booster

+

Super power boost: {{2 | exponentialStrength: 10}}

+ ''', pipes: const [ExponentialStrengthPipe]) class PowerBooster {} diff --git a/public/docs/_examples/pipes/dart/pubspec.yaml b/public/docs/_examples/pipes/dart/pubspec.yaml index 848c11cd1c..ff1fc42531 100644 --- a/public/docs/_examples/pipes/dart/pubspec.yaml +++ b/public/docs/_examples/pipes/dart/pubspec.yaml @@ -10,7 +10,7 @@ dependencies: dart_to_js_script_rewriter: ^1.0.1 transformers: - angular2: - platform_directives: 'package:angular2/src/common/directives.dart#CORE_DIRECTIVES' + platform_directives: 'package:angular2/common.dart#COMMON_DIRECTIVES' platform_pipes: 'package:angular2/common.dart#COMMON_PIPES' entry_points: web/main.dart - dart_to_js_script_rewriter diff --git a/public/docs/_examples/pipes/dart/web/index.html b/public/docs/_examples/pipes/dart/web/index.html index 483b9537ba..01bdf05322 100644 --- a/public/docs/_examples/pipes/dart/web/index.html +++ b/public/docs/_examples/pipes/dart/web/index.html @@ -8,9 +8,6 @@ -

Hero Birthday v.1

- hero-birthday loading... - my-app loading ... diff --git a/public/docs/_examples/pipes/e2e-spec.js b/public/docs/_examples/pipes/e2e-spec.js index 4f07ce7137..ae8327dd0d 100644 --- a/public/docs/_examples/pipes/e2e-spec.js +++ b/public/docs/_examples/pipes/e2e-spec.js @@ -9,10 +9,6 @@ describe('Pipes', function () { expect(element(by.css('hero-birthday p')).getText()).toEqual("The hero's birthday is Apr 15, 1988"); }); - it('should show an async hero message', function () { - expect(element.all(by.tagName('hero-message')).get(0).getText()).toContain('hero'); - }); - it('should show 4 heroes', function () { expect(element.all(by.css('hero-list div')).count()).toEqual(4); }); @@ -114,4 +110,8 @@ describe('Pipes', function () { }) }); + it('should show an async hero message', function () { + expect(element.all(by.tagName('hero-message')).get(0).getText()).toContain('hero'); + }); + }); diff --git a/public/docs/_examples/pipes/ts/app/app.component.html b/public/docs/_examples/pipes/ts/app/app.component.html index 83856e4e91..a27d587fcd 100644 --- a/public/docs/_examples/pipes/ts/app/app.component.html +++ b/public/docs/_examples/pipes/ts/app/app.component.html @@ -1,8 +1,8 @@

Pipes

-Happy Birthday v.1
+Happy Birthday v1
Birthday DatePipe
-Happy Birthday v.2
+Happy Birthday v2
Birthday Pipe Chaining
Power Booster custom pipe
Power Boost Calculator custom pipe with params
@@ -14,7 +14,7 @@
-

Hero Birthday v.1

+

Hero Birthday v1


@@ -30,7 +30,7 @@
-

Hero Birthday v.2

+

Hero Birthday v2


diff --git a/public/docs/_examples/pipes/ts/app/app.component.ts b/public/docs/_examples/pipes/ts/app/app.component.ts index 6a823ebd6f..c79c1305df 100644 --- a/public/docs/_examples/pipes/ts/app/app.component.ts +++ b/public/docs/_examples/pipes/ts/app/app.component.ts @@ -1,15 +1,15 @@ // #docregion -import {Component} from '@angular/core'; -import {HTTP_PROVIDERS} from '@angular/http'; +import { Component } from '@angular/core'; +import { HTTP_PROVIDERS } from '@angular/http'; -import {FlyingHeroesComponent, - FlyingHeroesImpureComponent} from './flying-heroes.component'; -import {HeroAsyncMessageComponent} from './hero-async-message.component'; -import {HeroBirthday} from './hero-birthday1.component'; -import {HeroBirthday2} from './hero-birthday2.component'; -import {HeroListComponent} from './hero-list.component'; -import {PowerBooster} from './power-booster.component'; -import {PowerBoostCalculator} from './power-boost-calculator.component'; +import { FlyingHeroesComponent, + FlyingHeroesImpureComponent } from './flying-heroes.component'; +import { HeroAsyncMessageComponent } from './hero-async-message.component'; +import { HeroBirthday } from './hero-birthday1.component'; +import { HeroBirthday2 } from './hero-birthday2.component'; +import { HeroListComponent } from './hero-list.component'; +import { PowerBooster } from './power-booster.component'; +import { PowerBoostCalculator } from './power-boost-calculator.component'; @Component({ selector: 'my-app', diff --git a/public/docs/_examples/pipes/ts/app/exponential-strength.pipe.ts b/public/docs/_examples/pipes/ts/app/exponential-strength.pipe.ts index 62ea8b1f24..0a703d7016 100644 --- a/public/docs/_examples/pipes/ts/app/exponential-strength.pipe.ts +++ b/public/docs/_examples/pipes/ts/app/exponential-strength.pipe.ts @@ -1,5 +1,5 @@ // #docregion -import {Pipe, PipeTransform} from '@angular/core'; +import { Pipe, PipeTransform } from '@angular/core'; /* * Raise the value exponentially * Takes an exponent argument that defaults to 1. diff --git a/public/docs/_examples/pipes/ts/app/fetch-json.pipe.ts b/public/docs/_examples/pipes/ts/app/fetch-json.pipe.ts index c491baaf9e..72fd58e178 100644 --- a/public/docs/_examples/pipes/ts/app/fetch-json.pipe.ts +++ b/public/docs/_examples/pipes/ts/app/fetch-json.pipe.ts @@ -1,6 +1,6 @@ // #docregion -import {Pipe, PipeTransform} from '@angular/core'; -import {Http} from '@angular/http'; +import { Pipe, PipeTransform } from '@angular/core'; +import { Http } from '@angular/http'; // #docregion pipe-metadata @Pipe({ @@ -9,7 +9,7 @@ import {Http} from '@angular/http'; }) // #enddocregion pipe-metadata export class FetchJsonPipe implements PipeTransform{ - private fetched:any = null; + private fetchedJson: any = null; private prevUrl = ''; constructor(private _http: Http) { } @@ -17,12 +17,12 @@ export class FetchJsonPipe implements PipeTransform{ transform(url: string): any { if (url !== this.prevUrl) { this.prevUrl = url; - this.fetched = null; + this.fetchedJson = null; this._http.get(url) .map( result => result.json() ) - .subscribe( result => this.fetched = result ); + .subscribe( result => this.fetchedJson = result ); } - return this.fetched; + return this.fetchedJson; } } diff --git a/public/docs/_examples/pipes/ts/app/flying-heroes.component.html b/public/docs/_examples/pipes/ts/app/flying-heroes.component.html index c004987503..93e635b662 100644 --- a/public/docs/_examples/pipes/ts/app/flying-heroes.component.html +++ b/public/docs/_examples/pipes/ts/app/flying-heroes.component.html @@ -35,5 +35,4 @@ New hero:
-
diff --git a/public/docs/_examples/pipes/ts/app/flying-heroes.component.ts b/public/docs/_examples/pipes/ts/app/flying-heroes.component.ts index 05a7112149..94323297ba 100644 --- a/public/docs/_examples/pipes/ts/app/flying-heroes.component.ts +++ b/public/docs/_examples/pipes/ts/app/flying-heroes.component.ts @@ -1,9 +1,10 @@ // #docplaster // #docregion -import {Component} from '@angular/core'; -import {FlyingHeroesPipe, - FlyingHeroesImpurePipe} from './flying-heroes.pipe'; -import {HEROES} from './heroes'; +import { Component } from '@angular/core'; + +import { FlyingHeroesPipe, + FlyingHeroesImpurePipe } from './flying-heroes.pipe'; +import { HEROES } from './heroes'; @Component({ selector: 'flying-heroes', diff --git a/public/docs/_examples/pipes/ts/app/flying-heroes.pipe.ts b/public/docs/_examples/pipes/ts/app/flying-heroes.pipe.ts index 0db0096d4e..3dee7d6757 100644 --- a/public/docs/_examples/pipes/ts/app/flying-heroes.pipe.ts +++ b/public/docs/_examples/pipes/ts/app/flying-heroes.pipe.ts @@ -1,7 +1,8 @@ // #docregion // #docregion pure -import {Flyer} from './heroes'; -import {Pipe, PipeTransform} from '@angular/core'; +import { Pipe, PipeTransform } from '@angular/core'; + +import { Flyer } from './heroes'; @Pipe({ name: 'flyingHeroes' }) export class FlyingHeroesPipe implements PipeTransform { diff --git a/public/docs/_examples/pipes/ts/app/hero-async-message.component.ts b/public/docs/_examples/pipes/ts/app/hero-async-message.component.ts index bc77e39f70..cced9f3e57 100644 --- a/public/docs/_examples/pipes/ts/app/hero-async-message.component.ts +++ b/public/docs/_examples/pipes/ts/app/hero-async-message.component.ts @@ -1,17 +1,12 @@ // #docregion -import {Component} from '@angular/core'; -import {Observable} from 'rxjs/Rx'; - -// Initial view: "Message: " -// After 500ms: Message: You are my Hero!" +import { Component } from '@angular/core'; +import { Observable } from 'rxjs/Rx'; @Component({ selector: 'hero-message', template: `

Async Hero Message and AsyncPipe

-

Message: {{ message$ | async }}

- `, }) export class HeroAsyncMessageComponent { diff --git a/public/docs/_examples/pipes/ts/app/hero-birthday1.component.ts b/public/docs/_examples/pipes/ts/app/hero-birthday1.component.ts index 368d96218e..52a462757b 100644 --- a/public/docs/_examples/pipes/ts/app/hero-birthday1.component.ts +++ b/public/docs/_examples/pipes/ts/app/hero-birthday1.component.ts @@ -1,6 +1,5 @@ -// Version #1 // #docregion -import {Component} from '@angular/core' +import { Component } from '@angular/core' @Component({ selector: 'hero-birthday', @@ -11,4 +10,3 @@ import {Component} from '@angular/core' export class HeroBirthday { birthday = new Date(1988,3,15); // April 15, 1988 } -// #enddocregion \ No newline at end of file diff --git a/public/docs/_examples/pipes/ts/app/hero-birthday2.component.ts b/public/docs/_examples/pipes/ts/app/hero-birthday2.component.ts index a0c9f38f71..683f082e27 100644 --- a/public/docs/_examples/pipes/ts/app/hero-birthday2.component.ts +++ b/public/docs/_examples/pipes/ts/app/hero-birthday2.component.ts @@ -1,15 +1,14 @@ -// Version #2 // #docregion -import {Component} from '@angular/core' +import { Component } from '@angular/core' @Component({ selector: 'hero-birthday2', -// #docregion template + // #docregion template template: `

The hero's birthday is {{ birthday | date:format }}

` -// #enddocregion template + // #enddocregion template }) // #docregion class export class HeroBirthday2 { @@ -19,4 +18,3 @@ export class HeroBirthday2 { get format() { return this.toggle ? 'shortDate' : 'fullDate'} toggleFormat() { this.toggle = !this.toggle; } } -// #enddocregion class diff --git a/public/docs/_examples/pipes/ts/app/hero-list.component.ts b/public/docs/_examples/pipes/ts/app/hero-list.component.ts index 788ebe87b0..0b9d8df37e 100644 --- a/public/docs/_examples/pipes/ts/app/hero-list.component.ts +++ b/public/docs/_examples/pipes/ts/app/hero-list.component.ts @@ -1,6 +1,7 @@ // #docregion -import {Component} from '@angular/core'; -import {FetchJsonPipe} from './fetch-json.pipe'; +import { Component } from '@angular/core'; + +import { FetchJsonPipe } from './fetch-json.pipe'; @Component({ selector: 'hero-list', diff --git a/public/docs/_examples/pipes/ts/app/main.ts b/public/docs/_examples/pipes/ts/app/main.ts index 0e080e0da5..dd9994d2b6 100644 --- a/public/docs/_examples/pipes/ts/app/main.ts +++ b/public/docs/_examples/pipes/ts/app/main.ts @@ -1,6 +1,6 @@ -import {bootstrap} from '@angular/platform-browser-dynamic'; +import { bootstrap } from '@angular/platform-browser-dynamic'; import 'rxjs/Rx'; -import {AppComponent} from './app.component'; +import { AppComponent } from './app.component'; bootstrap(AppComponent); diff --git a/public/docs/_examples/pipes/ts/app/power-boost-calculator.component.ts b/public/docs/_examples/pipes/ts/app/power-boost-calculator.component.ts index 9421feac64..549056afb1 100644 --- a/public/docs/_examples/pipes/ts/app/power-boost-calculator.component.ts +++ b/public/docs/_examples/pipes/ts/app/power-boost-calculator.component.ts @@ -1,6 +1,7 @@ // #docregion -import {Component} from '@angular/core'; -import {ExponentialStrengthPipe} from './exponential-strength.pipe'; +import { Component } from '@angular/core'; + +import { ExponentialStrengthPipe } from './exponential-strength.pipe'; @Component({ selector: 'power-boost-calculator', diff --git a/public/docs/_examples/pipes/ts/app/power-booster.component.ts b/public/docs/_examples/pipes/ts/app/power-booster.component.ts index 59fccfdf27..78c6f9c127 100644 --- a/public/docs/_examples/pipes/ts/app/power-booster.component.ts +++ b/public/docs/_examples/pipes/ts/app/power-booster.component.ts @@ -1,14 +1,13 @@ // #docregion -import {Component} from '@angular/core'; -import {ExponentialStrengthPipe} from './exponential-strength.pipe'; +import { Component } from '@angular/core'; + +import { ExponentialStrengthPipe } from './exponential-strength.pipe'; @Component({ selector: 'power-booster', template: `

Power Booster

-

- Super power boost: {{2 | exponentialStrength: 10}} -

+

Super power boost: {{2 | exponentialStrength: 10}}

`, pipes: [ExponentialStrengthPipe] }) diff --git a/public/docs/_examples/pipes/ts/index.html b/public/docs/_examples/pipes/ts/index.html index 458123fe19..445a3d9c1f 100644 --- a/public/docs/_examples/pipes/ts/index.html +++ b/public/docs/_examples/pipes/ts/index.html @@ -15,7 +15,7 @@ diff --git a/public/docs/_examples/quickstart/dart/example-config.json b/public/docs/_examples/quickstart/dart/example-config.json new file mode 100644 index 0000000000..e69de29bb2 diff --git a/public/docs/_examples/quickstart/dart/lib/app_component.dart b/public/docs/_examples/quickstart/dart/lib/app_component.dart new file mode 100644 index 0000000000..a54b6f7a1f --- /dev/null +++ b/public/docs/_examples/quickstart/dart/lib/app_component.dart @@ -0,0 +1,12 @@ +// #docregion +// #docregion import +import 'package:angular2/core.dart'; +// #enddocregion import + +// #docregion metadata +@Component( + selector: 'my-app', + template: '

My First Angular 2 App

') +// #enddocregion metadata +// #docregion class +class AppComponent {} diff --git a/public/docs/_examples/quickstart/dart/web/main.dart b/public/docs/_examples/quickstart/dart/web/main.dart index 3d1f7a3015..19b47a1237 100644 --- a/public/docs/_examples/quickstart/dart/web/main.dart +++ b/public/docs/_examples/quickstart/dart/web/main.dart @@ -1,10 +1,8 @@ // #docregion -import 'package:angular2/core.dart'; import 'package:angular2/platform/browser.dart'; -@Component(selector: 'my-app', template: '

My First Angular 2 App

') -class AppComponent {} +import 'package:angular2_getting_started/app_component.dart'; -main() { +void main() { bootstrap(AppComponent); } diff --git a/public/docs/_examples/quickstart/dart/web/styles_1.css b/public/docs/_examples/quickstart/dart/web/styles_1.css new file mode 100644 index 0000000000..27e60d67c0 --- /dev/null +++ b/public/docs/_examples/quickstart/dart/web/styles_1.css @@ -0,0 +1,14 @@ +/* #docregion */ +h1 { + color: #369; + font-family: Arial, Helvetica, sans-serif; + font-size: 250%; +} +body { + margin: 2em; +} + +/* +* See https://github.com/angular/angular.io/blob/master/public/docs/_examples/styles.css +* for the full set of master styles used by the documentation samples +*/ diff --git a/public/docs/_examples/quickstart/js/package.1.json b/public/docs/_examples/quickstart/js/package.1.json index 6ca4585d27..e5e96f785e 100644 --- a/public/docs/_examples/quickstart/js/package.1.json +++ b/public/docs/_examples/quickstart/js/package.1.json @@ -7,14 +7,22 @@ }, "license": "ISC", "dependencies": { - "@angular/common": "2.0.0-rc.0", - "@angular/compiler": "2.0.0-rc.0", - "@angular/core": "2.0.0-rc.0", - "@angular/platform-browser": "2.0.0-rc.0", - "@angular/platform-browser-dynamic": "2.0.0-rc.0", + "@angular/common": "2.0.0-rc.1", + "@angular/compiler": "2.0.0-rc.1", + "@angular/core": "2.0.0-rc.1", + "@angular/http": "2.0.0-rc.1", + "@angular/platform-browser": "2.0.0-rc.1", + "@angular/platform-browser-dynamic": "2.0.0-rc.1", + "@angular/router": "2.0.0-rc.1", + "@angular/router-deprecated": "2.0.0-rc.1", + "@angular/upgrade": "2.0.0-rc.1", + "reflect-metadata": "0.1.3", "rxjs": "5.0.0-beta.6", - "zone.js": "0.6.12" + "zone.js": "0.6.12", + + "angular2-in-memory-web-api": "0.0.7", + "bootstrap": "^3.3.6" }, "devDependencies": { "concurrently": "^2.0.0", diff --git a/public/docs/_examples/quickstart/ts/app/app.component.ts b/public/docs/_examples/quickstart/ts/app/app.component.ts index c06649ce5b..ea76b32116 100644 --- a/public/docs/_examples/quickstart/ts/app/app.component.ts +++ b/public/docs/_examples/quickstart/ts/app/app.component.ts @@ -1,6 +1,6 @@ // #docregion // #docregion import -import {Component} from '@angular/core'; +import { Component } from '@angular/core'; // #enddocregion import // #docregion metadata @@ -9,6 +9,6 @@ import {Component} from '@angular/core'; template: '

My First Angular 2 App

' }) // #enddocregion metadata -// #docregion export +// #docregion class export class AppComponent { } -// #enddocregion export +// #enddocregion class diff --git a/public/docs/_examples/quickstart/ts/app/main.ts b/public/docs/_examples/quickstart/ts/app/main.ts index b4af948a35..2aede345e9 100644 --- a/public/docs/_examples/quickstart/ts/app/main.ts +++ b/public/docs/_examples/quickstart/ts/app/main.ts @@ -1,7 +1,8 @@ // #docregion -import {bootstrap} from '@angular/platform-browser-dynamic'; -// #docregion app-component -import {AppComponent} from './app.component'; -// #enddocregion app-component +import { bootstrap } from '@angular/platform-browser-dynamic'; + +// #docregion import +import { AppComponent } from './app.component'; +// #enddocregion import bootstrap(AppComponent); diff --git a/public/docs/_examples/quickstart/ts/index.html b/public/docs/_examples/quickstart/ts/index.html index 1032381949..b1be60a776 100644 --- a/public/docs/_examples/quickstart/ts/index.html +++ b/public/docs/_examples/quickstart/ts/index.html @@ -23,7 +23,7 @@ diff --git a/public/docs/_examples/quickstart/ts/package.1.json b/public/docs/_examples/quickstart/ts/package.1.json index 16ed9c6461..8be1e8b8c6 100644 --- a/public/docs/_examples/quickstart/ts/package.1.json +++ b/public/docs/_examples/quickstart/ts/package.1.json @@ -11,14 +11,15 @@ }, "license": "ISC", "dependencies": { - "@angular/common": "2.0.0-rc.0", - "@angular/compiler": "2.0.0-rc.0", - "@angular/core": "2.0.0-rc.0", - "@angular/http": "2.0.0-rc.0", - "@angular/platform-browser": "2.0.0-rc.0", - "@angular/platform-browser-dynamic": "2.0.0-rc.0", - "@angular/router-deprecated": "2.0.0-rc.0", - "@angular/upgrade": "2.0.0-rc.0", + "@angular/common": "2.0.0-rc.1", + "@angular/compiler": "2.0.0-rc.1", + "@angular/core": "2.0.0-rc.1", + "@angular/http": "2.0.0-rc.1", + "@angular/platform-browser": "2.0.0-rc.1", + "@angular/platform-browser-dynamic": "2.0.0-rc.1", + "@angular/router": "2.0.0-rc.1", + "@angular/router-deprecated": "2.0.0-rc.1", + "@angular/upgrade": "2.0.0-rc.1", "systemjs": "0.19.27", "es6-shim": "^0.35.0", @@ -26,7 +27,7 @@ "rxjs": "5.0.0-beta.6", "zone.js": "^0.6.12", - "angular2-in-memory-web-api": "0.0.5", + "angular2-in-memory-web-api": "0.0.7", "bootstrap": "^3.3.6" }, "devDependencies": { diff --git a/public/docs/_examples/quickstart/ts/styles.1.css b/public/docs/_examples/quickstart/ts/styles.1.css index c1bd2cfec6..fbc30e2c9e 100644 --- a/public/docs/_examples/quickstart/ts/styles.1.css +++ b/public/docs/_examples/quickstart/ts/styles.1.css @@ -1,25 +1,14 @@ /* #docregion */ -/* Master Styles */ h1 { - color: #369; - font-family: Arial, Helvetica, sans-serif; + color: #369; + font-family: Arial, Helvetica, sans-serif; font-size: 250%; } -h2, h3 { - color: #444; - font-family: Arial, Helvetica, sans-serif; - font-weight: lighter; -} -body { - margin: 2em; -} -body, input[text], button { - color: #888; - font-family: Cambria, Georgia; +body { + margin: 2em; } -/* - * See https://github.com/angular/angular.io/blob/master/public/docs/_examples/styles.css - * for the full set of master styles used by the documentation samples - */ - \ No newline at end of file + /* + * See https://github.com/angular/angular.io/blob/master/public/docs/_examples/styles.css + * for the full set of master styles used by the documentation samples + */ diff --git a/public/docs/_examples/quickstart/ts/systemjs.config.1.js b/public/docs/_examples/quickstart/ts/systemjs.config.1.js index e7230083fb..8cdeb99cb5 100644 --- a/public/docs/_examples/quickstart/ts/systemjs.config.1.js +++ b/public/docs/_examples/quickstart/ts/systemjs.config.1.js @@ -1,18 +1,16 @@ -// #docregion /** * System configuration for Angular 2 samples * Adjust as necessary for your application needs. - * Override at the last minute with global.filterSystemConfig (as plunkers do) */ -// #docregion (function(global) { // map tells the System loader where to look for things var map = { 'app': 'app', // 'dist', - 'rxjs': 'node_modules/rxjs', + + '@angular': 'node_modules/@angular', 'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api', - '@angular': 'node_modules/@angular' + 'rxjs': 'node_modules/rxjs' }; // packages tells the System loader how to load when no filename and/or no extension @@ -22,21 +20,21 @@ 'angular2-in-memory-web-api': { defaultExtension: 'js' }, }; - var packageNames = [ - '@angular/common', - '@angular/compiler', - '@angular/core', - '@angular/http', - '@angular/platform-browser', - '@angular/platform-browser-dynamic', - '@angular/router', - '@angular/testing', - '@angular/upgrade', + var ngPackageNames = [ + 'common', + 'compiler', + 'core', + 'http', + 'platform-browser', + 'platform-browser-dynamic', + 'router', + 'router-deprecated', + 'upgrade', ]; - // add package entries for angular packages in the form '@angular/common': { main: 'index.js', defaultExtension: 'js' } - packageNames.forEach(function(pkgName) { - packages[pkgName] = { main: 'index.js', defaultExtension: 'js' }; + // Add package entries for angular packages + ngPackageNames.forEach(function(pkgName) { + packages['@angular/'+pkgName] = { main: pkgName + '.umd.js', defaultExtension: 'js' }; }); var config = { @@ -44,9 +42,6 @@ packages: packages } - // filterSystemConfig - index.html's chance to modify config before we register it. - if (global.filterSystemConfig) { global.filterSystemConfig(config); } - System.config(config); })(this); diff --git a/public/docs/_examples/quickstart/ts/typings.1.json b/public/docs/_examples/quickstart/ts/typings.1.json index 9d5c20bc92..b5324f4199 100644 --- a/public/docs/_examples/quickstart/ts/typings.1.json +++ b/public/docs/_examples/quickstart/ts/typings.1.json @@ -1,6 +1,7 @@ { "ambientDependencies": { "es6-shim": "registry:dt/es6-shim#0.31.2+20160317120654", - "jasmine": "registry:dt/jasmine#2.2.0+20160412134438" + "jasmine": "registry:dt/jasmine#2.2.0+20160412134438", + "node": "registry:dt/node#4.0.0+20160509154515" } } diff --git a/public/docs/_examples/router-deprecated/e2e-spec.js b/public/docs/_examples/router-deprecated/e2e-spec.js new file mode 100644 index 0000000000..4e3018b5c2 --- /dev/null +++ b/public/docs/_examples/router-deprecated/e2e-spec.js @@ -0,0 +1,123 @@ +describe('Router', function () { + + beforeAll(function () { + browser.get(''); + }); + + function getPageStruct() { + hrefEles = element.all(by.css('my-app a')); + + return { + hrefs: hrefEles, + routerParent: element(by.css('my-app > undefined')), + routerTitle: element(by.css('my-app > undefined > h2')), + + crisisHref: hrefEles.get(0), + crisisList: element.all(by.css('my-app > undefined > undefined li')), + crisisDetail: element(by.css('my-app > undefined > undefined > div')), + crisisDetailTitle: element(by.css('my-app > undefined > undefined > div > h3')), + + heroesHref: hrefEles.get(1), + heroesList: element.all(by.css('my-app > undefined li')), + heroDetail: element(by.css('my-app > undefined > div')), + heroDetailTitle: element(by.css('my-app > undefined > div > h3')), + + } + } + + it('should be able to see the start screen', function () { + var page = getPageStruct(); + expect(page.hrefs.count()).toEqual(2, 'should be two dashboard choices'); + expect(page.crisisHref.getText()).toEqual("Crisis Center"); + expect(page.heroesHref.getText()).toEqual("Heroes"); + }); + + it('should be able to see crises center items', function () { + var page = getPageStruct(); + expect(page.crisisList.count()).toBe(4, "should be 4 crisis center entries at start"); + }); + + it('should be able to see hero items', function () { + var page = getPageStruct(); + page.heroesHref.click().then(function() { + expect(page.routerTitle.getText()).toContain('HEROES'); + expect(page.heroesList.count()).toBe(6, "should be 6 heroes"); + }); + }); + + it('should be able to toggle the views', function () { + var page = getPageStruct(); + page.crisisHref.click().then(function() { + expect(page.crisisList.count()).toBe(4, "should be 4 crisis center entries"); + return page.heroesHref.click(); + }).then(function() { + expect(page.heroesList.count()).toBe(6, "should be 6 heroes"); + }); + }); + + it('should be able to edit and save details from the crisis center view', function () { + crisisCenterEdit(2, true); + }); + + it('should be able to edit and cancel details from the crisis center view', function () { + crisisCenterEdit(3, false); + }); + + it('should be able to edit and save details from the heroes view', function () { + var page = getPageStruct(); + var heroEle, heroText; + page.heroesHref.click().then(function() { + heroEle = page.heroesList.get(4); + return heroEle.getText(); + }).then(function(text) { + expect(text.length).toBeGreaterThan(0, 'should have some text'); + // remove leading id from text + heroText = text.substr(text.indexOf(' ')).trim(); + return heroEle.click(); + }).then(function() { + expect(page.heroesList.count()).toBe(0, "should no longer see crisis center entries"); + expect(page.heroDetail.isPresent()).toBe(true, 'should be able to see crisis detail'); + expect(page.heroDetailTitle.getText()).toContain(heroText); + var inputEle = page.heroDetail.element(by.css('input')); + return sendKeys(inputEle, '-foo'); + }).then(function() { + expect(page.heroDetailTitle.getText()).toContain(heroText + '-foo'); + var buttonEle = page.heroDetail.element(by.css('button')); + return buttonEle.click(); + }).then(function() { + expect(heroEle.getText()).toContain(heroText + '-foo'); + }) + }); + + function crisisCenterEdit(index, shouldSave) { + var page = getPageStruct(); + var crisisEle, crisisText; + page.crisisHref.click() + .then(function () { + crisisEle = page.crisisList.get(index); + return crisisEle.getText(); + }).then(function (text) { + expect(text.length).toBeGreaterThan(0, 'should have some text'); + // remove leading id from text + crisisText = text.substr(text.indexOf(' ')).trim(); + return crisisEle.click(); + }).then(function () { + expect(page.crisisList.count()).toBe(0, "should no longer see crisis center entries"); + expect(page.crisisDetail.isPresent()).toBe(true, 'should be able to see crisis detail'); + expect(page.crisisDetailTitle.getText()).toContain(crisisText); + var inputEle = page.crisisDetail.element(by.css('input')); + return sendKeys(inputEle, '-foo'); + }).then(function () { + expect(page.crisisDetailTitle.getText()).toContain(crisisText + '-foo'); + var buttonEle = page.crisisDetail.element(by.cssContainingText('button', shouldSave ? 'Save' : 'Cancel')); + return buttonEle.click(); + }).then(function () { + if (shouldSave) { + expect(crisisEle.getText()).toContain(crisisText + '-foo'); + } else { + expect(crisisEle.getText()).not.toContain(crisisText + '-foo'); + } + }); + } + +}); diff --git a/public/docs/_examples/router-deprecated/ts/app/app.component.1.ts b/public/docs/_examples/router-deprecated/ts/app/app.component.1.ts new file mode 100644 index 0000000000..0e20623fd3 --- /dev/null +++ b/public/docs/_examples/router-deprecated/ts/app/app.component.1.ts @@ -0,0 +1,43 @@ +/* First version */ +// #docplaster + +// #docregion +import { Component } from '@angular/core'; +// #docregion import-router +import { RouteConfig, ROUTER_DIRECTIVES } from '@angular/router-deprecated'; +// #enddocregion import-router + +import { CrisisListComponent } from './crisis-list.component'; +import { HeroListComponent } from './hero-list.component'; + +@Component({ + selector: 'my-app', +// #docregion template + template: ` +

Component Router (Deprecated)

+ + + `, +// #enddocregion template + directives: [ROUTER_DIRECTIVES] +}) +// #enddocregion +/* +// #docregion route-config +@Component({ ... }) +// #enddocregion route-config +*/ +// #docregion +// #docregion route-config +@RouteConfig([ +// #docregion route-defs + {path: '/crisis-center', name: 'CrisisCenter', component: CrisisListComponent}, + {path: '/heroes', name: 'Heroes', component: HeroListComponent} +// #enddocregion route-defs +]) +export class AppComponent { } +// #enddocregion route-config +// #enddocregion diff --git a/public/docs/_examples/router-deprecated/ts/app/app.component.2.ts b/public/docs/_examples/router-deprecated/ts/app/app.component.2.ts new file mode 100644 index 0000000000..e4685ff418 --- /dev/null +++ b/public/docs/_examples/router-deprecated/ts/app/app.component.2.ts @@ -0,0 +1,58 @@ +/* Second Heroes version */ +// #docplaster + +// #docregion +import { Component } from '@angular/core'; +import { RouteConfig, ROUTER_DIRECTIVES } from '@angular/router-deprecated'; + +import { CrisisListComponent } from './crisis-list.component'; +// #enddocregion +/* +// Apparent Milestone 2 imports +// #docregion +// #docregion hero-import +import { HeroListComponent } from './heroes/hero-list.component'; +import { HeroDetailComponent } from './heroes/hero-detail.component'; +import { HeroService } from './heroes/hero.service'; +// #enddocregion hero-import +// #enddocregion +*/ +// Actual Milestone 2 imports +import { HeroListComponent } from './heroes/hero-list.component.1'; +import { HeroDetailComponent } from './heroes/hero-detail.component.1'; +import { HeroService } from './heroes/hero.service'; +// #docregion + +@Component({ + selector: 'my-app', + template: ` +

Component Router (Deprecated)

+ + + `, + providers: [HeroService], + directives: [ROUTER_DIRECTIVES] +}) +// #enddocregion +/* +// #docregion route-config +@Component({ ... }) +// #enddocregion route-config +*/ +// #docregion +// #docregion route-config +@RouteConfig([ +// #docregion route-defs + {path: '/crisis-center', name: 'CrisisCenter', component: CrisisListComponent}, + {path: '/heroes', name: 'Heroes', component: HeroListComponent}, + // #docregion hero-detail-route + {path: '/hero/:id', name: 'HeroDetail', component: HeroDetailComponent} + // #enddocregion hero-detail-route +// #enddocregion route-defs +]) +export class AppComponent { } +// #enddocregion route-config +// #enddocregion diff --git a/public/docs/_examples/router-deprecated/ts/app/app.component.3.ts b/public/docs/_examples/router-deprecated/ts/app/app.component.3.ts new file mode 100644 index 0000000000..68635e8aad --- /dev/null +++ b/public/docs/_examples/router-deprecated/ts/app/app.component.3.ts @@ -0,0 +1,52 @@ +// #docplaster +import { Component } from '@angular/core'; +import { RouteConfig, ROUTER_DIRECTIVES } from '@angular/router-deprecated'; + +import { CrisisCenterComponent } from './crisis-center/crisis-center.component.1'; +import { DialogService } from './dialog.service'; +import { HeroService } from './heroes/hero.service'; + +@Component({ + selector: 'my-app', +// #enddocregion + /* Typical link + // #docregion h-anchor + Heroes + // #enddocregion h-anchor + */ + /* Incomplete Crisis Center link when CC lacks a default + // #docregion cc-anchor-fail + // The link now fails with a "non-terminal link" error + // #docregion cc-anchor-w-default + Crisis Center + // #enddocregion cc-anchor-w-default + // #enddocregion cc-anchor-fail + */ + /* Crisis Center link when CC lacks a default + // #docregion cc-anchor-no-default + Crisis Center + // #enddocregion cc-anchor-no-default + */ + /* Crisis Center Detail link + // #docregion Dragon-anchor + Dragon Crisis + // #enddocregion Dragon-anchor + */ +// #docregion template + template: ` +

Component Router (Deprecated)

+ + + `, +// #enddocregion template + providers: [DialogService, HeroService], + directives: [ROUTER_DIRECTIVES] +}) +@RouteConfig([ + {path: '/crisis-center/...', name: 'CrisisCenter', component: CrisisCenterComponent}, +]) +export class AppComponent { } diff --git a/public/docs/_examples/router-deprecated/ts/app/app.component.ts b/public/docs/_examples/router-deprecated/ts/app/app.component.ts new file mode 100644 index 0000000000..a6f784cda9 --- /dev/null +++ b/public/docs/_examples/router-deprecated/ts/app/app.component.ts @@ -0,0 +1,44 @@ +// #docplaster +// #docregion +import { Component } from '@angular/core'; +import { RouteConfig, ROUTER_DIRECTIVES } from '@angular/router-deprecated'; + +import { CrisisCenterComponent } from './crisis-center/crisis-center.component'; +import { HeroListComponent } from './heroes/hero-list.component'; +import { HeroDetailComponent } from './heroes/hero-detail.component'; + +import { DialogService } from './dialog.service'; +import { HeroService } from './heroes/hero.service'; + +@Component({ + selector: 'my-app', +// #docregion template + template: ` +

Component Router (Deprecated)

+ + + `, +// #enddocregion template + providers: [DialogService, HeroService], + directives: [ROUTER_DIRECTIVES] +}) +// #docregion route-config +@RouteConfig([ + + // #docregion route-config-cc + { // Crisis Center child route + path: '/crisis-center/...', + name: 'CrisisCenter', + component: CrisisCenterComponent, + useAsDefault: true + }, + // #enddocregion route-config-cc + + {path: '/heroes', name: 'Heroes', component: HeroListComponent}, + {path: '/hero/:id', name: 'HeroDetail', component: HeroDetailComponent}, +]) +// #enddocregion route-config +export class AppComponent { } diff --git a/public/docs/_examples/router/ts/app/crisis-center/add-crisis.component.ts b/public/docs/_examples/router-deprecated/ts/app/crisis-center/add-crisis.component.ts similarity index 54% rename from public/docs/_examples/router/ts/app/crisis-center/add-crisis.component.ts rename to public/docs/_examples/router-deprecated/ts/app/crisis-center/add-crisis.component.ts index ac7fe55f7c..5067e8aa3f 100644 --- a/public/docs/_examples/router/ts/app/crisis-center/add-crisis.component.ts +++ b/public/docs/_examples/router-deprecated/ts/app/crisis-center/add-crisis.component.ts @@ -1,7 +1,8 @@ -import {Component} from '@angular/core'; -import {Crisis, CrisisService} from './crisis.service'; -import {DialogService} from '../dialog.service'; -import {CanDeactivate, ComponentInstruction, Router} from '@angular/router-deprecated'; +import { Component } from '@angular/core'; +import { CanDeactivate, ComponentInstruction, Router } from '@angular/router-deprecated'; + +import { Crisis, CrisisService } from './crisis.service'; +import { DialogService } from '../dialog.service'; @Component({ template: ` @@ -19,23 +20,23 @@ export class AddCrisisComponent implements CanDeactivate { editName: string; constructor( - private _service: CrisisService, - private _router: Router, - private _dialog: DialogService) { } + private service: CrisisService, + private router: Router, + private dialog: DialogService) { } routerCanDeactivate(next: ComponentInstruction, prev: ComponentInstruction) { return !!this.editName.trim() || - this._dialog.confirm('Discard changes?'); + this.dialog.confirm('Discard changes?'); } cancel() { this.gotoCrises(); } save() { - this._service.addCrisis(this.editName); + this.service.addCrisis(this.editName); this.gotoCrises(); } gotoCrises() { - this._router.navigate(['CrisisCenter']); + this.router.navigate(['CrisisCenter']); } } \ No newline at end of file diff --git a/public/docs/_examples/router-deprecated/ts/app/crisis-center/crisis-center.component.1.ts b/public/docs/_examples/router-deprecated/ts/app/crisis-center/crisis-center.component.1.ts new file mode 100644 index 0000000000..496b8ba11e --- /dev/null +++ b/public/docs/_examples/router-deprecated/ts/app/crisis-center/crisis-center.component.1.ts @@ -0,0 +1,28 @@ +import { Component } from '@angular/core'; +import { RouteConfig, RouterOutlet } from '@angular/router-deprecated'; + +import { CrisisListComponent } from './crisis-list.component.1'; +import { CrisisDetailComponent } from './crisis-detail.component.1'; +import { CrisisService } from './crisis.service'; + +// #docregion minus-imports +@Component({ + template: ` +

CRISIS CENTER

+ + `, + directives: [RouterOutlet], +// #docregion providers + providers: [CrisisService] +// #enddocregion providers +}) +// #docregion route-config +@RouteConfig([ + // #docregion default-route + {path:'/', name: 'CrisisList', component: CrisisListComponent, useAsDefault: true}, + // #enddocregion default-route + {path:'/:id', name: 'CrisisDetail', component: CrisisDetailComponent} +]) +// #enddocregion route-config +export class CrisisCenterComponent { } +// #enddocregion minus-imports diff --git a/public/docs/_examples/router-deprecated/ts/app/crisis-center/crisis-center.component.ts b/public/docs/_examples/router-deprecated/ts/app/crisis-center/crisis-center.component.ts new file mode 100644 index 0000000000..27f9ff09ac --- /dev/null +++ b/public/docs/_examples/router-deprecated/ts/app/crisis-center/crisis-center.component.ts @@ -0,0 +1,22 @@ +// #docregion +import { Component } from '@angular/core'; +import { RouteConfig, RouterOutlet } from '@angular/router-deprecated'; + +import { CrisisListComponent } from './crisis-list.component'; +import { CrisisDetailComponent } from './crisis-detail.component'; +import { CrisisService } from './crisis.service'; + +@Component({ + template: ` +

CRISIS CENTER

+ + `, + directives: [RouterOutlet], + providers: [CrisisService] +}) +@RouteConfig([ + {path:'/', name: 'CrisisList', component: CrisisListComponent, useAsDefault: true}, + {path:'/:id', name: 'CrisisDetail', component: CrisisDetailComponent} +]) +export class CrisisCenterComponent { } +// #enddocregion diff --git a/public/docs/_examples/router-deprecated/ts/app/crisis-center/crisis-detail.component.1.ts b/public/docs/_examples/router-deprecated/ts/app/crisis-center/crisis-detail.component.1.ts new file mode 100644 index 0000000000..8fb93b371a --- /dev/null +++ b/public/docs/_examples/router-deprecated/ts/app/crisis-center/crisis-detail.component.1.ts @@ -0,0 +1,95 @@ +// #docplaster + +// #docregion +import { Component, OnInit } from '@angular/core'; +import { RouteParams, Router } from '@angular/router-deprecated'; +// #docregion routerCanDeactivate +import { CanDeactivate, ComponentInstruction } from '@angular/router-deprecated'; + +import { DialogService } from '../dialog.service'; + +// #enddocregion routerCanDeactivate +import { Crisis, CrisisService } from './crisis.service'; + +@Component({ + // #docregion template + template: ` +
+

"{{editName}}"

+
+ {{crisis.id}}
+
+ + +
+

+ + +

+
+ `, + // #enddocregion template + styles: ['input {width: 20em}'] +}) +// #docregion routerCanDeactivate, cancel-save +export class CrisisDetailComponent implements OnInit, CanDeactivate { + + crisis: Crisis; + editName: string; + +// #enddocregion routerCanDeactivate, cancel-save + constructor( + private service: CrisisService, + private router: Router, + private routeParams: RouteParams, + private dialog: DialogService + ) { } + + // #docregion ngOnInit + ngOnInit() { + let id = +this.routeParams.get('id'); + this.service.getCrisis(id).then(crisis => { + if (crisis) { + this.editName = crisis.name; + this.crisis = crisis; + } else { // id not found + this.gotoCrises(); + } + }); + } + // #enddocregion ngOnInit + + // #docregion routerCanDeactivate + routerCanDeactivate(next: ComponentInstruction, prev: ComponentInstruction) : any { + // Allow synchronous navigation (`true`) if no crisis or the crisis is unchanged. + if (!this.crisis || this.crisis.name === this.editName) { + return true; + } + // Otherwise ask the user with the dialog service and return its + // promise which resolves to true or false when the user decides + return this.dialog.confirm('Discard changes?'); + } + // #enddocregion routerCanDeactivate + + // #docregion cancel-save + cancel() { + this.editName = this.crisis.name; + this.gotoCrises(); + } + + save() { + this.crisis.name = this.editName; + this.gotoCrises(); + } + // #enddocregion cancel-save + + // #docregion gotoCrises + gotoCrises() { + // Like Crisis Center +

"{{editName}}"

+
+ {{crisis.id}}
+
+ + +
+

+ + +

+
+ `, + styles: ['input {width: 20em}'] +}) + +export class CrisisDetailComponent implements OnInit, CanDeactivate { + + crisis: Crisis; + editName: string; + + constructor( + private service: CrisisService, + private router: Router, + private routeParams: RouteParams, + private _dialog: DialogService + ) { } + + ngOnInit() { + let id = +this.routeParams.get('id'); + this.service.getCrisis(id).then(crisis => { + if (crisis) { + this.editName = crisis.name; + this.crisis = crisis; + } else { // id not found + this.gotoCrises(); + } + }); + } + + routerCanDeactivate(next: ComponentInstruction, prev: ComponentInstruction) : any { + // Allow synchronous navigation (`true`) if no crisis or the crisis is unchanged. + if (!this.crisis || this.crisis.name === this.editName) { + return true; + } + // Otherwise ask the user with the dialog service and return its + // promise which resolves to true or false when the user decides + return this._dialog.confirm('Discard changes?'); + } + + cancel() { + this.editName = this.crisis.name; + this.gotoCrises(); + } + + save() { + this.crisis.name = this.editName; + this.gotoCrises(); + } + + // #docregion gotoCrises + gotoCrises() { + let crisisId = this.crisis ? this.crisis.id : null; + // Pass along the hero id if available + // so that the CrisisListComponent can select that hero. + // Add a totally useless `foo` parameter for kicks. + // #docregion gotoCrises-navigate + this.router.navigate(['CrisisList', {id: crisisId, foo: 'foo'} ]); + // #enddocregion gotoCrises-navigate + } + // #enddocregion gotoCrises +} diff --git a/public/docs/_examples/router-deprecated/ts/app/crisis-center/crisis-list.component.1.ts b/public/docs/_examples/router-deprecated/ts/app/crisis-center/crisis-list.component.1.ts new file mode 100644 index 0000000000..45121da69e --- /dev/null +++ b/public/docs/_examples/router-deprecated/ts/app/crisis-center/crisis-list.component.1.ts @@ -0,0 +1,37 @@ +// #docplaster + +// #docregion +import { Component, OnInit } from '@angular/core'; +import { Router } from '@angular/router-deprecated'; + +import { Crisis, CrisisService } from './crisis.service'; + +@Component({ + // #docregion template + template: ` +
    +
  • + {{crisis.id}} {{crisis.name}} +
  • +
+ `, + // #enddocregion template +}) +export class CrisisListComponent implements OnInit { + crises: Crisis[]; + + constructor( + private service: CrisisService, + private router: Router) {} + + ngOnInit() { + this.service.getCrises().then(crises => this.crises = crises); + } + + // #docregion select + onSelect(crisis: Crisis) { + this.router.navigate(['CrisisDetail', { id: crisis.id }] ); + } + // #enddocregion select +} diff --git a/public/docs/_examples/router-deprecated/ts/app/crisis-center/crisis-list.component.ts b/public/docs/_examples/router-deprecated/ts/app/crisis-center/crisis-list.component.ts new file mode 100644 index 0000000000..a5770d256f --- /dev/null +++ b/public/docs/_examples/router-deprecated/ts/app/crisis-center/crisis-list.component.ts @@ -0,0 +1,41 @@ +// #docplaster + +// #docregion +import { Component, OnInit } from '@angular/core'; +import { RouteParams, Router } from '@angular/router-deprecated'; + +import { Crisis, CrisisService } from './crisis.service'; + +@Component({ + template: ` +
    +
  • + {{crisis.id}} {{crisis.name}} +
  • +
+ `, +}) +export class CrisisListComponent implements OnInit { + crises: Crisis[]; + + private selectedId: number; + + constructor( + private service: CrisisService, + private router: Router, + routeParams: RouteParams) { + this.selectedId = +routeParams.get('id'); + } + + isSelected(crisis: Crisis) { return crisis.id === this.selectedId; } + + ngOnInit() { + this.service.getCrises().then(crises => this.crises = crises); + } + + onSelect(crisis: Crisis) { + this.router.navigate( ['CrisisDetail', { id: crisis.id }] ); + } +} diff --git a/public/docs/_examples/router-deprecated/ts/app/crisis-center/crisis.service.ts b/public/docs/_examples/router-deprecated/ts/app/crisis-center/crisis.service.ts new file mode 100644 index 0000000000..949ccd4e00 --- /dev/null +++ b/public/docs/_examples/router-deprecated/ts/app/crisis-center/crisis.service.ts @@ -0,0 +1,41 @@ +// #docplaster + +// #docregion +import { Injectable } from '@angular/core'; + +export class Crisis { + constructor(public id: number, public name: string) { } +} + +@Injectable() +export class CrisisService { + getCrises() { return crisesPromise; } + + getCrisis(id: number | string) { + return crisesPromise + .then(crises => crises.filter(c => c.id === +id)[0]); + } + +// #enddocregion + + static nextCrisisId = 100; + + addCrisis(name:string) { + name = name.trim(); + if (name){ + let crisis = new Crisis(CrisisService.nextCrisisId++, name); + crisesPromise.then(crises => crises.push(crisis)); + } + } +// #docregion +} + +var crises = [ + new Crisis(1, 'Dragon Burning Cities'), + new Crisis(2, 'Sky Rains Great White Sharks'), + new Crisis(3, 'Giant Asteroid Heading For Earth'), + new Crisis(4, 'Procrastinators Meeting Delayed Again'), +]; + +var crisesPromise = Promise.resolve(crises); +// #enddocregion diff --git a/public/docs/_examples/router-deprecated/ts/app/crisis-list.component.ts b/public/docs/_examples/router-deprecated/ts/app/crisis-list.component.ts new file mode 100644 index 0000000000..6caa3653b5 --- /dev/null +++ b/public/docs/_examples/router-deprecated/ts/app/crisis-list.component.ts @@ -0,0 +1,10 @@ +// Initial empty version +// #docregion +import { Component } from '@angular/core'; + +@Component({ + template: ` +

CRISIS CENTER

+

Get your crisis here

` +}) +export class CrisisListComponent { } diff --git a/public/docs/_examples/router-deprecated/ts/app/dialog.service.ts b/public/docs/_examples/router-deprecated/ts/app/dialog.service.ts new file mode 100644 index 0000000000..5d6160c59f --- /dev/null +++ b/public/docs/_examples/router-deprecated/ts/app/dialog.service.ts @@ -0,0 +1,18 @@ +// #docregion +import { Injectable } from '@angular/core'; +/** + * Async modal dialog service + * DialogService makes this app easier to test by faking this service. + * TODO: better modal implemenation that doesn't use window.confirm + */ +@Injectable() +export class DialogService { + /** + * Ask user to confirm an action. `message` explains the action and choices. + * Returns promise resolving to `true`=confirm or `false`=cancel + */ + confirm(message?:string) { + return new Promise((resolve, reject) => + resolve(window.confirm(message || 'Is it OK?'))); + }; +} diff --git a/public/docs/_examples/router-deprecated/ts/app/hero-list.component.ts b/public/docs/_examples/router-deprecated/ts/app/hero-list.component.ts new file mode 100644 index 0000000000..5dbbe17d8e --- /dev/null +++ b/public/docs/_examples/router-deprecated/ts/app/hero-list.component.ts @@ -0,0 +1,10 @@ +/// Initial empty version +// #docregion +import { Component } from '@angular/core'; + +@Component({ + template: ` +

HEROES

+

Get your heroes here

` +}) +export class HeroListComponent { } diff --git a/public/docs/_examples/router-deprecated/ts/app/heroes/hero-detail.component.1.ts b/public/docs/_examples/router-deprecated/ts/app/heroes/hero-detail.component.1.ts new file mode 100644 index 0000000000..bb8509af21 --- /dev/null +++ b/public/docs/_examples/router-deprecated/ts/app/heroes/hero-detail.component.1.ts @@ -0,0 +1,47 @@ +// #docregion +import { Component, OnInit } from '@angular/core'; +import { RouteParams, Router } from '@angular/router-deprecated'; + +import { Hero, HeroService } from './hero.service'; + +@Component({ + template: ` +

HEROES

+
+

"{{hero.name}}"

+
+ {{hero.id}}
+
+ + +
+

+ +

+
+ `, +}) +export class HeroDetailComponent implements OnInit { + hero: Hero; + + // #docregion ctor + constructor( + private router:Router, + private routeParams:RouteParams, + private service:HeroService){} + // #enddocregion ctor + + // #docregion ngOnInit + ngOnInit() { + let id = this.routeParams.get('id'); + this.service.getHero(id).then(hero => this.hero = hero); + } + // #enddocregion ngOnInit + + // #docregion gotoHeroes + gotoHeroes() { + // Like Heroes + this.router.navigate(['Heroes']); + } + // #enddocregion gotoHeroes +} diff --git a/public/docs/_examples/router-deprecated/ts/app/heroes/hero-detail.component.ts b/public/docs/_examples/router-deprecated/ts/app/heroes/hero-detail.component.ts new file mode 100644 index 0000000000..abf4d4dd3b --- /dev/null +++ b/public/docs/_examples/router-deprecated/ts/app/heroes/hero-detail.component.ts @@ -0,0 +1,52 @@ +// #docregion +import { Component, OnInit } from '@angular/core'; +import { RouteParams, Router } from '@angular/router-deprecated'; + +import { Hero, HeroService } from './hero.service'; + +@Component({ + template: ` +

HEROES

+
+

"{{hero.name}}"

+
+ {{hero.id}}
+
+ + +
+

+ +

+
+ `, +}) +export class HeroDetailComponent implements OnInit { + hero: Hero; + + // #docregion ctor + constructor( + private router:Router, + private routeParams:RouteParams, + private service:HeroService){} + // #enddocregion ctor + + // #docregion ngOnInit + ngOnInit() { + let id = this.routeParams.get('id'); + this.service.getHero(id).then(hero => this.hero = hero); + } + // #enddocregion ngOnInit + + // #docregion gotoHeroes + gotoHeroes() { + let heroId = this.hero ? this.hero.id : null; + // Pass along the hero id if available + // so that the HeroList component can select that hero. + // Add a totally useless `foo` parameter for kicks. + // #docregion gotoHeroes-navigate + this.router.navigate(['Heroes', {id: heroId, foo: 'foo'} ]); + // #enddocregion gotoHeroes-navigate + } + // #enddocregion gotoHeroes +} diff --git a/public/docs/_examples/router-deprecated/ts/app/heroes/hero-list.component.1.ts b/public/docs/_examples/router-deprecated/ts/app/heroes/hero-list.component.1.ts new file mode 100644 index 0000000000..cd11dc8e1a --- /dev/null +++ b/public/docs/_examples/router-deprecated/ts/app/heroes/hero-list.component.1.ts @@ -0,0 +1,50 @@ +// #docplaster + +// #docregion +// TODO SOMEDAY: Feature Componetized like HeroCenter +import { Component, OnInit } from '@angular/core'; +import { Router } from '@angular/router-deprecated'; + +import { Hero, HeroService } from './hero.service'; + +@Component({ + // #docregion template + template: ` +

HEROES

+
    +
  • + {{hero.id}} {{hero.name}} +
  • +
+ ` + // #enddocregion template +}) +export class HeroListComponent implements OnInit { + heroes: Hero[]; + + // #docregion ctor + constructor( + private router: Router, + private service: HeroService) { } + // #enddocregion ctor + + ngOnInit() { + this.service.getHeroes().then(heroes => this.heroes = heroes) + } + + // #docregion select + onSelect(hero: Hero) { + // #docregion nav-to-detail + this.router.navigate( ['HeroDetail', { id: hero.id }] ); + // #enddocregion nav-to-detail + } + // #enddocregion select +} +// #enddocregion + +/* A link parameters array +// #docregion link-parameters-array +['HeroDetail', { id: hero.id }] // {id: 15} +// #enddocregion link-parameters-array +*/ \ No newline at end of file diff --git a/public/docs/_examples/router-deprecated/ts/app/heroes/hero-list.component.ts b/public/docs/_examples/router-deprecated/ts/app/heroes/hero-list.component.ts new file mode 100644 index 0000000000..0f27e98cd6 --- /dev/null +++ b/public/docs/_examples/router-deprecated/ts/app/heroes/hero-list.component.ts @@ -0,0 +1,56 @@ +// #docplaster + +// TODO SOMEDAY: Feature Componetized like CrisisCenter +// #docregion +import { Component, OnInit } from '@angular/core'; +// #docregion import-route-params +import { RouteParams, Router } from '@angular/router-deprecated'; +// #enddocregion import-route-params + +import { Hero, HeroService } from './hero.service'; + +@Component({ + // #docregion template + template: ` +

HEROES

+
    +
  • + {{hero.id}} {{hero.name}} +
  • +
+ ` + // #enddocregion template +}) +export class HeroListComponent implements OnInit { + heroes: Hero[]; + + // #docregion ctor + private selectedId: number; + + constructor( + private service: HeroService, + private router: Router, + routeParams: RouteParams) { + this.selectedId = +routeParams.get('id'); + } + // #enddocregion ctor + + // #docregion isSelected + isSelected(hero: Hero) { return hero.id === this.selectedId; } + // #enddocregion isSelected + + // #docregion select + onSelect(hero: Hero) { + this.router.navigate( ['HeroDetail', { id: hero.id }] ); + } + // #enddocregion select + + ngOnInit() { + + + this.service.getHeroes().then(heroes => this.heroes = heroes) + } +} +// #enddocregion diff --git a/public/docs/_examples/router-deprecated/ts/app/heroes/hero.service.ts b/public/docs/_examples/router-deprecated/ts/app/heroes/hero.service.ts new file mode 100644 index 0000000000..a2c4495cb6 --- /dev/null +++ b/public/docs/_examples/router-deprecated/ts/app/heroes/hero.service.ts @@ -0,0 +1,27 @@ +// #docregion +import { Injectable } from '@angular/core'; + +export class Hero { + constructor(public id: number, public name: string) { } +} + +@Injectable() +export class HeroService { + getHeroes() { return heroesPromise; } + + getHero(id: number | string) { + return heroesPromise + .then(heroes => heroes.filter(h => h.id === +id)[0]); + } +} + +var HEROES = [ + new Hero(11, 'Mr. Nice'), + new Hero(12, 'Narco'), + new Hero(13, 'Bombasto'), + new Hero(14, 'Celeritas'), + new Hero(15, 'Magneta'), + new Hero(16, 'RubberMan') +]; + +var heroesPromise = Promise.resolve(HEROES); diff --git a/public/docs/_examples/router-deprecated/ts/app/main.1.ts b/public/docs/_examples/router-deprecated/ts/app/main.1.ts new file mode 100644 index 0000000000..8ff3ff84fb --- /dev/null +++ b/public/docs/_examples/router-deprecated/ts/app/main.1.ts @@ -0,0 +1,24 @@ +/* First version */ +// #docplaster + +// #docregion all +import { bootstrap } from '@angular/platform-browser-dynamic'; +import { ROUTER_PROVIDERS } from '@angular/router-deprecated'; + +import { AppComponent } from './app.component'; + +// #enddocregion all + +/* Can't use AppComponent ... but display as if we can +// #docregion all +bootstrap(AppComponent, [ +// #enddocregion all +*/ + +// Actually use the v.1 component +import { AppComponent as ac} from './app.component.1'; +bootstrap(ac, [ +// #docregion all + ROUTER_PROVIDERS +]); +// #enddocregion all diff --git a/public/docs/_examples/router-deprecated/ts/app/main.2.ts b/public/docs/_examples/router-deprecated/ts/app/main.2.ts new file mode 100644 index 0000000000..9a04fa8109 --- /dev/null +++ b/public/docs/_examples/router-deprecated/ts/app/main.2.ts @@ -0,0 +1,33 @@ +/* Second version */ +// For Milestone #2 +// Also includes digression on HashPathStrategy (not used in the final app) +// #docplaster + +// #docregion +import { bootstrap } from '@angular/platform-browser-dynamic'; +import { ROUTER_PROVIDERS } from '@angular/router-deprecated'; + +// Add these symbols to override the `LocationStrategy` +import { provide } from '@angular/core'; +import { LocationStrategy, + HashLocationStrategy } from '@angular/common'; + +import { AppComponent } from './app.component'; +// #enddocregion +/* Can't use AppComponent ... but display as if we can +// #docregion + +bootstrap(AppComponent, [ +// #enddocregion +*/ + +// Actually use the v.2 component +import { AppComponent as ac } from './app.component.2'; + +bootstrap(ac, [ +// #docregion + ROUTER_PROVIDERS, + provide(LocationStrategy, + {useClass: HashLocationStrategy}) // .../#/crisis-center/ +]); +// #enddocregion diff --git a/public/docs/_examples/router-deprecated/ts/app/main.3.ts b/public/docs/_examples/router-deprecated/ts/app/main.3.ts new file mode 100644 index 0000000000..9e9eb04721 --- /dev/null +++ b/public/docs/_examples/router-deprecated/ts/app/main.3.ts @@ -0,0 +1,7 @@ +// #docregion +import { bootstrap } from '@angular/platform-browser-dynamic'; +import { ROUTER_PROVIDERS } from '@angular/router-deprecated'; + +import { AppComponent } from './app.component.3'; + +bootstrap(AppComponent, [ROUTER_PROVIDERS]); diff --git a/public/docs/_examples/router-deprecated/ts/app/main.ts b/public/docs/_examples/router-deprecated/ts/app/main.ts new file mode 100644 index 0000000000..08bbbef6e8 --- /dev/null +++ b/public/docs/_examples/router-deprecated/ts/app/main.ts @@ -0,0 +1,7 @@ +// #docregion +import { bootstrap } from '@angular/platform-browser-dynamic'; +import { ROUTER_PROVIDERS } from '@angular/router-deprecated'; + +import { AppComponent } from './app.component'; + +bootstrap(AppComponent, [ROUTER_PROVIDERS]); diff --git a/public/docs/_examples/router-deprecated/ts/example-config.json b/public/docs/_examples/router-deprecated/ts/example-config.json new file mode 100644 index 0000000000..e69de29bb2 diff --git a/public/docs/_examples/router-deprecated/ts/index.1.html b/public/docs/_examples/router-deprecated/ts/index.1.html new file mode 100644 index 0000000000..7a58c4ec50 --- /dev/null +++ b/public/docs/_examples/router-deprecated/ts/index.1.html @@ -0,0 +1,33 @@ + + + + + + + + Router (Deprecated) Sample v.1 + + + + + + + + + + + + + + + + +

Milestone 1

+ loading... + + + + diff --git a/public/docs/_examples/router-deprecated/ts/index.2.html b/public/docs/_examples/router-deprecated/ts/index.2.html new file mode 100644 index 0000000000..83c06e1af6 --- /dev/null +++ b/public/docs/_examples/router-deprecated/ts/index.2.html @@ -0,0 +1,31 @@ + + + + + + Router (Deprecated) Sample v.2 + + + + + + + + + + + + + + + + +

Milestone 2

+ loading... + + + + diff --git a/public/docs/_examples/router-deprecated/ts/index.3.html b/public/docs/_examples/router-deprecated/ts/index.3.html new file mode 100644 index 0000000000..2a5fc893ae --- /dev/null +++ b/public/docs/_examples/router-deprecated/ts/index.3.html @@ -0,0 +1,31 @@ + + + + + + Router (Deprecated) Sample v.3 + + + + + + + + + + + + + + + + +

Milestone 3

+ loading... + + + + diff --git a/public/docs/_examples/router-deprecated/ts/index.html b/public/docs/_examples/router-deprecated/ts/index.html new file mode 100644 index 0000000000..9ac268d05f --- /dev/null +++ b/public/docs/_examples/router-deprecated/ts/index.html @@ -0,0 +1,30 @@ + + + + + + + Router (Deprecated) Sample + + + + + + + + + + + + + + + + + loading... + + + + diff --git a/public/docs/_examples/router-deprecated/ts/plnkr.json b/public/docs/_examples/router-deprecated/ts/plnkr.json new file mode 100644 index 0000000000..91eff6fdb9 --- /dev/null +++ b/public/docs/_examples/router-deprecated/ts/plnkr.json @@ -0,0 +1,12 @@ +{ + "description": "Router (Deprecated Beta)", + "files":[ + "!**/*.d.ts", + "!**/*.js", + "!**/*.[1,2,3].*", + "!app/crisis-list.component.ts", + "!app/hero-list.component.ts", + "!app/crisis-center/add-crisis.component.ts" + ], + "tags": ["router", "deprecated"] +} diff --git a/public/docs/_examples/router/e2e-spec.js b/public/docs/_examples/router/e2e-spec.js index bd3f84ee83..4e3018b5c2 100644 --- a/public/docs/_examples/router/e2e-spec.js +++ b/public/docs/_examples/router/e2e-spec.js @@ -92,7 +92,8 @@ describe('Router', function () { function crisisCenterEdit(index, shouldSave) { var page = getPageStruct(); var crisisEle, crisisText; - page.crisisHref.click().then(function () { + page.crisisHref.click() + .then(function () { crisisEle = page.crisisList.get(index); return crisisEle.getText(); }).then(function (text) { diff --git a/public/docs/_examples/router/ts/app/app.component.1.ts b/public/docs/_examples/router/ts/app/app.component.1.ts index 0ceeb73848..a041cb2198 100644 --- a/public/docs/_examples/router/ts/app/app.component.1.ts +++ b/public/docs/_examples/router/ts/app/app.component.1.ts @@ -3,12 +3,10 @@ // #docregion import { Component } from '@angular/core'; -// #docregion import-router -import { RouteConfig, ROUTER_DIRECTIVES } from '@angular/router-deprecated'; -// #enddocregion import-router +import { ROUTER_DIRECTIVES, Routes } from '@angular/router'; -import { CrisisListComponent } from './crisis-list.component'; -import { HeroListComponent } from './hero-list.component'; +import { CrisisListComponent } from './crisis-list.component'; +import { HeroListComponent } from './hero-list.component'; @Component({ selector: 'my-app', @@ -16,8 +14,8 @@ import { HeroListComponent } from './hero-list.component'; template: `

Component Router

`, @@ -26,16 +24,17 @@ import { HeroListComponent } from './hero-list.component'; }) // #enddocregion /* -// #docregion route-config -@Component({ ... }) -// #enddocregion route-config -*/ + // #docregion route-config + @Component({ ... }) + // #enddocregion route-config + */ // #docregion // #docregion route-config -@RouteConfig([ +@Routes([ // #docregion route-defs - {path: '/crisis-center', name: 'CrisisCenter', component: CrisisListComponent}, - {path: '/heroes', name: 'Heroes', component: HeroListComponent} + {path: '/crisis-center', component: CrisisListComponent}, + {path: '/heroes', component: HeroListComponent}, + {path: '*', component: CrisisListComponent} // #enddocregion route-defs ]) export class AppComponent { } diff --git a/public/docs/_examples/router/ts/app/app.component.2.ts b/public/docs/_examples/router/ts/app/app.component.2.ts index ec0cb936b3..5cbe9b1e7e 100644 --- a/public/docs/_examples/router/ts/app/app.component.2.ts +++ b/public/docs/_examples/router/ts/app/app.component.2.ts @@ -2,25 +2,25 @@ // #docplaster // #docregion -import {Component} from '@angular/core'; -import {RouteConfig, ROUTER_DIRECTIVES} from '@angular/router-deprecated'; +import { Component, OnInit } from '@angular/core'; +import { Router, ROUTER_DIRECTIVES, Routes } from '@angular/router'; -import {CrisisListComponent} from './crisis-list.component'; +import { CrisisListComponent } from './crisis-list.component'; // #enddocregion /* -// Apparent Milestone 2 imports -// #docregion -// #docregion hero-import -import {HeroListComponent} from './heroes/hero-list.component'; -import {HeroDetailComponent} from './heroes/hero-detail.component'; -import {HeroService} from './heroes/hero.service'; -// #enddocregion hero-import -// #enddocregion -*/ + // Apparent Milestone 2 imports + // #docregion + // #docregion hero-import + import { HeroDetailComponent } from './heroes/hero-detail.component'; + import { HeroListComponent } from './heroes/hero-list.component'; + import { HeroService } from './heroes/hero.service'; + // #enddocregion hero-import + // #enddocregion + */ // Actual Milestone 2 imports -import {HeroListComponent} from './heroes/hero-list.component.1'; -import {HeroDetailComponent} from './heroes/hero-detail.component.1'; -import {HeroService} from './heroes/hero.service'; +import { HeroDetailComponent } from './heroes/hero-detail.component.1'; +import { HeroListComponent } from './heroes/hero-list.component.1'; +import { HeroService } from './heroes/hero.service'; // #docregion @Component({ @@ -28,8 +28,8 @@ import {HeroService} from './heroes/hero.service'; template: `

Component Router

`, @@ -38,21 +38,27 @@ import {HeroService} from './heroes/hero.service'; }) // #enddocregion /* -// #docregion route-config -@Component({ ... }) -// #enddocregion route-config -*/ + // #docregion route-config + @Component({ ... }) + // #enddocregion route-config + */ // #docregion // #docregion route-config -@RouteConfig([ +@Routes([ // #docregion route-defs - {path: '/crisis-center', name: 'CrisisCenter', component: CrisisListComponent}, - {path: '/heroes', name: 'Heroes', component: HeroListComponent}, + {path: '/crisis-center', component: CrisisListComponent}, + {path: '/heroes', component: HeroListComponent}, // #docregion hero-detail-route - {path: '/hero/:id', name: 'HeroDetail', component: HeroDetailComponent} + {path: '/hero/:id', component: HeroDetailComponent} // #enddocregion hero-detail-route // #enddocregion route-defs ]) -export class AppComponent { } +export class AppComponent implements OnInit { + constructor(private router: Router) {} + + ngOnInit() { + this.router.navigate(['/crisis-center']); + } +} // #enddocregion route-config // #enddocregion diff --git a/public/docs/_examples/router/ts/app/app.component.3.ts b/public/docs/_examples/router/ts/app/app.component.3.ts index d0bd0b4f84..b44db38fc6 100644 --- a/public/docs/_examples/router/ts/app/app.component.3.ts +++ b/public/docs/_examples/router/ts/app/app.component.3.ts @@ -1,45 +1,48 @@ +/* tslint:disable:no-unused-variable */ // #docplaster -import {Component} from '@angular/core'; -import {RouteConfig, ROUTER_DIRECTIVES} from '@angular/router-deprecated'; +import { Component, OnInit } from '@angular/core'; +import { Router, ROUTER_DIRECTIVES, Routes } from '@angular/router'; -import {CrisisCenterComponent} from './crisis-center/crisis-center.component.1'; +import { CrisisCenterComponent } from './crisis-center/crisis-center.component.1'; +import { HeroDetailComponent } from './heroes/hero-detail.component.1'; +import { HeroListComponent } from './heroes/hero-list.component.1'; -import {DialogService} from './dialog.service'; -import {HeroService} from './heroes/hero.service'; +import { DialogService } from './dialog.service'; +import { HeroService } from './heroes/hero.service'; @Component({ selector: 'my-app', // #enddocregion /* Typical link - // #docregion h-anchor - Heroes - // #enddocregion h-anchor - */ + // #docregion h-anchor + Heroes + // #enddocregion h-anchor + */ /* Incomplete Crisis Center link when CC lacks a default - // #docregion cc-anchor-fail - // The link now fails with a "non-terminal link" error - // #docregion cc-anchor-w-default - Crisis Center - // #enddocregion cc-anchor-w-default - // #enddocregion cc-anchor-fail - */ + // #docregion cc-anchor-fail + // The link now fails with a "non-terminal link" error + // #docregion cc-anchor-w-default + Crisis Center + // #enddocregion cc-anchor-w-default + // #enddocregion cc-anchor-fail + */ /* Crisis Center link when CC lacks a default - // #docregion cc-anchor-no-default - Crisis Center - // #enddocregion cc-anchor-no-default - */ + // #docregion cc-anchor-no-default + Crisis Center + // #enddocregion cc-anchor-no-default + */ /* Crisis Center Detail link - // #docregion Dragon-anchor - Dragon Crisis - // #enddocregion Dragon-anchor - */ + // #docregion Dragon-anchor + Dragon Crisis + // #enddocregion Dragon-anchor + */ // #docregion template template: `

Component Router

`, @@ -47,7 +50,14 @@ import {HeroService} from './heroes/hero.service'; providers: [DialogService, HeroService], directives: [ROUTER_DIRECTIVES] }) -@RouteConfig([ - {path: '/crisis-center/...', name: 'CrisisCenter', component: CrisisCenterComponent}, +@Routes([ + {path: '/crisis-center', component: CrisisCenterComponent}, + {path: '*', component: CrisisCenterComponent} ]) -export class AppComponent { } +export class AppComponent implements OnInit { + constructor(private router: Router) {} + + ngOnInit() { + this.router.navigate(['/crisis-center']); + } +} diff --git a/public/docs/_examples/router/ts/app/app.component.ts b/public/docs/_examples/router/ts/app/app.component.ts index 4d8528c463..aeee375e61 100644 --- a/public/docs/_examples/router/ts/app/app.component.ts +++ b/public/docs/_examples/router/ts/app/app.component.ts @@ -1,14 +1,14 @@ // #docplaster // #docregion -import {Component} from '@angular/core'; -import {RouteConfig, ROUTER_DIRECTIVES} from '@angular/router-deprecated'; +import { Component, OnInit } from '@angular/core'; +import { Routes, Router, ROUTER_DIRECTIVES } from '@angular/router'; -import {CrisisCenterComponent} from './crisis-center/crisis-center.component'; -import {HeroListComponent} from './heroes/hero-list.component'; -import {HeroDetailComponent} from './heroes/hero-detail.component'; +import { CrisisCenterComponent } from './crisis-center/crisis-center.component'; +import { HeroListComponent } from './heroes/hero-list.component'; +import { HeroDetailComponent } from './heroes/hero-detail.component'; -import {DialogService} from './dialog.service'; -import {HeroService} from './heroes/hero.service'; +import { DialogService } from './dialog.service'; +import { HeroService } from './heroes/hero.service'; @Component({ selector: 'my-app', @@ -16,8 +16,8 @@ import {HeroService} from './heroes/hero.service'; template: `

Component Router

`, @@ -25,20 +25,17 @@ import {HeroService} from './heroes/hero.service'; providers: [DialogService, HeroService], directives: [ROUTER_DIRECTIVES] }) -// #docregion route-config -@RouteConfig([ - - // #docregion route-config-cc - { // Crisis Center child route - path: '/crisis-center/...', - name: 'CrisisCenter', - component: CrisisCenterComponent, - useAsDefault: true - }, - // #enddocregion route-config-cc - - {path: '/heroes', name: 'Heroes', component: HeroListComponent}, - {path: '/hero/:id', name: 'HeroDetail', component: HeroDetailComponent}, +// #docregion routes +@Routes([ + {path: '/crisis-center', component: CrisisCenterComponent}, + {path: '/heroes', component: HeroListComponent}, + {path: '/hero/:id', component: HeroDetailComponent}, ]) -// #enddocregion route-config -export class AppComponent { } +// #enddocregion routes +export class AppComponent implements OnInit { + constructor(private router: Router) {} + + ngOnInit() { + this.router.navigate(['/crisis-center']); + } +} diff --git a/public/docs/_examples/router/ts/app/crisis-center/crisis-center.component.1.ts b/public/docs/_examples/router/ts/app/crisis-center/crisis-center.component.1.ts index 027d8df037..d195a4a162 100644 --- a/public/docs/_examples/router/ts/app/crisis-center/crisis-center.component.1.ts +++ b/public/docs/_examples/router/ts/app/crisis-center/crisis-center.component.1.ts @@ -1,9 +1,9 @@ -import {Component} from '@angular/core'; -import {RouteConfig, RouterOutlet} from '@angular/router-deprecated'; +import { Component } from '@angular/core'; +import { ROUTER_DIRECTIVES, Routes } from '@angular/router'; -import {CrisisListComponent} from './crisis-list.component.1'; -import {CrisisDetailComponent} from './crisis-detail.component.1'; -import {CrisisService} from './crisis.service'; +import { CrisisDetailComponent } from './crisis-detail.component.1'; +import { CrisisListComponent } from './crisis-list.component.1'; +import { CrisisService } from './crisis.service'; // #docregion minus-imports @Component({ @@ -11,17 +11,17 @@ import {CrisisService} from './crisis.service';

CRISIS CENTER

`, - directives: [RouterOutlet], + directives: [ROUTER_DIRECTIVES], // #docregion providers providers: [CrisisService] // #enddocregion providers }) // #docregion route-config -@RouteConfig([ +@Routes([ // #docregion default-route - {path:'/', name: 'CrisisList', component: CrisisListComponent, useAsDefault: true}, + {path: '/', component: CrisisListComponent}, // , useAsDefault: true}, // coming soon // #enddocregion default-route - {path:'/:id', name: 'CrisisDetail', component: CrisisDetailComponent} + {path: '/:id', component: CrisisDetailComponent} ]) // #enddocregion route-config export class CrisisCenterComponent { } diff --git a/public/docs/_examples/router/ts/app/crisis-center/crisis-center.component.ts b/public/docs/_examples/router/ts/app/crisis-center/crisis-center.component.ts index 77060d936b..73cee8baac 100644 --- a/public/docs/_examples/router/ts/app/crisis-center/crisis-center.component.ts +++ b/public/docs/_examples/router/ts/app/crisis-center/crisis-center.component.ts @@ -1,22 +1,22 @@ // #docregion -import {Component} from '@angular/core'; -import {RouteConfig, RouterOutlet} from '@angular/router-deprecated'; +import { Component } from '@angular/core'; +import { ROUTER_DIRECTIVES, Routes } from '@angular/router'; -import {CrisisListComponent} from './crisis-list.component'; -import {CrisisDetailComponent} from './crisis-detail.component'; -import {CrisisService} from './crisis.service'; +import { CrisisDetailComponent } from './crisis-detail.component'; +import { CrisisListComponent } from './crisis-list.component'; +import { CrisisService } from './crisis.service'; @Component({ template: `

CRISIS CENTER

`, - directives: [RouterOutlet], + directives: [ROUTER_DIRECTIVES], providers: [CrisisService] }) -@RouteConfig([ - {path:'/', name: 'CrisisList', component: CrisisListComponent, useAsDefault: true}, - {path:'/:id', name: 'CrisisDetail', component: CrisisDetailComponent} +@Routes([ + {path: '', component: CrisisListComponent}, // , useAsDefault: true}, // coming soon + {path: '/:id', component: CrisisDetailComponent} ]) export class CrisisCenterComponent { } // #enddocregion diff --git a/public/docs/_examples/router/ts/app/crisis-center/crisis-detail.component.1.ts b/public/docs/_examples/router/ts/app/crisis-center/crisis-detail.component.1.ts index f92180e462..9ac3df8eb8 100644 --- a/public/docs/_examples/router/ts/app/crisis-center/crisis-detail.component.1.ts +++ b/public/docs/_examples/router/ts/app/crisis-center/crisis-detail.component.1.ts @@ -1,15 +1,14 @@ // #docplaster - // #docregion -import {Component, OnInit} from '@angular/core'; -import {Crisis, CrisisService} from './crisis.service'; -import {RouteParams, Router} from '@angular/router-deprecated'; +import { Component } from '@angular/core'; +import { OnActivate, Router, RouteSegment } from '@angular/router'; + +import { Crisis, CrisisService } from './crisis.service'; // #docregion routerCanDeactivate -import {CanDeactivate, ComponentInstruction} from '@angular/router-deprecated'; -import {DialogService} from '../dialog.service'; +// import { CanDeactivate } from '@angular/router'; +import { DialogService } from '../dialog.service'; // #enddocregion routerCanDeactivate - @Component({ // #docregion template template: ` @@ -31,23 +30,22 @@ import {DialogService} from '../dialog.service'; styles: ['input {width: 20em}'] }) // #docregion routerCanDeactivate, cancel-save -export class CrisisDetailComponent implements OnInit, CanDeactivate { +export class CrisisDetailComponent implements OnActivate {// , CanDeactivate { crisis: Crisis; editName: string; // #enddocregion routerCanDeactivate, cancel-save constructor( - private _service: CrisisService, - private _router: Router, - private _routeParams: RouteParams, - private _dialog: DialogService + private service: CrisisService, + private router: Router, + private dialog: DialogService ) { } - // #docregion ngOnInit - ngOnInit() { - let id = +this._routeParams.get('id'); - this._service.getCrisis(id).then(crisis => { + // #docregion ngOnActivate + routerOnActivate(curr: RouteSegment): void { + let id = +curr.getParam('id'); + this.service.getCrisis(id).then(crisis => { if (crisis) { this.editName = crisis.name; this.crisis = crisis; @@ -56,17 +54,18 @@ export class CrisisDetailComponent implements OnInit, CanDeactivate { } }); } - // #enddocregion ngOnInit + // #enddocregion ngOnActivate // #docregion routerCanDeactivate - routerCanDeactivate(next: ComponentInstruction, prev: ComponentInstruction) : any { + // NOT IMPLEMENTED YET + routerCanDeactivate(): any { // Allow synchronous navigation (`true`) if no crisis or the crisis is unchanged. if (!this.crisis || this.crisis.name === this.editName) { return true; } // Otherwise ask the user with the dialog service and return its // promise which resolves to true or false when the user decides - return this._dialog.confirm('Discard changes?'); + return this.dialog.confirm('Discard changes?'); } // #enddocregion routerCanDeactivate @@ -84,8 +83,8 @@ export class CrisisDetailComponent implements OnInit, CanDeactivate { // #docregion gotoCrises gotoCrises() { - // Like Crisis CenterCrisis Center { + routerOnActivate(curr: RouteSegment) { + this.curSegment = curr; + + let id = +curr.getParam('id'); + this.service.getCrisis(id).then(crisis => { if (crisis) { this.editName = crisis.name; this.crisis = crisis; @@ -50,14 +50,14 @@ export class CrisisDetailComponent implements OnInit, CanDeactivate { }); } - routerCanDeactivate(next: ComponentInstruction, prev: ComponentInstruction) : any { + routerCanDeactivate(): any { // Allow synchronous navigation (`true`) if no crisis or the crisis is unchanged. if (!this.crisis || this.crisis.name === this.editName) { return true; } // Otherwise ask the user with the dialog service and return its // promise which resolves to true or false when the user decides - return this._dialog.confirm('Discard changes?'); + return this.dialog.confirm('Discard changes?'); } cancel() { @@ -77,7 +77,11 @@ export class CrisisDetailComponent implements OnInit, CanDeactivate { // so that the CrisisListComponent can select that hero. // Add a totally useless `foo` parameter for kicks. // #docregion gotoCrises-navigate - this._router.navigate(['CrisisList', {id: crisisId, foo: 'foo'} ]); + // Absolute link + this.router.navigate(['/crisis-center', {id: crisisId, foo: 'foo'}]); + + // Relative link + // this.router.navigate(['../', {id: crisisId, foo: 'foo'}], this.curSegment); // #enddocregion gotoCrises-navigate } // #enddocregion gotoCrises diff --git a/public/docs/_examples/router/ts/app/crisis-center/crisis-list.component.1.ts b/public/docs/_examples/router/ts/app/crisis-center/crisis-list.component.1.ts index f2fa9c770c..7c78a63bf6 100644 --- a/public/docs/_examples/router/ts/app/crisis-center/crisis-list.component.1.ts +++ b/public/docs/_examples/router/ts/app/crisis-center/crisis-list.component.1.ts @@ -1,9 +1,9 @@ // #docplaster - // #docregion -import {Component, OnInit} from '@angular/core'; -import {Crisis, CrisisService} from './crisis.service'; -import {Router} from '@angular/router-deprecated'; +import { Component } from '@angular/core'; +import { OnActivate, Router, RouteSegment } from '@angular/router'; + +import { Crisis, CrisisService } from './crisis.service'; @Component({ // #docregion template @@ -17,20 +17,20 @@ import {Router} from '@angular/router-deprecated'; `, // #enddocregion template }) -export class CrisisListComponent implements OnInit { +export class CrisisListComponent implements OnActivate { crises: Crisis[]; constructor( - private _service: CrisisService, - private _router: Router) {} + private service: CrisisService, + private router: Router) {} - ngOnInit() { - this._service.getCrises().then(crises => this.crises = crises); + routerOnActivate(curr: RouteSegment): void { + this.service.getCrises().then(crises => this.crises = crises); } // #docregion select onSelect(crisis: Crisis) { - this._router.navigate(['CrisisDetail', { id: crisis.id }] ); + this.router.navigateByUrl( `/crisis-list/${crisis.id}`); } // #enddocregion select } diff --git a/public/docs/_examples/router/ts/app/crisis-center/crisis-list.component.ts b/public/docs/_examples/router/ts/app/crisis-center/crisis-list.component.ts index 3a6128302f..d6f99ff4b5 100644 --- a/public/docs/_examples/router/ts/app/crisis-center/crisis-list.component.ts +++ b/public/docs/_examples/router/ts/app/crisis-center/crisis-list.component.ts @@ -1,9 +1,9 @@ // #docplaster - // #docregion -import {Component, OnInit} from '@angular/core'; -import {Crisis, CrisisService} from './crisis.service'; -import {Router, RouteParams} from '@angular/router-deprecated'; +import { Component } from '@angular/core'; +import { OnActivate, Router, RouteSegment, RouteTree } from '@angular/router'; + +import { Crisis, CrisisService } from './crisis.service'; @Component({ template: ` @@ -16,25 +16,28 @@ import {Router, RouteParams} from '@angular/router-deprecated'; `, }) -export class CrisisListComponent implements OnInit { +export class CrisisListComponent implements OnActivate { crises: Crisis[]; - - private _selectedId: number; + private currSegment: RouteSegment; + private selectedId: number; constructor( - private _service: CrisisService, - private _router: Router, - routeParams: RouteParams) { - this._selectedId = +routeParams.get('id'); - } + private service: CrisisService, + private router: Router) { } - isSelected(crisis: Crisis) { return crisis.id === this._selectedId; } + isSelected(crisis: Crisis) { return crisis.id === this.selectedId; } - ngOnInit() { - this._service.getCrises().then(crises => this.crises = crises); + routerOnActivate(curr: RouteSegment, prev: RouteSegment, currTree: RouteTree) { + this.currSegment = curr; + this.selectedId = +currTree.parent(curr).getParam('id'); + this.service.getCrises().then(crises => this.crises = crises); } onSelect(crisis: Crisis) { - this._router.navigate( ['CrisisDetail', { id: crisis.id }] ); + // Absolute link + // this.router.navigate([`/crisis-center`, crisis.id]); + + // Relative link + this.router.navigate([`./${crisis.id}`], this.currSegment); } } diff --git a/public/docs/_examples/router/ts/app/crisis-center/crisis.service.ts b/public/docs/_examples/router/ts/app/crisis-center/crisis.service.ts index c71827a656..46158da480 100644 --- a/public/docs/_examples/router/ts/app/crisis-center/crisis.service.ts +++ b/public/docs/_examples/router/ts/app/crisis-center/crisis.service.ts @@ -1,14 +1,26 @@ // #docplaster -// #docregion -import {Injectable} from '@angular/core'; - export class Crisis { constructor(public id: number, public name: string) { } } +const CRISES = [ + new Crisis(1, 'Dragon Burning Cities'), + new Crisis(2, 'Sky Rains Great White Sharks'), + new Crisis(3, 'Giant Asteroid Heading For Earth'), + new Crisis(4, 'Procrastinators Meeting Delayed Again'), +]; + +let crisesPromise = Promise.resolve(CRISES); + +// #docregion +import { Injectable } from '@angular/core'; + @Injectable() export class CrisisService { + + static nextCrisisId = 100; + getCrises() { return crisesPromise; } getCrisis(id: number | string) { @@ -18,24 +30,13 @@ export class CrisisService { // #enddocregion - static nextCrisisId = 100; - - addCrisis(name:string) { + addCrisis(name: string) { name = name.trim(); - if (name){ + if (name) { let crisis = new Crisis(CrisisService.nextCrisisId++, name); crisesPromise.then(crises => crises.push(crisis)); } } // #docregion } - -var crises = [ - new Crisis(1, 'Dragon Burning Cities'), - new Crisis(2, 'Sky Rains Great White Sharks'), - new Crisis(3, 'Giant Asteroid Heading For Earth'), - new Crisis(4, 'Procrastinators Meeting Delayed Again'), -]; - -var crisesPromise = Promise.resolve(crises); // #enddocregion diff --git a/public/docs/_examples/router/ts/app/crisis-list.component.ts b/public/docs/_examples/router/ts/app/crisis-list.component.ts index 9a22de266a..6caa3653b5 100644 --- a/public/docs/_examples/router/ts/app/crisis-list.component.ts +++ b/public/docs/_examples/router/ts/app/crisis-list.component.ts @@ -1,6 +1,6 @@ // Initial empty version // #docregion -import {Component} from '@angular/core'; +import { Component } from '@angular/core'; @Component({ template: ` diff --git a/public/docs/_examples/router/ts/app/dialog.service.ts b/public/docs/_examples/router/ts/app/dialog.service.ts index c795945d2b..b6e234b6ea 100644 --- a/public/docs/_examples/router/ts/app/dialog.service.ts +++ b/public/docs/_examples/router/ts/app/dialog.service.ts @@ -1,5 +1,5 @@ // #docregion -import {Injectable} from '@angular/core'; +import { Injectable } from '@angular/core'; /** * Async modal dialog service * DialogService makes this app easier to test by faking this service. @@ -11,7 +11,7 @@ export class DialogService { * Ask user to confirm an action. `message` explains the action and choices. * Returns promise resolving to `true`=confirm or `false`=cancel */ - confirm(message?:string) { + confirm(message?: string) { return new Promise((resolve, reject) => resolve(window.confirm(message || 'Is it OK?'))); }; diff --git a/public/docs/_examples/router/ts/app/hero-list.component.ts b/public/docs/_examples/router/ts/app/hero-list.component.ts index 48c108dde1..5dbbe17d8e 100644 --- a/public/docs/_examples/router/ts/app/hero-list.component.ts +++ b/public/docs/_examples/router/ts/app/hero-list.component.ts @@ -1,6 +1,6 @@ /// Initial empty version // #docregion -import {Component} from '@angular/core'; +import { Component } from '@angular/core'; @Component({ template: ` diff --git a/public/docs/_examples/router/ts/app/heroes/hero-detail.component.1.ts b/public/docs/_examples/router/ts/app/heroes/hero-detail.component.1.ts index 7002b9a1dd..eecc838ab3 100644 --- a/public/docs/_examples/router/ts/app/heroes/hero-detail.component.1.ts +++ b/public/docs/_examples/router/ts/app/heroes/hero-detail.component.1.ts @@ -1,7 +1,8 @@ // #docregion -import {Component, OnInit} from '@angular/core'; -import {Hero, HeroService} from './hero.service'; -import {RouteParams, Router} from '@angular/router-deprecated'; +import { Component } from '@angular/core'; +import { OnActivate, Router, RouteSegment } from '@angular/router'; + +import { Hero, HeroService } from './hero.service'; @Component({ template: ` @@ -20,27 +21,26 @@ import {RouteParams, Router} from '@angular/router-deprecated'; `, }) -export class HeroDetailComponent implements OnInit { +export class HeroDetailComponent implements OnActivate { hero: Hero; // #docregion ctor constructor( - private _router:Router, - private _routeParams:RouteParams, - private _service:HeroService){} + private router: Router, + private service: HeroService) {} // #enddocregion ctor - // #docregion ngOnInit - ngOnInit() { - let id = this._routeParams.get('id'); - this._service.getHero(id).then(hero => this.hero = hero); + // #docregion OnActivate + routerOnActivate(curr: RouteSegment): void { + let id = +curr.getParam('id'); + this.service.getHero(id).then(hero => this.hero = hero); } - // #enddocregion ngOnInit + // #enddocregion OnActivate // #docregion gotoHeroes gotoHeroes() { - // Like Heroes - this._router.navigate(['Heroes']); + // Like Heroes + this.router.navigate(['/heroes']); } // #enddocregion gotoHeroes } diff --git a/public/docs/_examples/router/ts/app/heroes/hero-detail.component.ts b/public/docs/_examples/router/ts/app/heroes/hero-detail.component.ts index edbf163b37..21ab9fba8c 100644 --- a/public/docs/_examples/router/ts/app/heroes/hero-detail.component.ts +++ b/public/docs/_examples/router/ts/app/heroes/hero-detail.component.ts @@ -1,7 +1,8 @@ // #docregion -import {Component, OnInit} from '@angular/core'; -import {Hero, HeroService} from './hero.service'; -import {RouteParams, Router} from '@angular/router-deprecated'; +import { Component } from '@angular/core'; +import { OnActivate, Router, RouteSegment } from '@angular/router'; + +import { Hero, HeroService } from './hero.service'; @Component({ template: ` @@ -20,32 +21,30 @@ import {RouteParams, Router} from '@angular/router-deprecated'; `, }) -export class HeroDetailComponent implements OnInit { +export class HeroDetailComponent implements OnActivate { hero: Hero; // #docregion ctor constructor( - private _router:Router, - private _routeParams:RouteParams, - private _service:HeroService){} + private router: Router, + private service: HeroService) {} // #enddocregion ctor - // #docregion ngOnInit - ngOnInit() { - let id = this._routeParams.get('id'); - this._service.getHero(id).then(hero => this.hero = hero); - } - // #enddocregion ngOnInit - // #docregion gotoHeroes + // #docregion OnActivate + routerOnActivate(curr: RouteSegment): void { + let id = +curr.getParam('id'); + this.service.getHero(id).then(hero => this.hero = hero); + } + // #enddocregion OnActivate + gotoHeroes() { let heroId = this.hero ? this.hero.id : null; // Pass along the hero id if available // so that the HeroList component can select that hero. // Add a totally useless `foo` parameter for kicks. // #docregion gotoHeroes-navigate - this._router.navigate(['Heroes', {id: heroId, foo: 'foo'} ]); + this.router.navigate([`/heroes`, {id: heroId, foo: 'foo'}]); // #enddocregion gotoHeroes-navigate } - // #enddocregion gotoHeroes } diff --git a/public/docs/_examples/router/ts/app/heroes/hero-list.component.1.ts b/public/docs/_examples/router/ts/app/heroes/hero-list.component.1.ts index 18f6c6e36a..967ca97ccb 100644 --- a/public/docs/_examples/router/ts/app/heroes/hero-list.component.1.ts +++ b/public/docs/_examples/router/ts/app/heroes/hero-list.component.1.ts @@ -1,10 +1,10 @@ // #docplaster - // #docregion // TODO SOMEDAY: Feature Componetized like HeroCenter import {Component, OnInit} from '@angular/core'; +import {Router} from '@angular/router'; + import {Hero, HeroService} from './hero.service'; -import {Router} from '@angular/router-deprecated'; @Component({ // #docregion template @@ -24,18 +24,18 @@ export class HeroListComponent implements OnInit { // #docregion ctor constructor( - private _router: Router, - private _service: HeroService) { } + private router: Router, + private service: HeroService) { } // #enddocregion ctor ngOnInit() { - this._service.getHeroes().then(heroes => this.heroes = heroes) + this.service.getHeroes().then(heroes => this.heroes = heroes) } // #docregion select onSelect(hero: Hero) { // #docregion nav-to-detail - this._router.navigate( ['HeroDetail', { id: hero.id }] ); + this.router.navigate(['/hero', hero.id]); // #enddocregion nav-to-detail } // #enddocregion select @@ -43,7 +43,7 @@ export class HeroListComponent implements OnInit { // #enddocregion /* A link parameters array -// #docregion link-parameters-array -['HeroDetail', { id: hero.id }] // {id: 15} -// #enddocregion link-parameters-array -*/ \ No newline at end of file + // #docregion link-parameters-array + ['HeroDetail', { id: hero.id }] // {id: 15} + // #enddocregion link-parameters-array + */ diff --git a/public/docs/_examples/router/ts/app/heroes/hero-list.component.ts b/public/docs/_examples/router/ts/app/heroes/hero-list.component.ts index 3a5127d11f..00361ac9fe 100644 --- a/public/docs/_examples/router/ts/app/heroes/hero-list.component.ts +++ b/public/docs/_examples/router/ts/app/heroes/hero-list.component.ts @@ -1,12 +1,12 @@ // #docplaster - -// TODO SOMEDAY: Feature Componetized like CrisisCenter // #docregion -import {Component, OnInit} from '@angular/core'; -import {Hero, HeroService} from './hero.service'; -// #docregion import-route-params -import {Router, RouteParams} from '@angular/router-deprecated'; -// #enddocregion import-route-params +// TODO SOMEDAY: Feature Componetized like CrisisCenter +import { Component } from '@angular/core'; +// #docregion import-router +import { OnActivate, Router, RouteSegment, RouteTree } from '@angular/router'; +// #enddocregion import-router + +import { Hero, HeroService} from './hero.service'; @Component({ // #docregion template @@ -22,32 +22,31 @@ import {Router, RouteParams} from '@angular/router-deprecated'; ` // #enddocregion template }) -export class HeroListComponent implements OnInit { +export class HeroListComponent implements OnActivate { heroes: Hero[]; // #docregion ctor - private _selectedId: number; + private selectedId: number; constructor( - private _service: HeroService, - private _router: Router, - routeParams: RouteParams) { - this._selectedId = +routeParams.get('id'); - } + private service: HeroService, + private router: Router) { } // #enddocregion ctor + routerOnActivate(curr: RouteSegment, prev?: RouteSegment, currTree?: RouteTree, prevTree?: RouteTree): void { + this.selectedId = +curr.getParam('id'); + this.service.getHeroes().then(heroes => this.heroes = heroes); + } + // #docregion isSelected - isSelected(hero: Hero) { return hero.id === this._selectedId; } + isSelected(hero: Hero) { return hero.id === this.selectedId; } // #enddocregion isSelected // #docregion select onSelect(hero: Hero) { - this._router.navigate( ['HeroDetail', { id: hero.id }] ); + this.router.navigate(['/hero', hero.id]); } // #enddocregion select - ngOnInit() { - this._service.getHeroes().then(heroes => this.heroes = heroes) - } } // #enddocregion diff --git a/public/docs/_examples/router/ts/app/heroes/hero.service.ts b/public/docs/_examples/router/ts/app/heroes/hero.service.ts index 0b6066ee03..7ead04d9a4 100644 --- a/public/docs/_examples/router/ts/app/heroes/hero.service.ts +++ b/public/docs/_examples/router/ts/app/heroes/hero.service.ts @@ -5,6 +5,17 @@ export class Hero { constructor(public id: number, public name: string) { } } +let HEROES = [ + new Hero(11, 'Mr. Nice'), + new Hero(12, 'Narco'), + new Hero(13, 'Bombasto'), + new Hero(14, 'Celeritas'), + new Hero(15, 'Magneta'), + new Hero(16, 'RubberMan') +]; + +let heroesPromise = Promise.resolve(HEROES); + @Injectable() export class HeroService { getHeroes() { return heroesPromise; } @@ -14,14 +25,3 @@ export class HeroService { .then(heroes => heroes.filter(h => h.id === +id)[0]); } } - -var HEROES = [ - new Hero(11, 'Mr. Nice'), - new Hero(12, 'Narco'), - new Hero(13, 'Bombasto'), - new Hero(14, 'Celeritas'), - new Hero(15, 'Magneta'), - new Hero(16, 'RubberMan') -]; - -var heroesPromise = Promise.resolve(HEROES); diff --git a/public/docs/_examples/router/ts/app/main.1.ts b/public/docs/_examples/router/ts/app/main.1.ts index d9a288e6c0..92ff416326 100644 --- a/public/docs/_examples/router/ts/app/main.1.ts +++ b/public/docs/_examples/router/ts/app/main.1.ts @@ -2,10 +2,10 @@ // #docplaster // #docregion all -import {AppComponent} from './app.component'; -import {bootstrap} from '@angular/platform-browser-dynamic'; -import {ROUTER_PROVIDERS} from '@angular/router-deprecated'; +import { bootstrap } from '@angular/platform-browser-dynamic'; +import { ROUTER_PROVIDERS } from '@angular/router'; +import { AppComponent } from './app.component'; // #enddocregion all /* Can't use AppComponent ... but display as if we can @@ -15,9 +15,9 @@ bootstrap(AppComponent, [ */ // Actually use the v.1 component -import {AppComponent as ac} from './app.component.1'; +import { AppComponent as ac } from './app.component.1'; bootstrap(ac, [ // #docregion all ROUTER_PROVIDERS ]); -// #enddocregion all \ No newline at end of file +// #enddocregion all diff --git a/public/docs/_examples/router/ts/app/main.2.ts b/public/docs/_examples/router/ts/app/main.2.ts index d984713151..3b604f1aca 100644 --- a/public/docs/_examples/router/ts/app/main.2.ts +++ b/public/docs/_examples/router/ts/app/main.2.ts @@ -4,14 +4,15 @@ // #docplaster // #docregion -import {bootstrap} from '@angular/platform-browser-dynamic'; -import {ROUTER_PROVIDERS} from '@angular/router-deprecated'; -import {AppComponent} from './app.component'; +import { bootstrap } from '@angular/platform-browser-dynamic'; +import { ROUTER_PROVIDERS } from '@angular/router'; // Add these symbols to override the `LocationStrategy` -import {provide} from '@angular/core'; -import {LocationStrategy, - HashLocationStrategy} from '@angular/common'; +import { provide } from '@angular/core'; +import { LocationStrategy, + HashLocationStrategy } from '@angular/common'; + +import { AppComponent } from './app.component'; // #enddocregion /* Can't use AppComponent ... but display as if we can // #docregion diff --git a/public/docs/_examples/router/ts/app/main.3.ts b/public/docs/_examples/router/ts/app/main.3.ts index 2c84a01d02..9ee2055ee6 100644 --- a/public/docs/_examples/router/ts/app/main.3.ts +++ b/public/docs/_examples/router/ts/app/main.3.ts @@ -1,7 +1,7 @@ // #docregion -import {bootstrap} from '@angular/platform-browser-dynamic'; -import {ROUTER_PROVIDERS} from '@angular/router-deprecated'; +import { bootstrap } from '@angular/platform-browser-dynamic'; +import { ROUTER_PROVIDERS } from '@angular/router'; -import {AppComponent} from './app.component.3'; +import { AppComponent } from './app.component.3'; bootstrap(AppComponent, [ROUTER_PROVIDERS]); diff --git a/public/docs/_examples/router/ts/app/main.ts b/public/docs/_examples/router/ts/app/main.ts index eb0b424738..34079f84f0 100644 --- a/public/docs/_examples/router/ts/app/main.ts +++ b/public/docs/_examples/router/ts/app/main.ts @@ -1,7 +1,7 @@ // #docregion -import {bootstrap} from '@angular/platform-browser-dynamic'; -import {ROUTER_PROVIDERS} from '@angular/router-deprecated'; +import { bootstrap } from '@angular/platform-browser-dynamic'; +import { ROUTER_PROVIDERS } from '@angular/router'; -import {AppComponent} from './app.component'; +import { AppComponent } from './app.component'; bootstrap(AppComponent, [ROUTER_PROVIDERS]); diff --git a/public/docs/_examples/router/ts/index.2.html b/public/docs/_examples/router/ts/index.2.html index ea4c410a09..d5676ff4b5 100644 --- a/public/docs/_examples/router/ts/index.2.html +++ b/public/docs/_examples/router/ts/index.2.html @@ -2,9 +2,7 @@ - - Router Sample v.2 @@ -29,5 +27,10 @@ loading... + +

Milestone 2

+ loading... + + diff --git a/public/docs/_examples/router/ts/index.3.html b/public/docs/_examples/router/ts/index.3.html index 718343fd62..1be32f1d0d 100644 --- a/public/docs/_examples/router/ts/index.3.html +++ b/public/docs/_examples/router/ts/index.3.html @@ -2,10 +2,8 @@ - - - Router Sample v.4 + Router Sample v.3 diff --git a/public/docs/_examples/router/ts/index.html b/public/docs/_examples/router/ts/index.html index d65a547332..22ee1a8172 100644 --- a/public/docs/_examples/router/ts/index.html +++ b/public/docs/_examples/router/ts/index.html @@ -1,12 +1,10 @@ + - - - Router Sample @@ -21,7 +19,7 @@ diff --git a/public/docs/_examples/server-communication/dart/lib/hero_data.dart b/public/docs/_examples/server-communication/dart/lib/hero_data.dart index 4220e6cd9d..50ec0fab1d 100644 --- a/public/docs/_examples/server-communication/dart/lib/hero_data.dart +++ b/public/docs/_examples/server-communication/dart/lib/hero_data.dart @@ -1,6 +1,8 @@ +// #docregion +import 'package:http/browser_client.dart'; import 'package:http_in_memory_web_api/http_in_memory_web_api.dart'; -CreateDb heroData = () => { +CreateDb createDb = () => { 'heroes': [ {"id": "1", "name": "Windstorm"}, {"id": "2", "name": "Bombasto"}, @@ -8,3 +10,6 @@ CreateDb heroData = () => { {"id": "4", "name": "Tornado"} ] }; + +BrowserClient HttpClientBackendServiceFactory() => + new HttpClientInMemoryBackendService(createDb); diff --git a/public/docs/_examples/server-communication/dart/lib/toh/hero.dart b/public/docs/_examples/server-communication/dart/lib/toh/hero.dart index b7dd9f00ae..6e788437c7 100644 --- a/public/docs/_examples/server-communication/dart/lib/toh/hero.dart +++ b/public/docs/_examples/server-communication/dart/lib/toh/hero.dart @@ -5,11 +5,10 @@ class Hero { Hero(this.id, this.name); - factory Hero.fromJson(Map hero) { - final _id = hero['id']; - final id = _id is int ? _id : int.parse(_id); - return new Hero(id,hero['name']); - } + factory Hero.fromJson(Map hero) => + new Hero(_toInt(hero['id']), hero['name']); Map toJson() => {'id': id, 'name': name}; + + static int _toInt(id) => id is int ? id : int.parse(id); } diff --git a/public/docs/_examples/server-communication/dart/lib/toh/hero_list_component.dart b/public/docs/_examples/server-communication/dart/lib/toh/hero_list_component.dart index d812280943..58fe0bb40c 100644 --- a/public/docs/_examples/server-communication/dart/lib/toh/hero_list_component.dart +++ b/public/docs/_examples/server-communication/dart/lib/toh/hero_list_component.dart @@ -8,22 +8,7 @@ import 'hero_service.dart'; @Component( selector: 'hero-list', -// #docregion template - template: ''' -

Heroes:

-
    -
  • - {{hero.name}} -
  • -
- New Hero: - - -
{{errorMessage}}
- ''', -// #enddocregion template + templateUrl: 'hero_list_component.html', styles: const ['.error {color:red;}']) // #docregion component class HeroListComponent implements OnInit { @@ -33,20 +18,21 @@ class HeroListComponent implements OnInit { HeroListComponent(this._heroService); - bool get hasErrorMessage => errorMessage != null; - - Future ngOnInit() => getHeroes(); + Future ngOnInit() => getHeroes(); // #docregion methods - Future getHeroes() async { + // #docregion getHeroes + Future getHeroes() async { try { heroes = await _heroService.getHeroes(); } catch (e) { errorMessage = e.toString(); } } + // #enddocregion getHeroes - Future addHero(String name) async { + // #docregion addHero + Future addHero(String name) async { name = name.trim(); if (name.isEmpty) return; try { @@ -55,6 +41,7 @@ class HeroListComponent implements OnInit { errorMessage = e.toString(); } } + // #enddocregion addHero // #enddocregion methods } // #enddocregion component diff --git a/public/docs/_examples/server-communication/dart/lib/toh/hero_list_component.html b/public/docs/_examples/server-communication/dart/lib/toh/hero_list_component.html new file mode 100644 index 0000000000..86e2deedd6 --- /dev/null +++ b/public/docs/_examples/server-communication/dart/lib/toh/hero_list_component.html @@ -0,0 +1,13 @@ + +

Heroes:

+
    +
  • + {{hero.name}} +
  • +
+New hero name: + + +
{{errorMessage}}
diff --git a/public/docs/_examples/server-communication/dart/lib/toh/hero_service.dart b/public/docs/_examples/server-communication/dart/lib/toh/hero_service.dart index a009d03b7a..1daedc2d8c 100644 --- a/public/docs/_examples/server-communication/dart/lib/toh/hero_service.dart +++ b/public/docs/_examples/server-communication/dart/lib/toh/hero_service.dart @@ -1,41 +1,71 @@ // #docplaster - // #docregion +// #docregion v1 import 'dart:async'; import 'dart:convert'; - -import 'package:angular2/core.dart'; -// #enddocregion v1 -// #docregion import-request-options -import 'package:http/browser_client.dart'; -// #enddocregion import-request-options -// #docregion v1 import 'hero.dart'; +import 'package:angular2/core.dart'; +import 'package:http/browser_client.dart'; +import 'package:http/http.dart' show Response; @Injectable() class HeroService { - final String _heroesUrl = 'app/heroes'; - BrowserClient _http; + // #docregion endpoint, http-get + final String _heroesUrl = 'app/heroes'; // URL to web API + // #enddocregion endpoint, http-get + final BrowserClient _http; HeroService(this._http); -// #docregion methods + // #docregion methods, error-handling, http-get Future> getHeroes() async { - final response = await _http.get(_heroesUrl); - final heroes = JSON - .decode(response.body)['data'] - .map((value) => new Hero.fromJson(value)) - .toList(); - print(JSON.encode(heroes)); // eyeball results in the console - return heroes; + try { + final response = await _http.get(_heroesUrl); + final heroes = _extractData(response) + .map((value) => new Hero.fromJson(value)) + .toList(); + return heroes; + } catch (e) { + throw _handleError(e); + } } + // #enddocregion error-handling, http-get, v1 + // #docregion addhero, addhero-sig Future addHero(String name) async { - final headers = {'content-type': 'application/json'}; - final body = JSON.encode({'name': name}); - final response = await _http.post(_heroesUrl, headers: headers, body: body); - return new Hero.fromJson(JSON.decode(response.body)); + // #enddocregion addhero-sig + try { + final response = await _http.post(_heroesUrl, + headers: {'Content-Type': 'application/json'}, + body: JSON.encode({'name': name})); + return new Hero.fromJson(_extractData(response)); + } catch (e) { + throw _handleError(e); + } } -// #enddocregion methods + // #enddocregion addhero, v1 + + // #docregion extract-data + dynamic _extractData(Response res) { + var body = JSON.decode(res.body); + // TODO: once fixed, https://github.com/adaojunior/http-in-memory-web-api/issues/1 + // Drop the `?? body` term + return body['data'] ?? body; + } + // #enddocregion extract-data + // #docregion error-handling + + Exception _handleError(dynamic e) { + // In a real world app, we might use a remote logging infrastructure + print(e); // log to console instead + return new Exception('Server error; cause: $e'); + } + // #enddocregion error-handling, methods } // #enddocregion + +/* + // #docregion endpoint-json + private _heroesUrl = 'heroes.json'; // URL to JSON file + // #enddocregion endpoint-json +*/ diff --git a/public/docs/_examples/server-communication/dart/lib/toh/toh_component.dart b/public/docs/_examples/server-communication/dart/lib/toh/toh_component.dart index 80aff10bdf..9c752ed730 100644 --- a/public/docs/_examples/server-communication/dart/lib/toh/toh_component.dart +++ b/public/docs/_examples/server-communication/dart/lib/toh/toh_component.dart @@ -1,35 +1,36 @@ +// #docplaster +// #docregion import 'package:angular2/core.dart'; -import 'package:http_in_memory_web_api/http_in_memory_web_api.dart'; import 'package:http/browser_client.dart'; -import 'package:server_communication/hero_data.dart'; import 'hero_list_component.dart'; import 'hero_service.dart'; - -@Injectable() -HttpClientInMemoryBackendService HttpClientInMemoryBackendServiceFactory() => - new HttpClientInMemoryBackendService(heroData); // in-mem server +// #enddocregion +// #docregion in-mem-web-api +/* ... */ +import 'package:server_communication/hero_data.dart'; +// #docregion @Component( + // #enddocregion in-mem-web-api selector: 'my-toh', -// #docregion template + // #docregion template template: '''

Tour of Heroes

''', -// #enddocregion template + // #enddocregion template + directives: const [HeroListComponent], + // #enddocregion + // #docregion in-mem-web-api + /* ... */ + // #docregion providers: const [ HeroService, -//#enddocregion -//#docregion in-mem-web-api-providers -// in-memory web api providers + // #enddocregion + // in-memory web api providers const Provider(BrowserClient, - useFactory: HttpClientInMemoryBackendServiceFactory) -//#enddocregion in-mem-web-api-providers -//#docregion - ], - directives: const [ - HeroListComponent + useFactory: HttpClientBackendServiceFactory) + // #docregion ]) class TohComponent {} -// #enddocregion diff --git a/public/docs/_examples/server-communication/dart/web/index.html b/public/docs/_examples/server-communication/dart/web/index.html index b6b40d9193..ff2918e0bd 100644 --- a/public/docs/_examples/server-communication/dart/web/index.html +++ b/public/docs/_examples/server-communication/dart/web/index.html @@ -1,18 +1,20 @@ + + Angular 2 Http Demo + + + - - Angular 2 Http Demo - - - - + + + - - ToH Loading... - Wiki Loading... - WikiSmart loading... - + + ToH Loading... + Wiki Loading... + WikiSmart Loading... + diff --git a/public/docs/_examples/server-communication/ts/.gitignore b/public/docs/_examples/server-communication/ts/.gitignore deleted file mode 100644 index d30e27f5f7..0000000000 --- a/public/docs/_examples/server-communication/ts/.gitignore +++ /dev/null @@ -1 +0,0 @@ -!systemjs.config.1.js diff --git a/public/docs/_examples/server-communication/ts/app/add-rxjs-operators.ts b/public/docs/_examples/server-communication/ts/app/add-rxjs-operators.ts new file mode 100644 index 0000000000..1381b30cd9 --- /dev/null +++ b/public/docs/_examples/server-communication/ts/app/add-rxjs-operators.ts @@ -0,0 +1,9 @@ +// #docregion +// import 'rxjs/Rx'; // adds ALL RxJS operators to Observable + +// Just the Observable operators we need for THIS app. +import 'rxjs/add/operator/catch'; +import 'rxjs/add/operator/debounceTime'; +import 'rxjs/add/operator/distinctUntilChanged'; +import 'rxjs/add/operator/map'; +import 'rxjs/add/operator/switchMap'; diff --git a/public/docs/_examples/server-communication/ts/app/hero-data.ts b/public/docs/_examples/server-communication/ts/app/hero-data.ts index 29f58fe663..ad10b464c7 100644 --- a/public/docs/_examples/server-communication/ts/app/hero-data.ts +++ b/public/docs/_examples/server-communication/ts/app/hero-data.ts @@ -2,10 +2,10 @@ export class HeroData { createDb() { let heroes = [ - { "id": "1", "name": "Windstorm" }, - { "id": "2", "name": "Bombasto" }, - { "id": "3", "name": "Magneta" }, - { "id": "4", "name": "Tornado" } + { id: '1', name: 'Windstorm' }, + { id: '2', name: 'Bombasto' }, + { id: '3', name: 'Magneta' }, + { id: '4', name: 'Tornado' } ]; return {heroes}; } diff --git a/public/docs/_examples/server-communication/ts/app/main.ts b/public/docs/_examples/server-communication/ts/app/main.ts index 51371c758d..7fa98321f0 100644 --- a/public/docs/_examples/server-communication/ts/app/main.ts +++ b/public/docs/_examples/server-communication/ts/app/main.ts @@ -6,16 +6,16 @@ import { HTTP_PROVIDERS } from '@angular/http'; // #enddocregion http-providers // #docregion import-rxjs -// Add all operators to Observable -import 'rxjs/Rx'; +// Add the RxJS Observable operators we need in this app. +import './add-rxjs-operators'; // #enddocregion import-rxjs +import { TohComponent } from './toh/toh.component'; import { WikiComponent } from './wiki/wiki.component'; import { WikiSmartComponent } from './wiki/wiki-smart.component'; -import { TohComponent } from './toh/toh.component'; -bootstrap(WikiComponent); -bootstrap(WikiSmartComponent); // #docregion http-providers bootstrap(TohComponent, [HTTP_PROVIDERS]); // #enddocregion http-providers +bootstrap(WikiComponent); +bootstrap(WikiSmartComponent); diff --git a/public/docs/_examples/server-communication/ts/app/toh/hero-list.component.1.ts b/public/docs/_examples/server-communication/ts/app/toh/hero-list.component.1.ts index b12c7c0b7b..3e4c3c6bf2 100644 --- a/public/docs/_examples/server-communication/ts/app/toh/hero-list.component.1.ts +++ b/public/docs/_examples/server-communication/ts/app/toh/hero-list.component.1.ts @@ -1,8 +1,8 @@ // ToH Promise Version // #docregion -import {Component, OnInit} from '@angular/core'; -import {Hero} from './hero'; -import {HeroService} from './hero.service.1'; +import { Component, OnInit } from '@angular/core'; +import { Hero } from './hero'; +import { HeroService } from './hero.service.1'; @Component({ selector: 'hero-list', @@ -12,7 +12,7 @@ import {HeroService} from './hero.service.1'; // #docregion component export class HeroListComponent implements OnInit { - constructor (private _heroService: HeroService) {} + constructor (private heroService: HeroService) {} errorMessage: string; heroes: Hero[]; @@ -21,15 +21,15 @@ export class HeroListComponent implements OnInit { // #docregion methods getHeroes() { - this._heroService.getHeroes() + this.heroService.getHeroes() .then( heroes => this.heroes = heroes, error => this.errorMessage = error); } addHero (name: string) { - if (!name) {return;} - this._heroService.addHero(name) + if (!name) { return; } + this.heroService.addHero(name) .then( hero => this.heroes.push(hero), error => this.errorMessage = error); diff --git a/public/docs/_examples/server-communication/ts/app/toh/hero-list.component.html b/public/docs/_examples/server-communication/ts/app/toh/hero-list.component.html index b4fc477851..c099d222ef 100644 --- a/public/docs/_examples/server-communication/ts/app/toh/hero-list.component.html +++ b/public/docs/_examples/server-communication/ts/app/toh/hero-list.component.html @@ -2,12 +2,12 @@

Heroes:

  • - {{ hero.name }} + {{hero.name}}
-New Hero: - -
{{errorMessage}}
diff --git a/public/docs/_examples/server-communication/ts/app/toh/hero-list.component.ts b/public/docs/_examples/server-communication/ts/app/toh/hero-list.component.ts index 1387de477a..2cb1689e01 100644 --- a/public/docs/_examples/server-communication/ts/app/toh/hero-list.component.ts +++ b/public/docs/_examples/server-communication/ts/app/toh/hero-list.component.ts @@ -1,7 +1,8 @@ // #docregion -import {Component, OnInit} from '@angular/core'; -import {Hero} from './hero'; -import {HeroService} from './hero.service'; +import { Component, OnInit } from '@angular/core'; + +import { Hero } from './hero'; +import { HeroService } from './hero.service'; @Component({ selector: 'hero-list', @@ -11,7 +12,7 @@ import {HeroService} from './hero.service'; // #docregion component export class HeroListComponent implements OnInit { - constructor (private _heroService: HeroService) {} + constructor (private heroService: HeroService) {} errorMessage: string; heroes:Hero[]; @@ -21,7 +22,7 @@ export class HeroListComponent implements OnInit { // #docregion methods // #docregion getHeroes getHeroes() { - this._heroService.getHeroes() + this.heroService.getHeroes() .subscribe( heroes => this.heroes = heroes, error => this.errorMessage = error); @@ -30,8 +31,8 @@ export class HeroListComponent implements OnInit { // #docregion addHero addHero (name: string) { - if (!name) {return;} - this._heroService.addHero(name) + if (!name) { return; } + this.heroService.addHero(name) .subscribe( hero => this.heroes.push(hero), error => this.errorMessage = error); diff --git a/public/docs/_examples/server-communication/ts/app/toh/hero.service.1.ts b/public/docs/_examples/server-communication/ts/app/toh/hero.service.1.ts index 3f2d7f868b..a6da29514a 100644 --- a/public/docs/_examples/server-communication/ts/app/toh/hero.service.1.ts +++ b/public/docs/_examples/server-communication/ts/app/toh/hero.service.1.ts @@ -2,21 +2,21 @@ // #docplaster // #docregion -import {Injectable} from '@angular/core'; -import {Http, Response} from '@angular/http'; -import {Headers, RequestOptions} from '@angular/http'; -import {Hero} from './hero'; +import { Injectable } from '@angular/core'; +import { Http, Response } from '@angular/http'; +import { Headers, RequestOptions } from '@angular/http'; +import { Hero } from './hero'; @Injectable() export class HeroService { constructor (private http: Http) {} // URL to web api - private _heroesUrl = 'app/heroes.json'; + private heroesUrl = 'app/heroes.json'; // #docregion methods getHeroes (): Promise { - return this.http.get(this._heroesUrl) + return this.http.get(this.heroesUrl) .toPromise() .then(this.extractData) .catch(this.handleError); @@ -27,23 +27,21 @@ export class HeroService { let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); - return this.http.post(this._heroesUrl, body, options) + return this.http.post(this.heroesUrl, body, options) .toPromise() .then(this.extractData) .catch(this.handleError); } private extractData(res: Response) { - if (res.status < 200 || res.status >= 300) { - throw new Error('Bad response status: ' + res.status); - } let body = res.json(); return body.data || { }; } private handleError (error: any) { - // In a real world app, we might send the error to remote logging infrastructure - let errMsg = error.message || 'Server error'; + // In a real world app, we might use a remote logging infrastructure + // We'd also dig deeper into the error to get a better message + let errMsg = error.message || error.statusText || 'Server error'; console.error(errMsg); // log to console instead return Promise.reject(errMsg); } diff --git a/public/docs/_examples/server-communication/ts/app/toh/hero.service.ts b/public/docs/_examples/server-communication/ts/app/toh/hero.service.ts index faa04c2475..fcc0348c05 100644 --- a/public/docs/_examples/server-communication/ts/app/toh/hero.service.ts +++ b/public/docs/_examples/server-communication/ts/app/toh/hero.service.ts @@ -1,67 +1,48 @@ // #docplaster - // #docregion // #docregion v1 -import {Injectable} from '@angular/core'; -import {Http, Response} from '@angular/http'; +import { Injectable } from '@angular/core'; +import { Http, Response } from '@angular/http'; // #enddocregion v1 // #docregion import-request-options -import {Headers, RequestOptions} from '@angular/http'; +import { Headers, RequestOptions } from '@angular/http'; // #enddocregion import-request-options // #docregion v1 -import {Hero} from './hero'; -import {Observable} from 'rxjs/Observable'; + +import { Hero } from './hero'; +import { Observable } from 'rxjs/Observable'; @Injectable() export class HeroService { constructor (private http: Http) {} -// #enddocregion -// #enddocregion v1 - - /* - // #docregion endpoint-json - private _heroesUrl = 'app/heroes.json'; // URL to JSON file - // #enddocregion endpoint-json - */ -// #docregion -// #docregion v1 // #docregion endpoint - private _heroesUrl = 'app/heroes'; // URL to web api + private heroesUrl = 'app/heroes'; // URL to web API // #enddocregion endpoint - // #docregion methods - // #docregion error-handling, http-get + // #docregion methods, error-handling, http-get getHeroes (): Observable { - return this.http.get(this._heroesUrl) + return this.http.get(this.heroesUrl) .map(this.extractData) .catch(this.handleError); } - // #enddocregion error-handling, http-get - // #enddocregion v1 - - // #docregion addhero - addHero (name: string): Observable { + // #enddocregion error-handling, http-get, v1 + // #docregion addhero, addhero-sig + addHero (name: string): Observable { + // #enddocregion addhero-sig let body = JSON.stringify({ name }); - // #docregion headers let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); - return this.http.post(this._heroesUrl, body, options) - // #enddocregion headers + return this.http.post(this.heroesUrl, body, options) .map(this.extractData) .catch(this.handleError); } // #enddocregion addhero - // #docregion v1 - - // #docregion extract-data + // #docregion v1, extract-data private extractData(res: Response) { - if (res.status < 200 || res.status >= 300) { - throw new Error('Bad response status: ' + res.status); - } let body = res.json(); return body.data || { }; } @@ -69,12 +50,18 @@ export class HeroService { // #docregion error-handling private handleError (error: any) { - // In a real world app, we might send the error to remote logging infrastructure - let errMsg = error.message || 'Server error'; + // In a real world app, we might use a remote logging infrastructure + // We'd also dig deeper into the error to get a better message + let errMsg = error.message || error.statusText || 'Server error'; console.error(errMsg); // log to console instead return Observable.throw(errMsg); } - // #enddocregion error-handling - // #enddocregion methods + // #enddocregion error-handling, methods } // #enddocregion + +/* + // #docregion endpoint-json + private heroesUrl = 'app/heroes.json'; // URL to JSON file + // #enddocregion endpoint-json +*/ diff --git a/public/docs/_examples/server-communication/ts/app/toh/toh.component.1.ts b/public/docs/_examples/server-communication/ts/app/toh/toh.component.1.ts deleted file mode 100644 index 3603550d37..0000000000 --- a/public/docs/_examples/server-communication/ts/app/toh/toh.component.1.ts +++ /dev/null @@ -1,32 +0,0 @@ -// ToH Promise Version -console.log ('Promise version'); - -import { Component } from '@angular/core'; -import { HTTP_PROVIDERS } from '@angular/http'; - -import { HeroListComponent } from './hero-list.component.1'; -import { HeroService } from './hero.service.1'; - -import { provide } from '@angular/core'; -import { XHRBackend } from '@angular/http'; - -import { InMemoryBackendService, - SEED_DATA } from 'angular2-in-memory-web-api/core'; -import { HeroData } from '../hero-data'; - -@Component({ - selector: 'my-toh', - template: ` -

Tour of Heroes

- - `, - directives:[HeroListComponent], - providers: [ - HTTP_PROVIDERS, - HeroService, - // in-memory web api providers - provide(XHRBackend, { useClass: InMemoryBackendService }), // in-mem server - provide(SEED_DATA, { useClass: HeroData }) // in-mem server data - ] -}) -export class TohComponent { } diff --git a/public/docs/_examples/server-communication/ts/app/toh/toh.component.2.ts b/public/docs/_examples/server-communication/ts/app/toh/toh.component.2.ts deleted file mode 100644 index a8349e0e7c..0000000000 --- a/public/docs/_examples/server-communication/ts/app/toh/toh.component.2.ts +++ /dev/null @@ -1,44 +0,0 @@ -// #docplaster - -// #docregion -import { Component } from '@angular/core'; -import { HTTP_PROVIDERS } from '@angular/http'; - -import { HeroListComponent } from './hero-list.component'; -import { HeroService } from './hero.service'; -// #enddocregion - -// #docregion in-mem-web-api-imports -import { provide } from '@angular/core'; -import { XHRBackend } from '@angular/http'; - -// in-memory web api imports -import { InMemoryBackendService, - SEED_DATA } from 'angular2-in-memory-web-api/core'; -import { HeroData } from '../hero-data'; -// #enddocregion in-mem-web-api-imports -// #docregion - -@Component({ - selector: 'my-toh', -// #docregion template - template: ` -

Tour of Heroes

- - `, - // #enddocregion template - directives: [HeroListComponent], - providers: [ - HTTP_PROVIDERS, - HeroService, -// #enddocregion -// #docregion in-mem-web-api-providers - // in-memory web api providers - provide(XHRBackend, { useClass: InMemoryBackendService }), // in-mem server - provide(SEED_DATA, { useClass: HeroData }) // in-mem server data -// #enddocregion in-mem-web-api-providers -// #docregion - ] -}) -export class TohComponent { } -// #enddocregion diff --git a/public/docs/_examples/server-communication/ts/app/toh/toh.component.ts b/public/docs/_examples/server-communication/ts/app/toh/toh.component.ts index a8349e0e7c..7e0a663918 100644 --- a/public/docs/_examples/server-communication/ts/app/toh/toh.component.ts +++ b/public/docs/_examples/server-communication/ts/app/toh/toh.component.ts @@ -1,5 +1,4 @@ // #docplaster - // #docregion import { Component } from '@angular/core'; import { HTTP_PROVIDERS } from '@angular/http'; diff --git a/public/docs/_examples/server-communication/ts/app/wiki/wiki-smart.component.ts b/public/docs/_examples/server-communication/ts/app/wiki/wiki-smart.component.ts index f34b72d4de..55485b8ff4 100644 --- a/public/docs/_examples/server-communication/ts/app/wiki/wiki-smart.component.ts +++ b/public/docs/_examples/server-communication/ts/app/wiki/wiki-smart.component.ts @@ -1,12 +1,13 @@ +/* tslint:disable:member-ordering */ // #docregion -import {Component} from '@angular/core'; -import {JSONP_PROVIDERS} from '@angular/http'; -import {Observable} from 'rxjs/Observable'; +import { Component } from '@angular/core'; +import { JSONP_PROVIDERS } from '@angular/http'; +import { Observable } from 'rxjs/Observable'; // #docregion import-subject -import {Subject} from 'rxjs/Subject'; +import { Subject } from 'rxjs/Subject'; // #enddocregion import-subject -import {WikipediaService} from './wikipedia.service'; +import { WikipediaService } from './wikipedia.service'; @Component({ selector: 'my-wiki-smart', @@ -20,22 +21,22 @@ import {WikipediaService} from './wikipedia.service';
  • {{item}}
  • `, - providers:[JSONP_PROVIDERS, WikipediaService] + providers: [JSONP_PROVIDERS, WikipediaService] }) export class WikiSmartComponent { - constructor (private _wikipediaService: WikipediaService) { } + constructor (private wikipediaService: WikipediaService) { } // #docregion subject - private _searchTermStream = new Subject(); + private searchTermStream = new Subject(); - search(term:string) { this._searchTermStream.next(term); } + search(term: string) { this.searchTermStream.next(term); } // #enddocregion subject // #docregion observable-operators - items:Observable = this._searchTermStream + items: Observable = this.searchTermStream .debounceTime(300) .distinctUntilChanged() - .switchMap((term:string) => this._wikipediaService.search(term)); + .switchMap((term: string) => this.wikipediaService.search(term)); // #enddocregion observable-operators } diff --git a/public/docs/_examples/server-communication/ts/app/wiki/wiki.component.ts b/public/docs/_examples/server-communication/ts/app/wiki/wiki.component.ts index fa88a0bda6..63a0bc5f81 100644 --- a/public/docs/_examples/server-communication/ts/app/wiki/wiki.component.ts +++ b/public/docs/_examples/server-communication/ts/app/wiki/wiki.component.ts @@ -1,9 +1,9 @@ // #docregion -import {Component} from '@angular/core'; -import {JSONP_PROVIDERS} from '@angular/http'; -import {Observable} from 'rxjs/Observable'; +import { Component } from '@angular/core'; +import { JSONP_PROVIDERS } from '@angular/http'; +import { Observable } from 'rxjs/Observable'; -import {WikipediaService} from './wikipedia.service'; +import { WikipediaService } from './wikipedia.service'; @Component({ selector: 'my-wiki', @@ -12,20 +12,20 @@ import {WikipediaService} from './wikipedia.service';

    Fetches after each keystroke

    - +
    • {{item}}
    `, - providers:[JSONP_PROVIDERS, WikipediaService] + providers: [JSONP_PROVIDERS, WikipediaService] }) export class WikiComponent { - constructor (private _wikipediaService: WikipediaService) {} + constructor (private wikipediaService: WikipediaService) {} items: Observable; search (term: string) { - this.items = this._wikipediaService.search(term); + this.items = this.wikipediaService.search(term); } } diff --git a/public/docs/_examples/server-communication/ts/app/wiki/wikipedia.service.1.ts b/public/docs/_examples/server-communication/ts/app/wiki/wikipedia.service.1.ts index 7556163e71..f57bbf06d3 100644 --- a/public/docs/_examples/server-communication/ts/app/wiki/wikipedia.service.1.ts +++ b/public/docs/_examples/server-communication/ts/app/wiki/wikipedia.service.1.ts @@ -1,7 +1,7 @@ // Create the query string by hand // #docregion -import {Injectable} from '@angular/core'; -import {Jsonp} from '@angular/http'; +import { Injectable } from '@angular/core'; +import { Jsonp } from '@angular/http'; @Injectable() export class WikipediaService { diff --git a/public/docs/_examples/server-communication/ts/app/wiki/wikipedia.service.ts b/public/docs/_examples/server-communication/ts/app/wiki/wikipedia.service.ts index 161fdf9fe7..8bc5747e43 100644 --- a/public/docs/_examples/server-communication/ts/app/wiki/wikipedia.service.ts +++ b/public/docs/_examples/server-communication/ts/app/wiki/wikipedia.service.ts @@ -1,6 +1,6 @@ // #docregion -import {Injectable} from '@angular/core'; -import {Jsonp, URLSearchParams} from '@angular/http'; +import { Injectable } from '@angular/core'; +import { Jsonp, URLSearchParams } from '@angular/http'; @Injectable() export class WikipediaService { @@ -11,8 +11,8 @@ export class WikipediaService { let wikiUrl = 'http://en.wikipedia.org/w/api.php'; // #docregion search-parameters - var params = new URLSearchParams(); - params.set('search', term); // the user's search value + let params = new URLSearchParams(); +params.set('search', term); // the user's search value params.set('action', 'opensearch'); params.set('format', 'json'); params.set('callback', 'JSONP_CALLBACK'); diff --git a/public/docs/_examples/server-communication/ts/index.html b/public/docs/_examples/server-communication/ts/index.html index 65f8067886..21dc568313 100644 --- a/public/docs/_examples/server-communication/ts/index.html +++ b/public/docs/_examples/server-communication/ts/index.html @@ -16,7 +16,7 @@ diff --git a/public/docs/_examples/server-communication/ts/systemjs.config.1.js b/public/docs/_examples/server-communication/ts/systemjs.config.1.js deleted file mode 100644 index fc3e350d5a..0000000000 --- a/public/docs/_examples/server-communication/ts/systemjs.config.1.js +++ /dev/null @@ -1,56 +0,0 @@ -// #docplaster -/** - * System configuration for Angular 2 samples - * Adjust as necessary for your application needs. - * Override at the last minute with global.filterSystemConfig (as plunkers do) - */ -(function(global) { - - // map tells the System loader where to look for things - // #docregion rxjs - var map = { - 'app': 'app', // 'dist', - 'rxjs': 'node_modules/rxjs', - 'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api', - '@angular': 'node_modules/@angular' - }; - // #enddocregion rxjs - - // packages tells the System loader how to load when no filename and/or no extension - // #docregion rxjs - var packages = { - 'app': { main: 'main.js', defaultExtension: 'js' }, - 'rxjs': { defaultExtension: 'js' }, - 'angular2-in-memory-web-api': { defaultExtension: 'js' }, - }; - // #enddocregion rxjs -// #docregion package-names - var packageNames = [ - '@angular/common', - '@angular/compiler', - '@angular/core', - '@angular/http', - '@angular/platform-browser', - '@angular/platform-browser-dynamic', - '@angular/router', - '@angular/testing', - '@angular/upgrade', - ]; - // #enddocregion package-names - - // add package entries for angular packages in the form '@angular/common': { main: 'index.js', defaultExtension: 'js' } - packageNames.forEach(function(pkgName) { - packages[pkgName] = { main: 'index.js', defaultExtension: 'js' }; - }); - - var config = { - map: map, - packages: packages - } - - // filterSystemConfig - index.html's chance to modify config before we register it. - if (global.filterSystemConfig) { global.filterSystemConfig(config); } - - System.config(config); - -})(this); diff --git a/public/docs/_examples/structural-directives/ts/app/heavy-loader.component.ts b/public/docs/_examples/structural-directives/ts/app/heavy-loader.component.ts index 4e66f7866e..8272048b96 100644 --- a/public/docs/_examples/structural-directives/ts/app/heavy-loader.component.ts +++ b/public/docs/_examples/structural-directives/ts/app/heavy-loader.component.ts @@ -1,5 +1,5 @@ // #docregion -import {Component, Input, Output} from '@angular/core'; +import { Component, Input, Output } from '@angular/core'; let nextId = 1; @@ -13,23 +13,23 @@ export class HeavyLoaderComponent { ngOnInit() { // Mock todo: get 10,000 rows of data from the server - this._log(`heavy-loader ${this.id} initialized, + this.log(`heavy-loader ${this.id} initialized, loading 10,000 rows of data from the server`); } ngOnDestroy() { // Mock todo: clean-up - this._log(`heavy-loader ${this.id} destroyed, cleaning up`); + this.log(`heavy-loader ${this.id} destroyed, cleaning up`); } - private _log(msg: string) { + private log(msg: string) { this.logs.push(msg); - this._tick(); + this.tick(); } // Triggers the next round of Angular change detection // after one turn of the browser event loop // ensuring display of msg added in onDestroy - private _tick() { setTimeout(() => { }, 0); } + private tick() { setTimeout(() => { }, 0); } } // #enddocregion diff --git a/public/docs/_examples/structural-directives/ts/app/main.ts b/public/docs/_examples/structural-directives/ts/app/main.ts index bc7a18d255..5f5b5aeb19 100644 --- a/public/docs/_examples/structural-directives/ts/app/main.ts +++ b/public/docs/_examples/structural-directives/ts/app/main.ts @@ -1,4 +1,5 @@ -import {bootstrap} from '@angular/platform-browser-dynamic'; -import {StructuralDirectivesComponent} from './structural-directives.component'; +import { bootstrap } from '@angular/platform-browser-dynamic'; + +import { StructuralDirectivesComponent } from './structural-directives.component'; bootstrap(StructuralDirectivesComponent); diff --git a/public/docs/_examples/structural-directives/ts/app/structural-directives.component.ts b/public/docs/_examples/structural-directives/ts/app/structural-directives.component.ts index 3f21d50037..4620905568 100644 --- a/public/docs/_examples/structural-directives/ts/app/structural-directives.component.ts +++ b/public/docs/_examples/structural-directives/ts/app/structural-directives.component.ts @@ -1,8 +1,8 @@ // #docplaster // #docregion -import {Component, Input, Output} from '@angular/core'; -import {UnlessDirective} from './unless.directive'; -import {HeavyLoaderComponent} from './heavy-loader.component'; +import { Component, Input, Output } from '@angular/core'; +import { UnlessDirective } from './unless.directive'; +import { HeavyLoaderComponent } from './heavy-loader.component'; @Component({ selector: 'structural-directives', diff --git a/public/docs/_examples/structural-directives/ts/app/unless.directive.ts b/public/docs/_examples/structural-directives/ts/app/unless.directive.ts index bc8464f0d6..105fdde4ae 100644 --- a/public/docs/_examples/structural-directives/ts/app/unless.directive.ts +++ b/public/docs/_examples/structural-directives/ts/app/unless.directive.ts @@ -1,10 +1,10 @@ // #docplaster // #docregion // #docregion unless-declaration -import {Directive, Input} from '@angular/core'; +import { Directive, Input } from '@angular/core'; // #enddocregion unless-declaration -import {TemplateRef, ViewContainerRef} from '@angular/core'; +import { TemplateRef, ViewContainerRef } from '@angular/core'; // #docregion unless-declaration @Directive({ selector: '[myUnless]' }) @@ -13,17 +13,17 @@ export class UnlessDirective { // #docregion unless-constructor constructor( - private _templateRef: TemplateRef, - private _viewContainer: ViewContainerRef + private templateRef: TemplateRef, + private viewContainer: ViewContainerRef ) { } // #enddocregion unless-constructor // #docregion unless-set @Input() set myUnless(condition: boolean) { if (!condition) { - this._viewContainer.createEmbeddedView(this._templateRef); + this.viewContainer.createEmbeddedView(this.templateRef); } else { - this._viewContainer.clear(); + this.viewContainer.clear(); } } // #enddocregion unless-set diff --git a/public/docs/_examples/structural-directives/ts/index.html b/public/docs/_examples/structural-directives/ts/index.html index ff7858692c..8df7729afe 100644 --- a/public/docs/_examples/structural-directives/ts/index.html +++ b/public/docs/_examples/structural-directives/ts/index.html @@ -16,7 +16,7 @@ diff --git a/public/docs/_examples/style-guide/ts/04-10/app/typings.d.ts b/public/docs/_examples/style-guide/ts/04-10/app/typings.d.ts deleted file mode 100644 index 6a301ef23a..0000000000 --- a/public/docs/_examples/style-guide/ts/04-10/app/typings.d.ts +++ /dev/null @@ -1 +0,0 @@ -declare var module.id: any; diff --git a/public/docs/_examples/style-guide/ts/06-01/app/app.component.html b/public/docs/_examples/style-guide/ts/06-01/app/app.component.html index b92377d987..82b7c0a173 100644 --- a/public/docs/_examples/style-guide/ts/06-01/app/app.component.html +++ b/public/docs/_examples/style-guide/ts/06-01/app/app.component.html @@ -1,2 +1,2 @@ -
    Bombasta
    +
    Bombasta
    diff --git a/public/docs/_examples/style-guide/ts/07-03/app/app.component.ts b/public/docs/_examples/style-guide/ts/07-03/app/app.component.ts index 2c5502440f..11a08adb3e 100644 --- a/public/docs/_examples/style-guide/ts/07-03/app/app.component.ts +++ b/public/docs/_examples/style-guide/ts/07-03/app/app.component.ts @@ -1,7 +1,7 @@ // #docregion import { Component } from '@angular/core'; -import { HeroListComponent } from './heroes/hero-list.component'; +import { HeroListComponent } from './heroes/hero-list/hero-list.component'; import { HeroService } from './heroes/shared/hero.service'; @Component({ diff --git a/public/docs/_examples/style-guide/ts/07-03/app/heroes/hero-list.component.ts b/public/docs/_examples/style-guide/ts/07-03/app/heroes/hero-list/hero-list.component.ts similarity index 79% rename from public/docs/_examples/style-guide/ts/07-03/app/heroes/hero-list.component.ts rename to public/docs/_examples/style-guide/ts/07-03/app/heroes/hero-list/hero-list.component.ts index caef734945..64508765bb 100644 --- a/public/docs/_examples/style-guide/ts/07-03/app/heroes/hero-list.component.ts +++ b/public/docs/_examples/style-guide/ts/07-03/app/heroes/hero-list/hero-list.component.ts @@ -1,8 +1,8 @@ // #docregion import { Component, OnInit } from '@angular/core'; -import { HeroService } from './shared/hero.service'; -import { Hero } from './shared/hero.model'; +import { HeroService } from '../shared/hero.service'; +import { Hero } from '../shared/hero.model'; @Component({ selector: 'toh-heroes', diff --git a/public/docs/_examples/style-guide/ts/10-01/app/app.component.ts b/public/docs/_examples/style-guide/ts/10-01/app/app.component.ts index 111a0010cb..bdc95b503b 100644 --- a/public/docs/_examples/style-guide/ts/10-01/app/app.component.ts +++ b/public/docs/_examples/style-guide/ts/10-01/app/app.component.ts @@ -1,6 +1,6 @@ // #docregion import { Component } from '@angular/core'; -import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from '@angular/router'; +import { Routes, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from '@angular/router'; import { NavComponent } from './shared/nav/nav.component'; import { DashboardComponent } from './dashboard/dashboard.component'; @@ -17,8 +17,8 @@ import { HeroService } from './heroes/shared/hero.service'; HeroService ] }) -@RouteConfig([ - { path: '/dashboard', name: 'Dashboard', component: DashboardComponent, useAsDefault: true }, - { path: '/heroes/...', name: 'Heroes', component: HeroesComponent }, +@Routes([ + { path: '/dashboard', component: DashboardComponent }, // , useAsDefault: true}, // coming soon + { path: '/heroes/...', component: HeroesComponent }, ]) export class AppComponent {} diff --git a/public/docs/_examples/style-guide/ts/index.html b/public/docs/_examples/style-guide/ts/index.html index e9ceb39f73..9a11de94e3 100644 --- a/public/docs/_examples/style-guide/ts/index.html +++ b/public/docs/_examples/style-guide/ts/index.html @@ -18,7 +18,7 @@ diff --git a/public/docs/_examples/styleguide/ts/index.html b/public/docs/_examples/styleguide/ts/index.html index a2d63d504c..b98f73d603 100644 --- a/public/docs/_examples/styleguide/ts/index.html +++ b/public/docs/_examples/styleguide/ts/index.html @@ -16,7 +16,7 @@ diff --git a/public/docs/_examples/systemjs.config.js b/public/docs/_examples/systemjs.config.js index bd66896d18..dc5c1484b6 100644 --- a/public/docs/_examples/systemjs.config.js +++ b/public/docs/_examples/systemjs.config.js @@ -1,16 +1,16 @@ /** * System configuration for Angular 2 samples * Adjust as necessary for your application needs. - * Override at the last minute with global.filterSystemConfig (as plunkers do) */ (function(global) { // map tells the System loader where to look for things var map = { 'app': 'app', // 'dist', - 'rxjs': 'node_modules/rxjs', + + '@angular': 'node_modules/@angular', 'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api', - '@angular': 'node_modules/@angular' + 'rxjs': 'node_modules/rxjs' }; // packages tells the System loader how to load when no filename and/or no extension @@ -20,21 +20,26 @@ 'angular2-in-memory-web-api': { defaultExtension: 'js' }, }; - var packageNames = [ - '@angular/common', - '@angular/compiler', - '@angular/core', - '@angular/http', - '@angular/platform-browser', - '@angular/platform-browser-dynamic', - '@angular/router-deprecated', - '@angular/testing', - '@angular/upgrade', + var ngPackageNames = [ + 'common', + 'compiler', + 'core', + 'http', + 'platform-browser', + 'platform-browser-dynamic', + 'router', + 'router-deprecated', + 'upgrade', ]; - // add package entries for angular packages in the form '@angular/common': { main: 'index.js', defaultExtension: 'js' } - packageNames.forEach(function(pkgName) { - packages[pkgName] = { main: 'index.js', defaultExtension: 'js' }; + // Add package entries for angular packages + ngPackageNames.forEach(function(pkgName) { + + // Bundled (~40 requests): + packages['@angular/'+pkgName] = { main: pkgName + '.umd.js', defaultExtension: 'js' }; + + // Individual files (~300 requests): + //packages['@angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' }; }); var config = { @@ -42,9 +47,6 @@ packages: packages } - // filterSystemConfig - index.html's chance to modify config before we register it. - if (global.filterSystemConfig) { global.filterSystemConfig(config); } - System.config(config); })(this); diff --git a/public/docs/_examples/systemjs.config.plunker.js b/public/docs/_examples/systemjs.config.plunker.js index 157e142e18..29a93a07c4 100644 --- a/public/docs/_examples/systemjs.config.plunker.js +++ b/public/docs/_examples/systemjs.config.plunker.js @@ -2,18 +2,21 @@ * PLUNKER VERSION (based on systemjs.config.js in angular.io) * System configuration for Angular 2 samples * Adjust as necessary for your application needs. - * Override at the last minute with global.filterSystemConfig (as plunkers do) */ (function(global) { - var ngVer = '@2.0.0-rc.0'; // lock in the angular package version; do not let it float to current! + var ngVer = '@2.0.0-rc.1'; // lock in the angular package version; do not let it float to current! //map tells the System loader where to look for things var map = { - 'app': 'app', // 'dist', + 'app': 'app', + + '@angular': 'https://npmcdn.com/@angular', // sufficient if we didn't pin the version + 'angular2-in-memory-web-api': 'https://npmcdn.com/angular2-in-memory-web-api', // get latest 'rxjs': 'https://npmcdn.com/rxjs@5.0.0-beta.6', - 'angular2-in-memory-web-api': 'https://npmcdn.com/angular2-in-memory-web-api' // get latest - }; + 'ts': 'https://npmcdn.com/plugin-typescript@4.0.10/lib/plugin.js', + 'typescript': 'https://npmcdn.com/typescript@1.8.10/lib/typescript.js', + }; //packages tells the System loader how to load when no filename and/or no extension var packages = { @@ -22,40 +25,49 @@ 'angular2-in-memory-web-api': { defaultExtension: 'js' }, }; - var packageNames = [ - '@angular/common', - '@angular/compiler', - '@angular/core', - '@angular/http', - '@angular/platform-browser', - '@angular/platform-browser-dynamic', - '@angular/router-deprecated', - '@angular/testing', - '@angular/upgrade', + var ngPackageNames = [ + 'common', + 'compiler', + 'core', + 'http', + 'platform-browser', + 'platform-browser-dynamic', + 'router', + 'router-deprecated', + 'upgrade', ]; - // add map entries for angular packages in the form '@angular/common': 'https://npmcdn.com/@angular/common@0.0.0-3' - packageNames.forEach(function(pkgName) { - map[pkgName] = 'https://npmcdn.com/' + pkgName + ngVer; + // Add map entries for each angular package + // only because we're pinning the version with `ngVer`. + ngPackageNames.forEach(function(pkgName) { + map['@angular/'+pkgName] = 'https://npmcdn.com/@angular/' + pkgName + ngVer; }); - // add package entries for angular packages in the form '@angular/common': { main: 'index.js', defaultExtension: 'js' } - packageNames.forEach(function(pkgName) { - packages[pkgName] = { main: 'index.js', defaultExtension: 'js' }; + // Add package entries for angular packages + ngPackageNames.forEach(function(pkgName) { + + // Bundled (~40 requests): + packages['@angular/'+pkgName] = { main: pkgName + '.umd.js', defaultExtension: 'js' }; + + // Individual files (~300 requests): + //packages['@angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' }; }); var config = { - transpiler: 'typescript', + // DEMO ONLY! REAL CODE SHOULD NOT TRANSPILE IN THE BROWSER + transpiler: 'ts', typescriptOptions: { - emitDecoratorMetadata: true + tsconfig: true + }, + meta: { + 'typescript': { + "exports": "ts" + } }, map: map, packages: packages } - // filterSystemConfig - index.html's chance to modify config before we register it. - if (global.filterSystemConfig) { global.filterSystemConfig(config); } - System.config(config); })(this); diff --git a/public/docs/_examples/template-syntax/ts/app/app.component.ts b/public/docs/_examples/template-syntax/ts/app/app.component.ts index e9343da91a..1333f9c24d 100644 --- a/public/docs/_examples/template-syntax/ts/app/app.component.ts +++ b/public/docs/_examples/template-syntax/ts/app/app.component.ts @@ -1,11 +1,11 @@ //#docplaster -import {Component, AfterViewInit, ElementRef, OnInit, QueryList, ViewChildren} from '@angular/core'; -import {NgForm} from '@angular/common'; +import { AfterViewInit, Component, ElementRef, OnInit, QueryList, ViewChildren } from '@angular/core'; +import { NgForm } from '@angular/common'; -import {Hero} from './hero'; -import {HeroDetailComponent, BigHeroDetailComponent} from './hero-detail.component'; -import {MyClickDirective, MyClickDirective2} from './my-click.directive'; +import { Hero } from './hero'; +import { HeroDetailComponent, BigHeroDetailComponent } from './hero-detail.component'; +import { MyClickDirective, MyClickDirective2 } from './my-click.directive'; // Alerter fn: monkey patch during test export function alerter(msg?:string) { @@ -32,7 +32,7 @@ export class AppComponent implements AfterViewInit, OnInit { } ngAfterViewInit() { - this._detectNgForTrackByEffects(); + this.detectNgForTrackByEffects(); } actionName = 'Go for it'; @@ -53,9 +53,9 @@ export class AppComponent implements AfterViewInit, OnInit { deleteHero(hero:Hero){ this.alert('Deleted hero: '+ (hero && hero.firstName)) } - + // DevMode memoization fields - private _priorClasses:{}; + private priorClasses:{}; private _priorStyles:{}; private _priorStyles2:{}; @@ -119,10 +119,10 @@ export class AppComponent implements AfterViewInit, OnInit { // #enddocregion refresh-heroes // #docregion same-as-it-ever-was - private _samenessCount = 5; - moreOfTheSame() {this._samenessCount++;}; + private samenessCount = 5; + moreOfTheSame() {this.samenessCount++;}; get sameAsItEverWas() { - var result:string[] = Array(this._samenessCount); + var result:string[] = Array(this.samenessCount); for (var i=result.length; i-- > 0;){result[i]='same as it ever was ...'} return result; // return [1,2,3,4,5].map(id => { @@ -145,10 +145,10 @@ export class AppComponent implements AfterViewInit, OnInit { } // #enddocregion setClasses // compensate for DevMode (sigh) - if (JSON.stringify(classes) === JSON.stringify(this._priorClasses)){ - return this._priorClasses; + if (JSON.stringify(classes) === JSON.stringify(this.priorClasses)){ + return this.priorClasses; } - this._priorClasses = classes; + this.priorClasses = classes; // #docregion setClasses return classes; } @@ -209,7 +209,7 @@ export class AppComponent implements AfterViewInit, OnInit { heroesNoTrackByChangeCount = 0; heroesWithTrackByChangeCount = 0; - private _detectNgForTrackByEffects() { + private detectNgForTrackByEffects() { this._oldNoTrackBy = toArray(this.childrenNoTrackBy); this._oldWithTrackBy = toArray(this.childrenWithTrackBy); @@ -241,4 +241,4 @@ function toArray(viewChildren:QueryList) { let children = viewChildren.toArray()[0].nativeElement.children; for (var i = 0; i < children.length; i++) { result.push(children[i]); } return result; -} \ No newline at end of file +} diff --git a/public/docs/_examples/template-syntax/ts/app/decorator.directive.ts b/public/docs/_examples/template-syntax/ts/app/decorator.directive.ts index 694d8b2f5e..a7e9c7d93c 100644 --- a/public/docs/_examples/template-syntax/ts/app/decorator.directive.ts +++ b/public/docs/_examples/template-syntax/ts/app/decorator.directive.ts @@ -1,6 +1,6 @@ // Useful for spying on an element // for fun; not used (yet) -import {Directive, ElementRef} from '@angular/core'; +import { Directive, ElementRef } from '@angular/core'; // set the selector for the element type to spy on. @Directive({selector: 'select'}) diff --git a/public/docs/_examples/template-syntax/ts/app/hero-detail.component.ts b/public/docs/_examples/template-syntax/ts/app/hero-detail.component.ts index 52901e4413..b613fa63b4 100644 --- a/public/docs/_examples/template-syntax/ts/app/hero-detail.component.ts +++ b/public/docs/_examples/template-syntax/ts/app/hero-detail.component.ts @@ -1,7 +1,7 @@ // #docplaster -import {Component, Input, Output, EventEmitter} from '@angular/core'; +import { Component, EventEmitter, Input, Output } from '@angular/core'; -import {Hero} from './hero'; +import { Hero } from './hero'; let nextHeroDetailId = 1; diff --git a/public/docs/_examples/template-syntax/ts/app/hero.ts b/public/docs/_examples/template-syntax/ts/app/hero.ts index b576908b96..aca1fd5a72 100644 --- a/public/docs/_examples/template-syntax/ts/app/hero.ts +++ b/public/docs/_examples/template-syntax/ts/app/hero.ts @@ -8,7 +8,8 @@ export class Hero { public url?:string, public rate:number = 100, id?:number) { - this.id = id != null ? id : Hero.nextId++; + + this.id = id != null ? id : Hero.nextId++; } static clone({firstName, lastName, birthdate, url, rate, id} : Hero){ diff --git a/public/docs/_examples/template-syntax/ts/app/main.ts b/public/docs/_examples/template-syntax/ts/app/main.ts index fb12d36bb3..19551339f8 100644 --- a/public/docs/_examples/template-syntax/ts/app/main.ts +++ b/public/docs/_examples/template-syntax/ts/app/main.ts @@ -1,3 +1,5 @@ -import {bootstrap} from '@angular/platform-browser-dynamic'; -import {AppComponent} from './app.component'; +import { bootstrap } from '@angular/platform-browser-dynamic'; + +import { AppComponent } from './app.component'; + bootstrap(AppComponent); \ No newline at end of file diff --git a/public/docs/_examples/template-syntax/ts/app/my-click.directive.ts b/public/docs/_examples/template-syntax/ts/app/my-click.directive.ts index e461c77283..4b2b23b5cf 100644 --- a/public/docs/_examples/template-syntax/ts/app/my-click.directive.ts +++ b/public/docs/_examples/template-syntax/ts/app/my-click.directive.ts @@ -1,20 +1,20 @@ // #docplaster -import {Directive, Output, ElementRef, EventEmitter} from '@angular/core'; +import { Directive, ElementRef, EventEmitter, Output } from '@angular/core'; @Directive({selector:'[myClick]'}) export class MyClickDirective { // #docregion my-click-output-1 @Output('myClick') clicks = new EventEmitter(); // @Output(alias) propertyName = ... // #enddocregion my-click-output-1 - + constructor(el: ElementRef){ el.nativeElement .addEventListener('click', (event:Event) => { - this._toggle = !this._toggle; - this.clicks.emit(this._toggle ? 'Click!' : ''); + this.toggle = !this.toggle; + this.clicks.emit(this.toggle ? 'Click!' : ''); }); } - _toggle = false; + toggle = false; } // #docregion my-click-output-2 @@ -27,13 +27,13 @@ export class MyClickDirective { // #enddocregion my-click-output-2 export class MyClickDirective2 { clicks = new EventEmitter(); - + constructor(el: ElementRef){ el.nativeElement .addEventListener('click', (event:Event) => { - this._toggle = !this._toggle; - this.clicks.emit(this._toggle ? 'Click2!' : ''); + this.toggle = !this.toggle; + this.clicks.emit(this.toggle ? 'Click2!' : ''); }); } - _toggle = false; -} \ No newline at end of file + toggle = false; +} diff --git a/public/docs/_examples/template-syntax/ts/index.html b/public/docs/_examples/template-syntax/ts/index.html index 25c44af909..c7eb394e9c 100644 --- a/public/docs/_examples/template-syntax/ts/index.html +++ b/public/docs/_examples/template-syntax/ts/index.html @@ -16,7 +16,7 @@ diff --git a/public/docs/_examples/testing/ts/index.html b/public/docs/_examples/testing/ts/index.html index 227c2ced7d..07fca45f52 100644 --- a/public/docs/_examples/testing/ts/index.html +++ b/public/docs/_examples/testing/ts/index.html @@ -16,7 +16,7 @@ diff --git a/public/docs/_examples/toh-1/ts/app/app.component.ts b/public/docs/_examples/toh-1/ts/app/app.component.ts index 242a81a8e6..b3cd4e8f55 100644 --- a/public/docs/_examples/toh-1/ts/app/app.component.ts +++ b/public/docs/_examples/toh-1/ts/app/app.component.ts @@ -1,5 +1,5 @@ // #docregion pt1 -import {Component} from '@angular/core'; +import { Component } from '@angular/core'; // #docregion hero-class-1 export class Hero { diff --git a/public/docs/_examples/toh-1/ts/app/main.ts b/public/docs/_examples/toh-1/ts/app/main.ts index a5e9aa55ae..dae4ddf676 100644 --- a/public/docs/_examples/toh-1/ts/app/main.ts +++ b/public/docs/_examples/toh-1/ts/app/main.ts @@ -1,6 +1,7 @@ // #docregion pt1 -import {bootstrap} from '@angular/platform-browser-dynamic'; -import {AppComponent} from './app.component'; +import { bootstrap } from '@angular/platform-browser-dynamic'; + +import { AppComponent } from './app.component'; bootstrap(AppComponent); -// #enddocregion pt1 \ No newline at end of file +// #enddocregion pt1 diff --git a/public/docs/_examples/toh-1/ts/index.html b/public/docs/_examples/toh-1/ts/index.html index d9954575bd..22cff3f553 100644 --- a/public/docs/_examples/toh-1/ts/index.html +++ b/public/docs/_examples/toh-1/ts/index.html @@ -15,7 +15,7 @@ diff --git a/public/docs/_examples/toh-2/ts/app/app.component.ts b/public/docs/_examples/toh-2/ts/app/app.component.ts index 38c03395d5..2dee49f08c 100644 --- a/public/docs/_examples/toh-2/ts/app/app.component.ts +++ b/public/docs/_examples/toh-2/ts/app/app.component.ts @@ -1,5 +1,5 @@ // #docregion pt2 -import {Component} from '@angular/core'; +import { Component } from '@angular/core'; export class Hero { id: number; diff --git a/public/docs/_examples/toh-2/ts/app/main.ts b/public/docs/_examples/toh-2/ts/app/main.ts index a5e9aa55ae..dae4ddf676 100644 --- a/public/docs/_examples/toh-2/ts/app/main.ts +++ b/public/docs/_examples/toh-2/ts/app/main.ts @@ -1,6 +1,7 @@ // #docregion pt1 -import {bootstrap} from '@angular/platform-browser-dynamic'; -import {AppComponent} from './app.component'; +import { bootstrap } from '@angular/platform-browser-dynamic'; + +import { AppComponent } from './app.component'; bootstrap(AppComponent); -// #enddocregion pt1 \ No newline at end of file +// #enddocregion pt1 diff --git a/public/docs/_examples/toh-2/ts/index.html b/public/docs/_examples/toh-2/ts/index.html index 41b96be370..71fc2f4e4a 100644 --- a/public/docs/_examples/toh-2/ts/index.html +++ b/public/docs/_examples/toh-2/ts/index.html @@ -15,7 +15,7 @@ diff --git a/public/docs/_examples/toh-3/ts/app/app.component.ts b/public/docs/_examples/toh-3/ts/app/app.component.ts index 2a0cb20cae..9fc4f99910 100644 --- a/public/docs/_examples/toh-3/ts/app/app.component.ts +++ b/public/docs/_examples/toh-3/ts/app/app.component.ts @@ -1,10 +1,11 @@ //#docregion -import {Component} from '@angular/core'; +import { Component } from '@angular/core'; + // #docregion hero-import -import {Hero} from './hero'; +import { Hero } from './hero'; // #enddocregion hero-import // #docregion hero-detail-import -import {HeroDetailComponent} from './hero-detail.component'; +import { HeroDetailComponent } from './hero-detail.component'; // #enddocregion hero-detail-import @Component({ diff --git a/public/docs/_examples/toh-3/ts/app/hero-detail.component.ts b/public/docs/_examples/toh-3/ts/app/hero-detail.component.ts index 017256c0d9..1192359265 100644 --- a/public/docs/_examples/toh-3/ts/app/hero-detail.component.ts +++ b/public/docs/_examples/toh-3/ts/app/hero-detail.component.ts @@ -1,17 +1,17 @@ // #docplaster // #docregion // #docregion v1 -import {Component, Input} from '@angular/core'; +import { Component, Input } from '@angular/core'; // #enddocregion v1 // #docregion hero-import -import {Hero} from './hero'; +import { Hero } from './hero'; // #enddocregion hero-import // #docregion v1 @Component({ selector: 'my-hero-detail', -// #enddocregion v1 +// #enddocregion v1 // #docregion template template: `
    diff --git a/public/docs/_examples/toh-3/ts/app/main.ts b/public/docs/_examples/toh-3/ts/app/main.ts index a5e9aa55ae..dae4ddf676 100644 --- a/public/docs/_examples/toh-3/ts/app/main.ts +++ b/public/docs/_examples/toh-3/ts/app/main.ts @@ -1,6 +1,7 @@ // #docregion pt1 -import {bootstrap} from '@angular/platform-browser-dynamic'; -import {AppComponent} from './app.component'; +import { bootstrap } from '@angular/platform-browser-dynamic'; + +import { AppComponent } from './app.component'; bootstrap(AppComponent); -// #enddocregion pt1 \ No newline at end of file +// #enddocregion pt1 diff --git a/public/docs/_examples/toh-3/ts/index.html b/public/docs/_examples/toh-3/ts/index.html index b618c2bd5f..01d42394de 100644 --- a/public/docs/_examples/toh-3/ts/index.html +++ b/public/docs/_examples/toh-3/ts/index.html @@ -15,7 +15,7 @@ diff --git a/public/docs/_examples/toh-4/dart/lib/hero_service.dart b/public/docs/_examples/toh-4/dart/lib/hero_service.dart index 4fa0b97e1c..f3f4f85233 100644 --- a/public/docs/_examples/toh-4/dart/lib/hero_service.dart +++ b/public/docs/_examples/toh-4/dart/lib/hero_service.dart @@ -1,5 +1,6 @@ // #docplaster // #docregion +// #docregion just-get-heroes import 'dart:async'; import 'package:angular2/core.dart'; @@ -9,15 +10,17 @@ import 'mock_heroes.dart'; @Injectable() class HeroService { - //#docregion get-heroes + // #docregion get-heroes Future> getHeroes() async => mockHeroes; - //#enddocregion get-heroes - + // #enddocregion get-heroes + // #enddocregion just-get-heroes // See the "Take it slow" appendix - //#docregion get-heroes-slowly + // #docregion get-heroes-slowly Future> getHeroesSlowly() { return new Future.delayed(const Duration(seconds: 2), () => mockHeroes); } - //#enddocregion get-heroes-slowly + // #enddocregion get-heroes-slowly + // #docregion just-get-heroes } +// #enddocregion just-get-heroes // #enddocregion diff --git a/public/docs/_examples/toh-4/ts/app/app.component.1.ts b/public/docs/_examples/toh-4/ts/app/app.component.1.ts index 254a3af91f..42558a8a4b 100644 --- a/public/docs/_examples/toh-4/ts/app/app.component.1.ts +++ b/public/docs/_examples/toh-4/ts/app/app.component.1.ts @@ -1,13 +1,14 @@ // #docplaster // #docregion on-init -import {OnInit} from '@angular/core'; +import { OnInit } from '@angular/core'; // #enddocregion on-init -import {Component} from '@angular/core'; -import {Hero} from './hero'; -import {HeroDetailComponent} from './hero-detail.component'; +import { Component } from '@angular/core'; + +import { Hero } from './hero'; +import { HeroDetailComponent } from './hero-detail.component'; // #docregion hero-service-import -import {HeroService} from './hero.service.1'; +import { HeroService } from './hero.service.1'; // #enddocregion hero-service-import // Testable but never shown @@ -37,12 +38,12 @@ export class AppComponent implements OnInit { heroService = new HeroService(); // don't do this // #enddocregion new-service // #docregion ctor - constructor(private _heroService: HeroService) { } + constructor(private heroService: HeroService) { } // #enddocregion ctor // #docregion getHeroes getHeroes() { //#docregion get-heroes - this.heroes = this._heroService.getHeroes(); + this.heroes = this.heroService.getHeroes(); // #enddocregion get-heroes } // #enddocregion getHeroes @@ -61,4 +62,4 @@ export class AppComponent implements OnInit { // #docregion on-init } // #enddocregion on-init -// #enddocregion \ No newline at end of file +// #enddocregion diff --git a/public/docs/_examples/toh-4/ts/app/app.component.ts b/public/docs/_examples/toh-4/ts/app/app.component.ts index 5087ea012b..9b0de3caeb 100644 --- a/public/docs/_examples/toh-4/ts/app/app.component.ts +++ b/public/docs/_examples/toh-4/ts/app/app.component.ts @@ -1,10 +1,11 @@ // #docplaster // #docregion -import {Component, OnInit} from '@angular/core'; -import {Hero} from './hero'; -import {HeroDetailComponent} from './hero-detail.component'; +import { Component, OnInit } from '@angular/core'; + +import { Hero } from './hero'; +import { HeroDetailComponent } from './hero-detail.component'; // #docregion hero-service-import -import {HeroService} from './hero.service'; +import { HeroService } from './hero.service'; // #enddocregion hero-service-import @Component({ @@ -80,11 +81,11 @@ export class AppComponent implements OnInit { heroes: Hero[]; selectedHero: Hero; - constructor(private _heroService: HeroService) { } + constructor(private heroService: HeroService) { } // #docregion get-heroes getHeroes() { - this._heroService.getHeroes().then(heroes => this.heroes = heroes); + this.heroService.getHeroes().then(heroes => this.heroes = heroes); } // #enddocregion get-heroes diff --git a/public/docs/_examples/toh-4/ts/app/hero-detail.component.ts b/public/docs/_examples/toh-4/ts/app/hero-detail.component.ts index 4f14867356..80d6ca020c 100644 --- a/public/docs/_examples/toh-4/ts/app/hero-detail.component.ts +++ b/public/docs/_examples/toh-4/ts/app/hero-detail.component.ts @@ -1,6 +1,6 @@ // #docregion -import {Component, Input} from '@angular/core'; -import {Hero} from './hero'; +import { Component, Input } from '@angular/core'; +import { Hero } from './hero'; @Component({ selector: 'my-hero-detail', diff --git a/public/docs/_examples/toh-4/ts/app/hero.service.1.ts b/public/docs/_examples/toh-4/ts/app/hero.service.1.ts index 23dde3546d..1374cb25fd 100644 --- a/public/docs/_examples/toh-4/ts/app/hero.service.1.ts +++ b/public/docs/_examples/toh-4/ts/app/hero.service.1.ts @@ -1,9 +1,12 @@ // #docplaster // #docregion -import {HEROES} from './mock-heroes'; // #docregion empty-class -import {Injectable} from '@angular/core'; +import { Injectable } from '@angular/core'; +// #enddocregion empty-class +import { HEROES } from './mock-heroes'; + +// #docregion empty-class // #docregion getHeroes-stub @Injectable() export class HeroService { @@ -17,4 +20,4 @@ export class HeroService { } // #enddocregion getHeroes-stub // #enddocregion empty-class -// #enddocregion \ No newline at end of file +// #enddocregion diff --git a/public/docs/_examples/toh-4/ts/app/hero.service.ts b/public/docs/_examples/toh-4/ts/app/hero.service.ts index 10137658b2..943c8fe2d9 100644 --- a/public/docs/_examples/toh-4/ts/app/hero.service.ts +++ b/public/docs/_examples/toh-4/ts/app/hero.service.ts @@ -1,28 +1,28 @@ // #docplaster // #docregion // #docregion just-get-heroes -import {Injectable} from '@angular/core'; +import { Injectable } from '@angular/core'; -import {Hero} from './hero'; -import {HEROES} from './mock-heroes'; +import { Hero } from './hero'; +import { HEROES } from './mock-heroes'; @Injectable() export class HeroService { - //#docregion get-heroes + // #docregion get-heroes getHeroes() { return Promise.resolve(HEROES); } - //#enddocregion get-heroes + // #enddocregion get-heroes // #enddocregion just-get-heroes // See the "Take it slow" appendix - //#docregion get-heroes-slowly + // #docregion get-heroes-slowly getHeroesSlowly() { return new Promise(resolve => setTimeout(()=>resolve(HEROES), 2000) // 2 seconds ); } - //#enddocregion get-heroes-slowly + // #enddocregion get-heroes-slowly // #docregion just-get-heroes } // #enddocregion just-get-heroes -// #enddocregion \ No newline at end of file +// #enddocregion diff --git a/public/docs/_examples/toh-4/ts/app/main.1.ts b/public/docs/_examples/toh-4/ts/app/main.1.ts index 8f122d2f62..f8cf0497d6 100644 --- a/public/docs/_examples/toh-4/ts/app/main.1.ts +++ b/public/docs/_examples/toh-4/ts/app/main.1.ts @@ -1,4 +1,5 @@ -import {bootstrap} from '@angular/platform-browser-dynamic'; -import {AppComponent} from './app.component.1'; +import { bootstrap } from '@angular/platform-browser-dynamic'; -bootstrap(AppComponent); \ No newline at end of file +import { AppComponent } from './app.component.1'; + +bootstrap(AppComponent); diff --git a/public/docs/_examples/toh-4/ts/app/main.ts b/public/docs/_examples/toh-4/ts/app/main.ts index 07a96da44b..42dbeb9f7d 100644 --- a/public/docs/_examples/toh-4/ts/app/main.ts +++ b/public/docs/_examples/toh-4/ts/app/main.ts @@ -1,4 +1,5 @@ -import {bootstrap} from '@angular/platform-browser-dynamic'; -import {AppComponent} from './app.component'; +import { bootstrap } from '@angular/platform-browser-dynamic'; -bootstrap(AppComponent); \ No newline at end of file +import { AppComponent } from './app.component'; + +bootstrap(AppComponent); diff --git a/public/docs/_examples/toh-4/ts/app/mock-heroes.ts b/public/docs/_examples/toh-4/ts/app/mock-heroes.ts index 617bab5410..35fa5c67a8 100644 --- a/public/docs/_examples/toh-4/ts/app/mock-heroes.ts +++ b/public/docs/_examples/toh-4/ts/app/mock-heroes.ts @@ -1,5 +1,5 @@ // #docregion -import {Hero} from './hero'; +import { Hero } from './hero'; export var HEROES: Hero[] = [ {"id": 11, "name": "Mr. Nice"}, @@ -13,4 +13,4 @@ export var HEROES: Hero[] = [ {"id": 19, "name": "Magma"}, {"id": 20, "name": "Tornado"} ]; -// #enddocregion \ No newline at end of file +// #enddocregion diff --git a/public/docs/_examples/toh-4/ts/index.html b/public/docs/_examples/toh-4/ts/index.html index b618c2bd5f..01d42394de 100644 --- a/public/docs/_examples/toh-4/ts/index.html +++ b/public/docs/_examples/toh-4/ts/index.html @@ -15,7 +15,7 @@ diff --git a/public/docs/_examples/toh-5/dart/example-config.json b/public/docs/_examples/toh-5/dart/example-config.json new file mode 100644 index 0000000000..e69de29bb2 diff --git a/public/docs/_examples/toh-5/ts/app/app.component.1.ts b/public/docs/_examples/toh-5/ts/app/app.component.1.ts index 65fe5d5826..b35870af20 100644 --- a/public/docs/_examples/toh-5/ts/app/app.component.1.ts +++ b/public/docs/_examples/toh-5/ts/app/app.component.1.ts @@ -1,6 +1,7 @@ // #docplaster // #docregion import { Component } from '@angular/core'; + import { HeroService } from './hero.service'; import { HeroesComponent } from './heroes.component'; // #enddocregion diff --git a/public/docs/_examples/toh-5/ts/app/dashboard.component.1.ts b/public/docs/_examples/toh-5/ts/app/dashboard.component.1.ts index 3c92b205c8..430a30ebbe 100644 --- a/public/docs/_examples/toh-5/ts/app/dashboard.component.1.ts +++ b/public/docs/_examples/toh-5/ts/app/dashboard.component.1.ts @@ -6,3 +6,4 @@ import { Component } from '@angular/core'; template: '

    My Dashboard

    ' }) export class DashboardComponent { } + diff --git a/public/docs/_examples/toh-5/ts/app/dashboard.component.2.ts b/public/docs/_examples/toh-5/ts/app/dashboard.component.2.ts index cb32fdff21..3825a7625c 100644 --- a/public/docs/_examples/toh-5/ts/app/dashboard.component.2.ts +++ b/public/docs/_examples/toh-5/ts/app/dashboard.component.2.ts @@ -15,10 +15,10 @@ export class DashboardComponent implements OnInit { heroes: Hero[] = []; - constructor(private _heroService: HeroService) { } + constructor(private heroService: HeroService) { } ngOnInit() { - this._heroService.getHeroes() + this.heroService.getHeroes() .then(heroes => this.heroes = heroes.slice(1,5)); } diff --git a/public/docs/_examples/toh-5/ts/app/dashboard.component.ts b/public/docs/_examples/toh-5/ts/app/dashboard.component.ts index 455e4b4159..64489ff312 100644 --- a/public/docs/_examples/toh-5/ts/app/dashboard.component.ts +++ b/public/docs/_examples/toh-5/ts/app/dashboard.component.ts @@ -24,20 +24,20 @@ export class DashboardComponent implements OnInit { // #docregion ctor constructor( - private _router: Router, - private _heroService: HeroService) { + private router: Router, + private heroService: HeroService) { } // #enddocregion ctor ngOnInit() { - this._heroService.getHeroes() + this.heroService.getHeroes() .then(heroes => this.heroes = heroes.slice(1,5)); } // #docregion goto-detail gotoDetail(hero: Hero) { let link = ['HeroDetail', { id: hero.id }]; - this._router.navigate(link); + this.router.navigate(link); } // #enddocregion goto-detail } diff --git a/public/docs/_examples/toh-5/ts/app/hero-detail.component.ts b/public/docs/_examples/toh-5/ts/app/hero-detail.component.ts index 31d689f772..08af69c69c 100644 --- a/public/docs/_examples/toh-5/ts/app/hero-detail.component.ts +++ b/public/docs/_examples/toh-5/ts/app/hero-detail.component.ts @@ -31,17 +31,17 @@ export class HeroDetailComponent implements OnInit { // #docregion ctor constructor( - private _heroService: HeroService, - private _routeParams: RouteParams) { + private heroService: HeroService, + private routeParams: RouteParams) { } // #enddocregion ctor // #docregion ng-oninit ngOnInit() { // #docregion get-id - let id = +this._routeParams.get('id'); + let id = +this.routeParams.get('id'); // #enddocregion get-id - this._heroService.getHero(id) + this.heroService.getHero(id) .then(hero => this.hero = hero); } // #enddocregion ng-oninit diff --git a/public/docs/_examples/toh-5/ts/app/heroes.component.ts b/public/docs/_examples/toh-5/ts/app/heroes.component.ts index 0061e43f73..6567c899d9 100644 --- a/public/docs/_examples/toh-5/ts/app/heroes.component.ts +++ b/public/docs/_examples/toh-5/ts/app/heroes.component.ts @@ -27,11 +27,11 @@ export class HeroesComponent implements OnInit { selectedHero: Hero; constructor( - private _router: Router, - private _heroService: HeroService) { } + private router: Router, + private heroService: HeroService) { } getHeroes() { - this._heroService.getHeroes().then(heroes => this.heroes = heroes); + this.heroService.getHeroes().then(heroes => this.heroes = heroes); } ngOnInit() { @@ -41,10 +41,10 @@ export class HeroesComponent implements OnInit { onSelect(hero: Hero) { this.selectedHero = hero; } gotoDetail() { - this._router.navigate(['HeroDetail', { id: this.selectedHero.id }]); + this.router.navigate(['HeroDetail', { id: this.selectedHero.id }]); } // #docregion heroes-component-renaming } // #enddocregion heroes-component-renaming // #enddocregion class -// #enddocregion \ No newline at end of file +// #enddocregion diff --git a/public/docs/_examples/toh-5/ts/app/main.ts b/public/docs/_examples/toh-5/ts/app/main.ts index 50c5c6ab84..ad256f0823 100644 --- a/public/docs/_examples/toh-5/ts/app/main.ts +++ b/public/docs/_examples/toh-5/ts/app/main.ts @@ -1,4 +1,5 @@ import { bootstrap } from '@angular/platform-browser-dynamic'; + import { AppComponent } from './app.component'; -bootstrap(AppComponent); \ No newline at end of file +bootstrap(AppComponent); diff --git a/public/docs/_examples/toh-5/ts/index.html b/public/docs/_examples/toh-5/ts/index.html index 0384297337..bdb039a0fc 100644 --- a/public/docs/_examples/toh-5/ts/index.html +++ b/public/docs/_examples/toh-5/ts/index.html @@ -23,7 +23,7 @@ diff --git a/public/docs/_examples/tutorial/ts/app/app.component.ts b/public/docs/_examples/tutorial/ts/app/app.component.ts index 1ef1457bd0..8b0e0ad8da 100644 --- a/public/docs/_examples/tutorial/ts/app/app.component.ts +++ b/public/docs/_examples/tutorial/ts/app/app.component.ts @@ -1,9 +1,10 @@ -import {Component} from '@angular/core'; -import {RouteConfig, ROUTER_DIRECTIVES} from '@angular/router-deprecated'; -import {HeroesComponent} from './heroes.component'; -import {HeroDetailComponent} from './hero-detail.component'; -import {DashboardComponent} from './dashboard.component'; -import {HeroService} from './hero.service'; +import { Component } from '@angular/core'; +import { RouteConfig, ROUTER_DIRECTIVES } from '@angular/router-deprecated'; + +import { HeroesComponent } from './heroes.component'; +import { HeroDetailComponent } from './hero-detail.component'; +import { DashboardComponent } from './dashboard.component'; +import { HeroService } from './hero.service'; @Component({ selector: 'my-app', diff --git a/public/docs/_examples/tutorial/ts/app/dashboard.component.ts b/public/docs/_examples/tutorial/ts/app/dashboard.component.ts index b1facbeaab..f08e40a6e1 100644 --- a/public/docs/_examples/tutorial/ts/app/dashboard.component.ts +++ b/public/docs/_examples/tutorial/ts/app/dashboard.component.ts @@ -1,7 +1,8 @@ -import {Component, OnInit} from '@angular/core'; -import {Router} from '@angular/router-deprecated'; -import {Hero} from './hero'; -import {HeroService} from './hero.service'; +import { Component, OnInit } from '@angular/core'; +import { Router } from '@angular/router-deprecated'; + +import { Hero } from './hero'; +import { HeroService } from './hero.service'; @Component({ selector: 'my-dashboard', @@ -11,10 +12,10 @@ import {HeroService} from './hero.service'; export class DashboardComponent implements OnInit { heroes: Hero[] = []; - constructor(private _heroService: HeroService, private _router: Router) { } + constructor(private heroService: HeroService, private _router: Router) { } ngOnInit() { - this._heroService.getHeroes().then(heroes => this.heroes = heroes.slice(1,5)); + this.heroService.getHeroes().then(heroes => this.heroes = heroes.slice(1,5)); } gotoDetail(hero: Hero) { diff --git a/public/docs/_examples/tutorial/ts/app/hero-detail.component.ts b/public/docs/_examples/tutorial/ts/app/hero-detail.component.ts index f326f02a8b..0a168944c0 100644 --- a/public/docs/_examples/tutorial/ts/app/hero-detail.component.ts +++ b/public/docs/_examples/tutorial/ts/app/hero-detail.component.ts @@ -1,8 +1,8 @@ -import {Component, OnInit} from '@angular/core'; -import {RouteParams} from '@angular/router-deprecated'; +import { Component, OnInit } from '@angular/core'; +import { RouteParams } from '@angular/router-deprecated'; -import {Hero} from './hero'; -import {HeroService} from './hero.service'; +import { Hero } from './hero'; +import { HeroService } from './hero.service'; @Component({ selector: 'my-hero-detail', @@ -12,13 +12,13 @@ import {HeroService} from './hero.service'; export class HeroDetailComponent implements OnInit { hero: Hero; - constructor(private _heroService: HeroService, - private _routeParams: RouteParams) { + constructor(private heroService: HeroService, + private routeParams: RouteParams) { } ngOnInit() { - let id = +this._routeParams.get('id'); - this._heroService.getHero(id).then(hero => this.hero = hero); + let id = +this.routeParams.get('id'); + this.heroService.getHero(id).then(hero => this.hero = hero); } goBack() { diff --git a/public/docs/_examples/tutorial/ts/app/hero.service.ts b/public/docs/_examples/tutorial/ts/app/hero.service.ts index bd43053ef5..7d5c08de07 100644 --- a/public/docs/_examples/tutorial/ts/app/hero.service.ts +++ b/public/docs/_examples/tutorial/ts/app/hero.service.ts @@ -1,5 +1,6 @@ -import {Injectable} from '@angular/core'; -import {HEROES} from './mock-heroes'; +import { Injectable } from '@angular/core'; + +import { HEROES } from './mock-heroes'; @Injectable() export class HeroService { diff --git a/public/docs/_examples/tutorial/ts/app/heroes.component.ts b/public/docs/_examples/tutorial/ts/app/heroes.component.ts index 222aa66e04..1081aab2bd 100644 --- a/public/docs/_examples/tutorial/ts/app/heroes.component.ts +++ b/public/docs/_examples/tutorial/ts/app/heroes.component.ts @@ -1,8 +1,8 @@ -import {Component, OnInit} from '@angular/core'; -import {Router} from '@angular/router-deprecated'; -import {HeroService} from './hero.service'; -import {HeroDetailComponent} from './hero-detail.component'; -import {Hero} from './hero'; +import { Component, OnInit } from '@angular/core'; +import { Router } from '@angular/router-deprecated'; +import { HeroService } from './hero.service'; +import { HeroDetailComponent } from './hero-detail.component'; +import { Hero } from './hero'; @Component({ selector: 'my-heroes', @@ -14,14 +14,14 @@ export class HeroesComponent implements OnInit { heroes: Hero[]; selectedHero: Hero; - constructor(private _heroService: HeroService, private _router: Router) { } + constructor(private heroService: HeroService, private router: Router) { } getHeroes() { - this._heroService.getHeroes().then(heroes => this.heroes = heroes); + this.heroService.getHeroes().then(heroes => this.heroes = heroes); } gotoDetail() { - this._router.navigate(['HeroDetail', { id: this.selectedHero.id }]); + this.router.navigate(['HeroDetail', { id: this.selectedHero.id }]); } ngOnInit() { diff --git a/public/docs/_examples/tutorial/ts/app/main.ts b/public/docs/_examples/tutorial/ts/app/main.ts index 3a351ae5b9..0e07c5e213 100644 --- a/public/docs/_examples/tutorial/ts/app/main.ts +++ b/public/docs/_examples/tutorial/ts/app/main.ts @@ -1,7 +1,8 @@ -import {bootstrap} from '@angular/platform-browser-dynamic'; -import {ROUTER_PROVIDERS} from '@angular/router-deprecated'; -import {HeroService} from './hero.service'; -import {AppComponent} from './app.component'; +import { bootstrap } from '@angular/platform-browser-dynamic'; +import { ROUTER_PROVIDERS } from '@angular/router-deprecated'; + +import { HeroService } from './hero.service'; +import { AppComponent } from './app.component'; bootstrap(AppComponent, [ ROUTER_PROVIDERS, diff --git a/public/docs/_examples/tutorial/ts/index.html b/public/docs/_examples/tutorial/ts/index.html index 98c9e72196..ede4eb68e5 100644 --- a/public/docs/_examples/tutorial/ts/index.html +++ b/public/docs/_examples/tutorial/ts/index.html @@ -16,7 +16,7 @@ diff --git a/public/docs/_examples/typings.json b/public/docs/_examples/typings.json index 9d5c20bc92..b5324f4199 100644 --- a/public/docs/_examples/typings.json +++ b/public/docs/_examples/typings.json @@ -1,6 +1,7 @@ { "ambientDependencies": { "es6-shim": "registry:dt/es6-shim#0.31.2+20160317120654", - "jasmine": "registry:dt/jasmine#2.2.0+20160412134438" + "jasmine": "registry:dt/jasmine#2.2.0+20160412134438", + "node": "registry:dt/node#4.0.0+20160509154515" } } diff --git a/public/docs/_examples/upgrade-adapter/ts/app/1-2-hybrid-bootstrap/app.module.ts b/public/docs/_examples/upgrade-adapter/ts/app/1-2-hybrid-bootstrap/app.module.ts index 36ee07d431..2e2b7b5b54 100644 --- a/public/docs/_examples/upgrade-adapter/ts/app/1-2-hybrid-bootstrap/app.module.ts +++ b/public/docs/_examples/upgrade-adapter/ts/app/1-2-hybrid-bootstrap/app.module.ts @@ -1,7 +1,7 @@ declare var angular:any; // #docregion bootstrap -import {UpgradeAdapter} from '@angular/upgrade'; +import { UpgradeAdapter } from '@angular/upgrade'; // #enddocregion bootstrap diff --git a/public/docs/_examples/upgrade-adapter/ts/app/1-2-hybrid-shared-adapter-bootstrap/app.module.ts b/public/docs/_examples/upgrade-adapter/ts/app/1-2-hybrid-shared-adapter-bootstrap/app.module.ts index 39e2e092c4..f7e1ba4b13 100644 --- a/public/docs/_examples/upgrade-adapter/ts/app/1-2-hybrid-shared-adapter-bootstrap/app.module.ts +++ b/public/docs/_examples/upgrade-adapter/ts/app/1-2-hybrid-shared-adapter-bootstrap/app.module.ts @@ -1,5 +1,5 @@ // #docregion bootstrap -import {upgradeAdapter} from './upgrade_adapter'; +import { upgradeAdapter } from './upgrade_adapter'; // #enddocregion bootstrap diff --git a/public/docs/_examples/upgrade-adapter/ts/app/1-2-hybrid-shared-adapter-bootstrap/upgrade_adapter.ts b/public/docs/_examples/upgrade-adapter/ts/app/1-2-hybrid-shared-adapter-bootstrap/upgrade_adapter.ts index 0aeb894a86..f6066f9109 100644 --- a/public/docs/_examples/upgrade-adapter/ts/app/1-2-hybrid-shared-adapter-bootstrap/upgrade_adapter.ts +++ b/public/docs/_examples/upgrade-adapter/ts/app/1-2-hybrid-shared-adapter-bootstrap/upgrade_adapter.ts @@ -1,3 +1,3 @@ // #docregion -import {UpgradeAdapter} from '@angular/upgrade'; +import { UpgradeAdapter } from '@angular/upgrade'; export const upgradeAdapter = new UpgradeAdapter(); diff --git a/public/docs/_examples/upgrade-adapter/ts/app/1-to-2-projection/app.module.ts b/public/docs/_examples/upgrade-adapter/ts/app/1-to-2-projection/app.module.ts index 60dfe96d3e..2534ebd99a 100644 --- a/public/docs/_examples/upgrade-adapter/ts/app/1-to-2-projection/app.module.ts +++ b/public/docs/_examples/upgrade-adapter/ts/app/1-to-2-projection/app.module.ts @@ -1,6 +1,7 @@ -import {UpgradeAdapter} from '@angular/upgrade'; -import {MainController} from './main.controller'; -import {HeroDetailComponent} from './hero-detail.component'; +import { UpgradeAdapter } from '@angular/upgrade'; + +import { MainController } from './main.controller'; +import { HeroDetailComponent } from './hero-detail.component'; declare var angular:any; const upgradeAdapter = new UpgradeAdapter(); diff --git a/public/docs/_examples/upgrade-adapter/ts/app/1-to-2-projection/hero-detail.component.ts b/public/docs/_examples/upgrade-adapter/ts/app/1-to-2-projection/hero-detail.component.ts index e6656eb4d9..7a2956eb26 100644 --- a/public/docs/_examples/upgrade-adapter/ts/app/1-to-2-projection/hero-detail.component.ts +++ b/public/docs/_examples/upgrade-adapter/ts/app/1-to-2-projection/hero-detail.component.ts @@ -1,6 +1,6 @@ // #docregion -import {Component, Input} from '@angular/core'; -import {Hero} from '../hero'; +import { Component, Input } from '@angular/core'; +import { Hero } from '../hero'; @Component({ selector: 'hero-detail', diff --git a/public/docs/_examples/upgrade-adapter/ts/app/1-to-2-projection/main.controller.ts b/public/docs/_examples/upgrade-adapter/ts/app/1-to-2-projection/main.controller.ts index e4754e710d..a47d561b1b 100644 --- a/public/docs/_examples/upgrade-adapter/ts/app/1-to-2-projection/main.controller.ts +++ b/public/docs/_examples/upgrade-adapter/ts/app/1-to-2-projection/main.controller.ts @@ -1,4 +1,4 @@ -import {Hero} from '../Hero'; +import { Hero } from '../Hero'; export class MainController { hero = new Hero(1, 'Windstorm', 'Specific powers of controlling winds'); diff --git a/public/docs/_examples/upgrade-adapter/ts/app/1-to-2-providers/app.module.ts b/public/docs/_examples/upgrade-adapter/ts/app/1-to-2-providers/app.module.ts index 2d04886a8a..feba407bce 100644 --- a/public/docs/_examples/upgrade-adapter/ts/app/1-to-2-providers/app.module.ts +++ b/public/docs/_examples/upgrade-adapter/ts/app/1-to-2-providers/app.module.ts @@ -1,6 +1,6 @@ -import {HeroDetailComponent} from './hero-detail.component'; -import {HeroesService} from './heroes.service'; -import {upgradeAdapter} from './upgrade_adapter'; +import { HeroDetailComponent } from './hero-detail.component'; +import { HeroesService } from './heroes.service'; +import { upgradeAdapter } from './upgrade_adapter'; declare var angular:any; diff --git a/public/docs/_examples/upgrade-adapter/ts/app/1-to-2-providers/hero-detail.component.ts b/public/docs/_examples/upgrade-adapter/ts/app/1-to-2-providers/hero-detail.component.ts index 3fb05f97f2..fa1c26a9fa 100644 --- a/public/docs/_examples/upgrade-adapter/ts/app/1-to-2-providers/hero-detail.component.ts +++ b/public/docs/_examples/upgrade-adapter/ts/app/1-to-2-providers/hero-detail.component.ts @@ -1,7 +1,7 @@ // #docregion -import {Component, Inject} from '@angular/core'; -import {HeroesService} from './heroes.service'; -import {Hero} from '../hero'; +import { Component, Inject } from '@angular/core'; +import { HeroesService } from './heroes.service'; +import { Hero } from '../hero'; @Component({ selector: 'hero-detail', diff --git a/public/docs/_examples/upgrade-adapter/ts/app/1-to-2-providers/heroes.service.ts b/public/docs/_examples/upgrade-adapter/ts/app/1-to-2-providers/heroes.service.ts index 416d1af639..4a258e205a 100644 --- a/public/docs/_examples/upgrade-adapter/ts/app/1-to-2-providers/heroes.service.ts +++ b/public/docs/_examples/upgrade-adapter/ts/app/1-to-2-providers/heroes.service.ts @@ -1,5 +1,5 @@ // #docregion -import {Hero} from '../hero'; +import { Hero } from '../hero'; export class HeroesService { get() { diff --git a/public/docs/_examples/upgrade-adapter/ts/app/1-to-2-providers/upgrade_adapter.ts b/public/docs/_examples/upgrade-adapter/ts/app/1-to-2-providers/upgrade_adapter.ts index 0aeb894a86..f6066f9109 100644 --- a/public/docs/_examples/upgrade-adapter/ts/app/1-to-2-providers/upgrade_adapter.ts +++ b/public/docs/_examples/upgrade-adapter/ts/app/1-to-2-providers/upgrade_adapter.ts @@ -1,3 +1,3 @@ // #docregion -import {UpgradeAdapter} from '@angular/upgrade'; +import { UpgradeAdapter } from '@angular/upgrade'; export const upgradeAdapter = new UpgradeAdapter(); diff --git a/public/docs/_examples/upgrade-adapter/ts/app/2-to-1-providers/app.module.ts b/public/docs/_examples/upgrade-adapter/ts/app/2-to-1-providers/app.module.ts index 43a7fcf250..657c4d25cc 100644 --- a/public/docs/_examples/upgrade-adapter/ts/app/2-to-1-providers/app.module.ts +++ b/public/docs/_examples/upgrade-adapter/ts/app/2-to-1-providers/app.module.ts @@ -1,6 +1,6 @@ -import {heroDetailComponent} from './hero-detail.component'; -import {Heroes} from './heroes'; -import {upgradeAdapter} from './upgrade_adapter'; +import { heroDetailComponent } from './hero-detail.component'; +import { Heroes } from './heroes'; +import { upgradeAdapter } from './upgrade_adapter'; declare var angular:any; diff --git a/public/docs/_examples/upgrade-adapter/ts/app/2-to-1-providers/hero-detail.component.ts b/public/docs/_examples/upgrade-adapter/ts/app/2-to-1-providers/hero-detail.component.ts index 36bb5368aa..d736117ce0 100644 --- a/public/docs/_examples/upgrade-adapter/ts/app/2-to-1-providers/hero-detail.component.ts +++ b/public/docs/_examples/upgrade-adapter/ts/app/2-to-1-providers/hero-detail.component.ts @@ -1,4 +1,4 @@ -import {Heroes} from './heroes'; +import { Heroes } from './heroes'; // #docregion export const heroDetailComponent = { diff --git a/public/docs/_examples/upgrade-adapter/ts/app/2-to-1-providers/heroes.ts b/public/docs/_examples/upgrade-adapter/ts/app/2-to-1-providers/heroes.ts index 157436ed54..f5f6d87ed8 100644 --- a/public/docs/_examples/upgrade-adapter/ts/app/2-to-1-providers/heroes.ts +++ b/public/docs/_examples/upgrade-adapter/ts/app/2-to-1-providers/heroes.ts @@ -1,6 +1,6 @@ // #docregion -import {Injectable} from '@angular/core'; -import {Hero} from '../hero'; +import { Injectable } from '@angular/core'; +import { Hero } from '../hero'; @Injectable() export class Heroes { diff --git a/public/docs/_examples/upgrade-adapter/ts/app/2-to-1-providers/upgrade_adapter.ts b/public/docs/_examples/upgrade-adapter/ts/app/2-to-1-providers/upgrade_adapter.ts index 0aeb894a86..f6066f9109 100644 --- a/public/docs/_examples/upgrade-adapter/ts/app/2-to-1-providers/upgrade_adapter.ts +++ b/public/docs/_examples/upgrade-adapter/ts/app/2-to-1-providers/upgrade_adapter.ts @@ -1,3 +1,3 @@ // #docregion -import {UpgradeAdapter} from '@angular/upgrade'; +import { UpgradeAdapter } from '@angular/upgrade'; export const upgradeAdapter = new UpgradeAdapter(); diff --git a/public/docs/_examples/upgrade-adapter/ts/app/2-to-1-transclusion/app.module.ts b/public/docs/_examples/upgrade-adapter/ts/app/2-to-1-transclusion/app.module.ts index 0b36fe1379..ab16d3a24d 100644 --- a/public/docs/_examples/upgrade-adapter/ts/app/2-to-1-transclusion/app.module.ts +++ b/public/docs/_examples/upgrade-adapter/ts/app/2-to-1-transclusion/app.module.ts @@ -1,7 +1,7 @@ -import {UpgradeAdapter} from '@angular/upgrade'; -import {ContainerComponent} from './container.component'; -import {heroDetailComponent} from './hero-detail.component'; -import {upgradeAdapter} from './upgrade_adapter'; +import { UpgradeAdapter } from '@angular/upgrade'; +import { ContainerComponent } from './container.component'; +import { heroDetailComponent } from './hero-detail.component'; +import { upgradeAdapter } from './upgrade_adapter'; declare var angular:any; diff --git a/public/docs/_examples/upgrade-adapter/ts/app/2-to-1-transclusion/container.component.ts b/public/docs/_examples/upgrade-adapter/ts/app/2-to-1-transclusion/container.component.ts index 387e5d9c0d..fabb595405 100644 --- a/public/docs/_examples/upgrade-adapter/ts/app/2-to-1-transclusion/container.component.ts +++ b/public/docs/_examples/upgrade-adapter/ts/app/2-to-1-transclusion/container.component.ts @@ -1,7 +1,7 @@ // #docregion -import {Component} from '@angular/core'; -import {upgradeAdapter} from './upgrade_adapter'; -import {Hero} from '../Hero'; +import { Component } from '@angular/core'; +import { upgradeAdapter } from './upgrade_adapter'; +import { Hero } from '../Hero'; const HeroDetail = upgradeAdapter.upgradeNg1Component('heroDetail'); diff --git a/public/docs/_examples/upgrade-adapter/ts/app/2-to-1-transclusion/upgrade_adapter.ts b/public/docs/_examples/upgrade-adapter/ts/app/2-to-1-transclusion/upgrade_adapter.ts index 0aeb894a86..f6066f9109 100644 --- a/public/docs/_examples/upgrade-adapter/ts/app/2-to-1-transclusion/upgrade_adapter.ts +++ b/public/docs/_examples/upgrade-adapter/ts/app/2-to-1-transclusion/upgrade_adapter.ts @@ -1,3 +1,3 @@ // #docregion -import {UpgradeAdapter} from '@angular/upgrade'; +import { UpgradeAdapter } from '@angular/upgrade'; export const upgradeAdapter = new UpgradeAdapter(); diff --git a/public/docs/_examples/upgrade-adapter/ts/app/downgrade-io/app.module.ts b/public/docs/_examples/upgrade-adapter/ts/app/downgrade-io/app.module.ts index b6246b871e..d9af4e0104 100644 --- a/public/docs/_examples/upgrade-adapter/ts/app/downgrade-io/app.module.ts +++ b/public/docs/_examples/upgrade-adapter/ts/app/downgrade-io/app.module.ts @@ -1,9 +1,9 @@ -import {MainController} from './main.controller'; +import { MainController } from './main.controller'; // #docregion downgradecomponent -import {HeroDetailComponent} from './hero-detail.component'; +import { HeroDetailComponent } from './hero-detail.component'; // #enddocregion downgradecomponent -import {UpgradeAdapter} from '@angular/upgrade'; +import { UpgradeAdapter } from '@angular/upgrade'; const upgradeAdapter = new UpgradeAdapter(); diff --git a/public/docs/_examples/upgrade-adapter/ts/app/downgrade-io/hero-detail.component.ts b/public/docs/_examples/upgrade-adapter/ts/app/downgrade-io/hero-detail.component.ts index eeb367e3af..12879ac980 100644 --- a/public/docs/_examples/upgrade-adapter/ts/app/downgrade-io/hero-detail.component.ts +++ b/public/docs/_examples/upgrade-adapter/ts/app/downgrade-io/hero-detail.component.ts @@ -1,5 +1,5 @@ // #docregion -import {Component, Input, Output, EventEmitter} from '@angular/core'; +import { Component, EventEmitter, Input, Output } from '@angular/core'; import {Hero} from '../hero'; @Component({ diff --git a/public/docs/_examples/upgrade-adapter/ts/app/downgrade-io/main.controller.ts b/public/docs/_examples/upgrade-adapter/ts/app/downgrade-io/main.controller.ts index a43140429e..2bf72de681 100644 --- a/public/docs/_examples/upgrade-adapter/ts/app/downgrade-io/main.controller.ts +++ b/public/docs/_examples/upgrade-adapter/ts/app/downgrade-io/main.controller.ts @@ -1,4 +1,4 @@ -import {Hero} from '../Hero'; +import { Hero } from '../Hero'; export class MainController { hero = new Hero(1, 'Windstorm'); diff --git a/public/docs/_examples/upgrade-adapter/ts/app/downgrade-static/app.module.ts b/public/docs/_examples/upgrade-adapter/ts/app/downgrade-static/app.module.ts index fc4ed4a2f0..44935340f0 100644 --- a/public/docs/_examples/upgrade-adapter/ts/app/downgrade-static/app.module.ts +++ b/public/docs/_examples/upgrade-adapter/ts/app/downgrade-static/app.module.ts @@ -1,8 +1,8 @@ // #docregion downgradecomponent -import {HeroDetailComponent} from './hero-detail.component'; +import { HeroDetailComponent } from './hero-detail.component'; // #enddocregion downgradecomponent -import {UpgradeAdapter} from '@angular/upgrade'; +import { UpgradeAdapter } from '@angular/upgrade'; const upgradeAdapter = new UpgradeAdapter(); diff --git a/public/docs/_examples/upgrade-adapter/ts/app/downgrade-static/hero-detail.component.ts b/public/docs/_examples/upgrade-adapter/ts/app/downgrade-static/hero-detail.component.ts index 297d4d9669..cbcadfbd5a 100644 --- a/public/docs/_examples/upgrade-adapter/ts/app/downgrade-static/hero-detail.component.ts +++ b/public/docs/_examples/upgrade-adapter/ts/app/downgrade-static/hero-detail.component.ts @@ -1,5 +1,5 @@ // #docregion -import {Component} from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'hero-detail', diff --git a/public/docs/_examples/upgrade-adapter/ts/app/upgrade-io/app.module.ts b/public/docs/_examples/upgrade-adapter/ts/app/upgrade-io/app.module.ts index 5599ea67f0..dd2df20bdf 100644 --- a/public/docs/_examples/upgrade-adapter/ts/app/upgrade-io/app.module.ts +++ b/public/docs/_examples/upgrade-adapter/ts/app/upgrade-io/app.module.ts @@ -1,6 +1,6 @@ -import {heroDetail} from './hero-detail.component'; -import {ContainerComponent} from './container.component'; -import {upgradeAdapter} from './upgrade_adapter'; +import { heroDetail } from './hero-detail.component'; +import { ContainerComponent } from './container.component'; +import { upgradeAdapter } from './upgrade_adapter'; declare var angular:any; diff --git a/public/docs/_examples/upgrade-adapter/ts/app/upgrade-io/container.component.ts b/public/docs/_examples/upgrade-adapter/ts/app/upgrade-io/container.component.ts index 01844b7727..c13857c7c5 100644 --- a/public/docs/_examples/upgrade-adapter/ts/app/upgrade-io/container.component.ts +++ b/public/docs/_examples/upgrade-adapter/ts/app/upgrade-io/container.component.ts @@ -1,7 +1,7 @@ // #docregion -import {Component} from '@angular/core'; -import {upgradeAdapter} from './upgrade_adapter'; -import {Hero} from '../Hero'; +import { Component } from '@angular/core'; +import { upgradeAdapter } from './upgrade_adapter'; +import { Hero } from '../Hero'; const HeroDetail = upgradeAdapter.upgradeNg1Component('heroDetail'); diff --git a/public/docs/_examples/upgrade-adapter/ts/app/upgrade-io/upgrade_adapter.ts b/public/docs/_examples/upgrade-adapter/ts/app/upgrade-io/upgrade_adapter.ts index 0aeb894a86..f6066f9109 100644 --- a/public/docs/_examples/upgrade-adapter/ts/app/upgrade-io/upgrade_adapter.ts +++ b/public/docs/_examples/upgrade-adapter/ts/app/upgrade-io/upgrade_adapter.ts @@ -1,3 +1,3 @@ // #docregion -import {UpgradeAdapter} from '@angular/upgrade'; +import { UpgradeAdapter } from '@angular/upgrade'; export const upgradeAdapter = new UpgradeAdapter(); diff --git a/public/docs/_examples/upgrade-adapter/ts/app/upgrade-static/app.module.ts b/public/docs/_examples/upgrade-adapter/ts/app/upgrade-static/app.module.ts index 5599ea67f0..dd2df20bdf 100644 --- a/public/docs/_examples/upgrade-adapter/ts/app/upgrade-static/app.module.ts +++ b/public/docs/_examples/upgrade-adapter/ts/app/upgrade-static/app.module.ts @@ -1,6 +1,6 @@ -import {heroDetail} from './hero-detail.component'; -import {ContainerComponent} from './container.component'; -import {upgradeAdapter} from './upgrade_adapter'; +import { heroDetail } from './hero-detail.component'; +import { ContainerComponent } from './container.component'; +import { upgradeAdapter } from './upgrade_adapter'; declare var angular:any; diff --git a/public/docs/_examples/upgrade-adapter/ts/app/upgrade-static/container.component.ts b/public/docs/_examples/upgrade-adapter/ts/app/upgrade-static/container.component.ts index be52f7aeb8..ca8a93dd26 100644 --- a/public/docs/_examples/upgrade-adapter/ts/app/upgrade-static/container.component.ts +++ b/public/docs/_examples/upgrade-adapter/ts/app/upgrade-static/container.component.ts @@ -1,6 +1,6 @@ // #docregion -import {Component} from '@angular/core'; -import {upgradeAdapter} from './upgrade_adapter'; +import { Component } from '@angular/core'; +import { upgradeAdapter } from './upgrade_adapter'; const HeroDetail = upgradeAdapter.upgradeNg1Component('heroDetail'); diff --git a/public/docs/_examples/upgrade-adapter/ts/app/upgrade-static/upgrade_adapter.ts b/public/docs/_examples/upgrade-adapter/ts/app/upgrade-static/upgrade_adapter.ts index 0aeb894a86..f6066f9109 100644 --- a/public/docs/_examples/upgrade-adapter/ts/app/upgrade-static/upgrade_adapter.ts +++ b/public/docs/_examples/upgrade-adapter/ts/app/upgrade-static/upgrade_adapter.ts @@ -1,3 +1,3 @@ // #docregion -import {UpgradeAdapter} from '@angular/upgrade'; +import { UpgradeAdapter } from '@angular/upgrade'; export const upgradeAdapter = new UpgradeAdapter(); diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/app.module.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/app.module.ts index 07fce56e81..3718b9250f 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/app.module.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/app.module.ts @@ -1,11 +1,11 @@ // #docregion adapter-import -import {UpgradeAdapter} from '@angular/upgrade'; +import { UpgradeAdapter } from '@angular/upgrade'; // #enddocregion adapter-import // #docregion adapter-state-import import upgradeAdapter from './core/upgrade_adapter'; // #enddocregion adapter-state-import // #docregion http-import -import {HTTP_PROVIDERS} from '@angular/http'; +import { HTTP_PROVIDERS } from '@angular/http'; // #enddocregion http-import import core from './core/core.module'; import phoneList from './phone_list/phone_list.module'; diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/core/checkmark.pipe.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/core/checkmark.pipe.ts index 135f78b02d..d129a44e50 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/core/checkmark.pipe.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/core/checkmark.pipe.ts @@ -1,5 +1,5 @@ // #docregion -import {Pipe} from '@angular/core'; +import { Pipe } from '@angular/core'; @Pipe({name: 'checkmark'}) export class CheckmarkPipe { diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/core/core.module.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/core/core.module.ts index 5d80850593..c3e1ba514b 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/core/core.module.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/core/core.module.ts @@ -1,5 +1,5 @@ // #docregion -import {Phones} from './phones.service'; +import { Phones } from './phones.service'; import upgradeAdapter from './upgrade_adapter'; upgradeAdapter.addProvider(Phones); diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/core/phones.service.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/core/phones.service.ts index c9f2cb6408..d292bc54ee 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/core/phones.service.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/core/phones.service.ts @@ -1,7 +1,7 @@ // #docregion full -import {Injectable} from '@angular/core'; -import {Http, Response} from '@angular/http'; -import {Observable} from 'rxjs/Rx'; +import { Injectable } from '@angular/core'; +import { Http, Response } from '@angular/http'; +import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; // #docregion phone-interface diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/core/upgrade_adapter.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/core/upgrade_adapter.ts index c5d20edd7a..f1ad63012a 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/core/upgrade_adapter.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/core/upgrade_adapter.ts @@ -1,5 +1,5 @@ // #docregion full -import {UpgradeAdapter} from '@angular/upgrade'; +import { UpgradeAdapter } from '@angular/upgrade'; // #docregion adapter-init const upgradeAdapter = new UpgradeAdapter(); diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/phone_detail/phone_detail.component.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/phone_detail/phone_detail.component.ts index 4e645336a2..dc6c1ff4fd 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/phone_detail/phone_detail.component.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/phone_detail/phone_detail.component.ts @@ -1,8 +1,8 @@ // #docregion // #docregion top -import {Component, Inject} from '@angular/core'; -import {Phones, Phone} from '../core/phones.service'; -import {CheckmarkPipe} from '../core/checkmark.pipe'; +import { Component, Inject } from '@angular/core'; +import { Phones, Phone } from '../core/phones.service'; +import { CheckmarkPipe } from '../core/checkmark.pipe'; interface PhoneRouteParams { phoneId: string diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/phone_detail/phone_detail_without_pipes.component.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/phone_detail/phone_detail_without_pipes.component.ts index a743d115bd..0926ffeb84 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/phone_detail/phone_detail_without_pipes.component.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/phone_detail/phone_detail_without_pipes.component.ts @@ -1,6 +1,6 @@ // #docregion -import {Component, Inject} from '@angular/core'; -import {Phones, Phone} from '../core/phones.service'; +import { Component, Inject } from '@angular/core'; +import { Phone, Phones } from '../core/phones.service'; interface PhoneRouteParams { phoneId: string diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/phone_list/order_by.pipe.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/phone_list/order_by.pipe.ts index 89c239a999..162b91cf60 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/phone_list/order_by.pipe.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/phone_list/order_by.pipe.ts @@ -1,5 +1,5 @@ // #docregion -import {Pipe} from '@angular/core'; +import { Pipe } from '@angular/core'; @Pipe({name: 'orderBy'}) export default class OrderByPipe { diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/phone_list/phone_filter.pipe.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/phone_list/phone_filter.pipe.ts index de5040df01..9f38608e8f 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/phone_list/phone_filter.pipe.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/phone_list/phone_filter.pipe.ts @@ -1,6 +1,6 @@ // #docregion -import {Pipe} from '@angular/core'; -import {Phone} from '../core/phones.service'; +import { Pipe } from '@angular/core'; +import { Phone } from '../core/phones.service'; @Pipe({name: 'phoneFilter'}) export default class PhoneFilterPipe { diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/phone_list/phone_list.component.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/phone_list/phone_list.component.ts index 098783b487..d876e28861 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/phone_list/phone_list.component.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/phone_list/phone_list.component.ts @@ -1,8 +1,8 @@ // #docregion full // #docregion top -import {Component} from '@angular/core'; -import {Observable} from 'rxjs'; -import {Phones, Phone} from '../core/phones.service'; +import { Component } from '@angular/core'; +import { Observable } from 'rxjs'; +import { Phones, Phone } from '../core/phones.service'; import PhoneFilterPipe from './phone_filter.pipe'; import OrderByPipe from './order_by.pipe'; diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/phone_list/phone_list_without_pipes.component.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/phone_list/phone_list_without_pipes.component.ts index cd54e48e8a..d967ce464e 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/phone_list/phone_list_without_pipes.component.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/js/phone_list/phone_list_without_pipes.component.ts @@ -1,7 +1,7 @@ // #docregion top -import {Component} from '@angular/core'; -import {Observable} from 'rxjs'; -import {Phones, Phone} from '../core/phones.service'; +import { Component } from '@angular/core'; +import { Observable } from 'rxjs'; +import { Phone, Phones } from '../core/phones.service'; @Component({ selector: 'pc-phone-list', diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/systemjs.config.js b/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/systemjs.config.js index b7b216914c..d7510ce7c6 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/systemjs.config.js +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_components/app/systemjs.config.js @@ -17,6 +17,7 @@ System.config({ '@angular/platform-browser': { main: 'index.js', defaultExtension: 'js' }, '@angular/platform-browser-dynamic': { main: 'index.js', defaultExtension: 'js' }, '@angular/router': { main: 'index.js', defaultExtension: 'js' }, + '@angular/router-deprecated': { main: 'index.js', defaultExtension: 'js' }, '@angular/upgrade': { main: 'index.js', defaultExtension: 'js' }, 'rxjs': { defaultExtension: 'js' } diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_components/package.1.json b/public/docs/_examples/upgrade-phonecat/ts/ng2_components/package.1.json index 425ad7b82f..501da397e3 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_components/package.1.json +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_components/package.1.json @@ -6,14 +6,15 @@ "repository": "https://github.com/angular/angular-phonecat", "license": "MIT", "dependencies": { - "@angular/common": "0.0.0-3", - "@angular/compiler": "0.0.0-3", - "@angular/core": "0.0.0-3", - "@angular/http": "0.0.0-3", - "@angular/platform-browser": "0.0.0-3", - "@angular/platform-browser-dynamic": "0.0.0-3", - "@angular/router": "0.0.0-3", - "@angular/upgrade": "0.0.0-3", + "@angular/common": "2.0.0-rc.1", + "@angular/compiler": "2.0.0-rc.1", + "@angular/core": "2.0.0-rc.1", + "@angular/http": "2.0.0-rc.1", + "@angular/platform-browser": "2.0.0-rc.1", + "@angular/platform-browser-dynamic": "2.0.0-rc.1", + "@angular/router": "2.0.0-rc.1", + "@angular/router-deprecated": "2.0.0-rc.1", + "@angular/upgrade": "2.0.0-rc.1", "es6-shim": "^0.35.0", "reflect-metadata": "0.1.3", diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_components/test/karma_test_shim.js b/public/docs/_examples/upgrade-phonecat/ts/ng2_components/test/karma_test_shim.js index 7aa6c9ec90..26075e973d 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_components/test/karma_test_shim.js +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_components/test/karma_test_shim.js @@ -29,6 +29,7 @@ System.config({ '@angular/platform-browser': { main: 'index.js', defaultExtension: 'js' }, '@angular/platform-browser-dynamic': { main: 'index.js', defaultExtension: 'js' }, '@angular/router': { main: 'index.js', defaultExtension: 'js' }, + '@angular/router-deprecated': { main: 'index.js', defaultExtension: 'js' }, '@angular/upgrade': { main: 'index.js', defaultExtension: 'js' }, 'rxjs': { defaultExtension: 'js' } } @@ -37,8 +38,8 @@ System.config({ // #docregion ng2 System.import('@angular/core/testing').then(function(testing) { return System.import('@angular/platform-browser-dynamic/testing').then(function(browserTesting) { - testing.setBaseTestProviders(browserTesting.TEST_BROWSER_PLATFORM_PROVIDERS, - browserTesting.TEST_BROWSER_APPLICATION_PROVIDERS); + testing.setBaseTestProviders(browserTesting.TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS, + browserTesting.TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS); }); }).then(function() { return Promise.all( diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/app.component.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/app.component.ts index dafa140aae..f572854fc0 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/app.component.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/app.component.ts @@ -1,6 +1,7 @@ // #docregion -import {Component} from '@angular/core'; -import {RouteConfig, ROUTER_DIRECTIVES} from '@angular/router'; +import { Component } from '@angular/core'; +import { RouteConfig, ROUTER_DIRECTIVES } from '@angular/router-deprecated'; + import PhoneList from './phone_list/phone_list.component'; import PhoneDetail from './phone_detail/phone_detail.component'; diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/core/checkmark.pipe.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/core/checkmark.pipe.ts index 135f78b02d..d129a44e50 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/core/checkmark.pipe.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/core/checkmark.pipe.ts @@ -1,5 +1,5 @@ // #docregion -import {Pipe} from '@angular/core'; +import { Pipe } from '@angular/core'; @Pipe({name: 'checkmark'}) export class CheckmarkPipe { diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/core/phones.service.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/core/phones.service.ts index c9f2cb6408..d292bc54ee 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/core/phones.service.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/core/phones.service.ts @@ -1,7 +1,7 @@ // #docregion full -import {Injectable} from '@angular/core'; -import {Http, Response} from '@angular/http'; -import {Observable} from 'rxjs/Rx'; +import { Injectable } from '@angular/core'; +import { Http, Response } from '@angular/http'; +import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; // #docregion phone-interface diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/core/upgrade_adapter.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/core/upgrade_adapter.ts index c5d20edd7a..f1ad63012a 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/core/upgrade_adapter.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/core/upgrade_adapter.ts @@ -1,5 +1,5 @@ // #docregion full -import {UpgradeAdapter} from '@angular/upgrade'; +import { UpgradeAdapter } from '@angular/upgrade'; // #docregion adapter-init const upgradeAdapter = new UpgradeAdapter(); diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/main.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/main.ts index 210e280884..40ccfa0aac 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/main.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/main.ts @@ -1,16 +1,16 @@ // #docregion // #docregion importbootstrap -import {provide} from '@angular/core'; -import {LocationStrategy, HashLocationStrategy} from '@angular/common'; -import {bootstrap} from '@angular/platform-browser-dynamic'; -import {ROUTER_PROVIDERS} from '@angular/router'; +import { provide } from '@angular/core'; +import { LocationStrategy, HashLocationStrategy } from '@angular/common'; +import { bootstrap } from '@angular/platform-browser-dynamic'; +import { ROUTER_PROVIDERS } from '@angular/router-deprecated'; -import {Phones} from './core/phones.service'; +import { Phones } from './core/phones.service'; import AppComponent from './app.component'; // #enddocregion importbootstrap // #docregion http-import -import {HTTP_PROVIDERS} from '@angular/http'; +import { HTTP_PROVIDERS } from '@angular/http'; // #enddocregion http-import // #docregion bootstrap diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/phone_detail/phone_detail.component.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/phone_detail/phone_detail.component.ts index 4d1b28ab5f..a6d07f3773 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/phone_detail/phone_detail.component.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/phone_detail/phone_detail.component.ts @@ -1,9 +1,10 @@ // #docregion // #docregion top -import {Component, Inject} from '@angular/core'; -import {RouteParams} from '@angular/router'; -import {Phones, Phone} from '../core/phones.service'; -import {CheckmarkPipe} from '../core/checkmark.pipe'; +import { Component, Inject } from '@angular/core'; +import { RouteParams } from '@angular/router-deprecated'; + +import { Phones, Phone } from '../core/phones.service'; +import { CheckmarkPipe } from '../core/checkmark.pipe'; @Component({ selector: 'pc-phone-detail', diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/phone_list/order_by.pipe.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/phone_list/order_by.pipe.ts index 89c239a999..162b91cf60 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/phone_list/order_by.pipe.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/phone_list/order_by.pipe.ts @@ -1,5 +1,5 @@ // #docregion -import {Pipe} from '@angular/core'; +import { Pipe } from '@angular/core'; @Pipe({name: 'orderBy'}) export default class OrderByPipe { diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/phone_list/phone_filter.pipe.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/phone_list/phone_filter.pipe.ts index de5040df01..9f38608e8f 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/phone_list/phone_filter.pipe.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/phone_list/phone_filter.pipe.ts @@ -1,6 +1,6 @@ // #docregion -import {Pipe} from '@angular/core'; -import {Phone} from '../core/phones.service'; +import { Pipe } from '@angular/core'; +import { Phone } from '../core/phones.service'; @Pipe({name: 'phoneFilter'}) export default class PhoneFilterPipe { diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/phone_list/phone_list.component.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/phone_list/phone_list.component.ts index ca240414e2..f87aa62efc 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/phone_list/phone_list.component.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/js/phone_list/phone_list.component.ts @@ -1,9 +1,10 @@ // #docregion full // #docregion top -import {Component} from '@angular/core'; -import {RouterLink} from '@angular/router'; -import {Observable} from 'rxjs'; -import {Phones, Phone} from '../core/phones.service'; +import { Component } from '@angular/core'; +import { RouterLink } from '@angular/router-deprecated'; +import { Observable } from 'rxjs'; + +import { Phones, Phone } from '../core/phones.service'; import PhoneFilterPipe from './phone_filter.pipe'; import OrderByPipe from './order_by.pipe'; diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/systemjs.config.js b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/systemjs.config.js index b7b216914c..d7510ce7c6 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/systemjs.config.js +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/app/systemjs.config.js @@ -17,6 +17,7 @@ System.config({ '@angular/platform-browser': { main: 'index.js', defaultExtension: 'js' }, '@angular/platform-browser-dynamic': { main: 'index.js', defaultExtension: 'js' }, '@angular/router': { main: 'index.js', defaultExtension: 'js' }, + '@angular/router-deprecated': { main: 'index.js', defaultExtension: 'js' }, '@angular/upgrade': { main: 'index.js', defaultExtension: 'js' }, 'rxjs': { defaultExtension: 'js' } diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/package.1.json b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/package.1.json index e8f21a01ce..0f07a065d2 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/package.1.json +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/package.1.json @@ -6,14 +6,15 @@ "repository": "https://github.com/angular/angular-phonecat", "license": "MIT", "dependencies": { - "@angular/common": "0.0.0-3", - "@angular/compiler": "0.0.0-3", - "@angular/core": "0.0.0-3", - "@angular/http": "0.0.0-3", - "@angular/platform-browser": "0.0.0-3", - "@angular/platform-browser-dynamic": "0.0.0-3", - "@angular/router": "0.0.0-3", - "@angular/upgrade": "0.0.0-3", + "@angular/common": "2.0.0-rc.1", + "@angular/compiler": "2.0.0-rc.1", + "@angular/core": "2.0.0-rc.1", + "@angular/http": "2.0.0-rc.1", + "@angular/platform-browser": "2.0.0-rc.1", + "@angular/platform-browser-dynamic": "2.0.0-rc.1", + "@angular/router": "2.0.0-rc.1", + "@angular/router-deprecated": "2.0.0-rc.1", + "@angular/upgrade": "2.0.0-rc.1", "es6-shim": "^0.35.0", "reflect-metadata": "0.1.3", diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/test/karma_test_shim.js b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/test/karma_test_shim.js index 7aa6c9ec90..26075e973d 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/test/karma_test_shim.js +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/test/karma_test_shim.js @@ -29,6 +29,7 @@ System.config({ '@angular/platform-browser': { main: 'index.js', defaultExtension: 'js' }, '@angular/platform-browser-dynamic': { main: 'index.js', defaultExtension: 'js' }, '@angular/router': { main: 'index.js', defaultExtension: 'js' }, + '@angular/router-deprecated': { main: 'index.js', defaultExtension: 'js' }, '@angular/upgrade': { main: 'index.js', defaultExtension: 'js' }, 'rxjs': { defaultExtension: 'js' } } @@ -37,8 +38,8 @@ System.config({ // #docregion ng2 System.import('@angular/core/testing').then(function(testing) { return System.import('@angular/platform-browser-dynamic/testing').then(function(browserTesting) { - testing.setBaseTestProviders(browserTesting.TEST_BROWSER_PLATFORM_PROVIDERS, - browserTesting.TEST_BROWSER_APPLICATION_PROVIDERS); + testing.setBaseTestProviders(browserTesting.TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS, + browserTesting.TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS); }); }).then(function() { return Promise.all( diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/test/unit/checkmark.pipe.spec.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/test/unit/checkmark.pipe.spec.ts index 5a5b2284c2..c9a1def071 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/test/unit/checkmark.pipe.spec.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/test/unit/checkmark.pipe.spec.ts @@ -1,6 +1,7 @@ // #docregion -import {describe, beforeEachProviders, it, inject, expect} from '@angular/core/testing'; -import {CheckmarkPipe} from '../../app/js/core/checkmark.pipe'; +import { describe, beforeEachProviders, it, inject, expect } from '@angular/core/testing'; + +import { CheckmarkPipe } from '../../app/js/core/checkmark.pipe'; describe('CheckmarkPipe', () => { diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/test/unit/order_by.pipe.spec.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/test/unit/order_by.pipe.spec.ts index 09e0fbb1bf..416ca0797b 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/test/unit/order_by.pipe.spec.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/test/unit/order_by.pipe.spec.ts @@ -1,5 +1,5 @@ // #docregion -import {describe, beforeEachProviders, it, inject} from '@angular/core/testing'; +import { describe, beforeEachProviders, it, inject } from '@angular/core/testing'; import OrderByPipe from '../../app/js/phone_list/order_by.pipe'; diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/test/unit/phone_detail.component.spec.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/test/unit/phone_detail.component.spec.ts index b1b86ec4c1..c8751add62 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/test/unit/phone_detail.component.spec.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/test/unit/phone_detail.component.spec.ts @@ -1,9 +1,9 @@ -import {provide} from '@angular/core'; +import { provide } from '@angular/core'; // #docregion routeparams -import {RouteParams} from '@angular/router'; +import { RouteParams } from '@angular/router-deprecated'; // #enddocregion routeparams -import {HTTP_PROVIDERS} from '@angular/http'; -import {Observable} from 'rxjs/Rx'; +import { HTTP_PROVIDERS } from '@angular/http'; +import { Observable } from 'rxjs/Rx'; import { describe, beforeEachProviders, @@ -11,10 +11,10 @@ import { it, expect } from '@angular/core/testing'; -import {TestComponentBuilder} from '@angular/compiler/testing'; +import { TestComponentBuilder } from '@angular/compiler/testing'; import PhoneDetail from '../../app/js/phone_detail/phone_detail.component'; -import {Phones, Phone} from '../../app/js/core/phones.service'; +import { Phones, Phone } from '../../app/js/core/phones.service'; function xyzPhoneData():Phone { return { diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/test/unit/phone_filter.pipe.spec.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/test/unit/phone_filter.pipe.spec.ts index 9c3fba870b..6de1e5722d 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/test/unit/phone_filter.pipe.spec.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/test/unit/phone_filter.pipe.spec.ts @@ -1,8 +1,8 @@ // #docregion -import {describe, beforeEachProviders, it, inject} from '@angular/core/testing'; +import { describe, beforeEachProviders, it, inject } from '@angular/core/testing'; import PhoneFilterPipe from '../../app/js/phone_list/phone_filter.pipe'; -import {Phone} from '../../app/js/core/phones.service'; +import { Phone } from '../../app/js/core/phones.service'; describe('PhoneFilterPipe', () => { diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/test/unit/phone_list.component.spec.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/test/unit/phone_list.component.spec.ts index ae9fc89b14..f2a294e0e0 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/test/unit/phone_list.component.spec.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/test/unit/phone_list.component.spec.ts @@ -1,9 +1,9 @@ // #docregion -import {provide, ApplicationRef} from '@angular/core'; -import {LocationStrategy, HashLocationStrategy} from '@angular/common'; -import {HTTP_PROVIDERS} from '@angular/http'; -import {ROUTER_PROVIDERS, ROUTER_PRIMARY_COMPONENT} from '@angular/router'; -import {Observable} from 'rxjs/Rx'; +import { provide, ApplicationRef } from '@angular/core'; +import { LocationStrategy, HashLocationStrategy } from '@angular/common'; +import { HTTP_PROVIDERS } from '@angular/http'; +import { ROUTER_PROVIDERS, ROUTER_PRIMARY_COMPONENT } from '@angular/router-deprecated'; +import { Observable } from 'rxjs/Rx'; import { describe, beforeEachProviders, @@ -12,12 +12,12 @@ import { expect, MockApplicationRef } from '@angular/core/testing'; -import {MockLocationStrategy} from '@angular/common/testing'; -import {TestComponentBuilder} from '@angular/compiler/testing'; +import { MockLocationStrategy } from '@angular/common/testing'; +import { TestComponentBuilder } from '@angular/compiler/testing'; import AppComponent from '../../app/js/app.component'; import PhoneList from '../../app/js/phone_list/phone_list.component'; -import {Phones, Phone} from '../../app/js/core/phones.service'; +import { Phones, Phone } from '../../app/js/core/phones.service'; class MockPhones extends Phones { query():Observable { diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/test/unit/phones.service.spec.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/test/unit/phones.service.spec.ts index fd7b93c77e..8d3fc5270f 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_final/test/unit/phones.service.spec.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_final/test/unit/phones.service.spec.ts @@ -1,7 +1,7 @@ // #docregion -import {describe, beforeEachProviders, it, inject} from '@angular/core/testing'; -import {HTTP_PROVIDERS} from '@angular/http'; -import {Phones} from '../../app/js/core/phones.service'; +import { describe, beforeEachProviders, it, inject } from '@angular/core/testing'; +import { HTTP_PROVIDERS } from '@angular/http'; +import { Phones } from '../../app/js/core/phones.service'; describe('Phones', () => { diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/app/js/app.module.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/app/js/app.module.ts index eb5d23b89f..974836e396 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/app/js/app.module.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/app/js/app.module.ts @@ -1,11 +1,11 @@ // #docregion adapter-import -import {UpgradeAdapter} from '@angular/upgrade'; +import { UpgradeAdapter } from '@angular/upgrade'; // #enddocregion adapter-import // #docregion adapter-state-import import upgradeAdapter from './core/upgrade_adapter'; // #enddocregion adapter-state-import // #docregion http-import -import {HTTP_PROVIDERS} from '@angular/http'; +import { HTTP_PROVIDERS } from '@angular/http'; // #enddocregion http-import import core from './core/core.module'; import phoneList from './phone_list/phone_list.module'; diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/app/js/core/core.module.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/app/js/core/core.module.ts index d30604a807..e02e7dcf1a 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/app/js/core/core.module.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/app/js/core/core.module.ts @@ -1,5 +1,5 @@ // #docregion -import {Phones} from './phones.service'; +import { Phones } from './phones.service'; import checkmarkFilter from './checkmark.filter'; import upgradeAdapter from './upgrade_adapter'; diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/app/js/core/phones.service.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/app/js/core/phones.service.ts index 6eac9b1611..96cce48520 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/app/js/core/phones.service.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/app/js/core/phones.service.ts @@ -1,7 +1,7 @@ // #docregion full -import {Injectable} from '@angular/core'; -import {Http, Response} from '@angular/http'; -import {Observable} from 'rxjs/Rx'; +import { Injectable } from '@angular/core'; +import { Http, Response } from '@angular/http'; +import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/app/js/core/upgrade_adapter.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/app/js/core/upgrade_adapter.ts index c5d20edd7a..f1ad63012a 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/app/js/core/upgrade_adapter.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/app/js/core/upgrade_adapter.ts @@ -1,5 +1,5 @@ // #docregion full -import {UpgradeAdapter} from '@angular/upgrade'; +import { UpgradeAdapter } from '@angular/upgrade'; // #docregion adapter-init const upgradeAdapter = new UpgradeAdapter(); diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/app/js/phone_detail/phone_detail.controller.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/app/js/phone_detail/phone_detail.controller.ts index 2dd8b25c9e..ef24ac5814 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/app/js/phone_detail/phone_detail.controller.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/app/js/phone_detail/phone_detail.controller.ts @@ -1,5 +1,5 @@ // #docregion -import {Phones, Phone} from '../core/phones.service'; +import { Phones, Phone } from '../core/phones.service'; interface PhoneRouteParams { phoneId: string diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/app/js/phone_list/phone_list.controller.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/app/js/phone_list/phone_list.controller.ts index 05ea2907ad..ae4c39b0c9 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/app/js/phone_list/phone_list.controller.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/app/js/phone_list/phone_list.controller.ts @@ -1,5 +1,5 @@ // #docregion -import {Phones, Phone} from '../core/phones.service'; +import { Phones, Phone } from '../core/phones.service'; class PhoneListCtrl { phones:Phone[]; diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/app/systemjs.config.js b/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/app/systemjs.config.js index 6eb2cccc14..2b0b854f6a 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/app/systemjs.config.js +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/app/systemjs.config.js @@ -18,6 +18,7 @@ System.config({ '@angular/platform-browser': { main: 'index.js', defaultExtension: 'js' }, '@angular/platform-browser-dynamic': { main: 'index.js', defaultExtension: 'js' }, '@angular/router': { main: 'index.js', defaultExtension: 'js' }, + '@angular/router-deprecated': { main: 'index.js', defaultExtension: 'js' }, '@angular/upgrade': { main: 'index.js', defaultExtension: 'js' }, 'rxjs': { defaultExtension: 'js' } diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/package.1.json b/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/package.1.json index 425ad7b82f..501da397e3 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/package.1.json +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/package.1.json @@ -6,14 +6,15 @@ "repository": "https://github.com/angular/angular-phonecat", "license": "MIT", "dependencies": { - "@angular/common": "0.0.0-3", - "@angular/compiler": "0.0.0-3", - "@angular/core": "0.0.0-3", - "@angular/http": "0.0.0-3", - "@angular/platform-browser": "0.0.0-3", - "@angular/platform-browser-dynamic": "0.0.0-3", - "@angular/router": "0.0.0-3", - "@angular/upgrade": "0.0.0-3", + "@angular/common": "2.0.0-rc.1", + "@angular/compiler": "2.0.0-rc.1", + "@angular/core": "2.0.0-rc.1", + "@angular/http": "2.0.0-rc.1", + "@angular/platform-browser": "2.0.0-rc.1", + "@angular/platform-browser-dynamic": "2.0.0-rc.1", + "@angular/router": "2.0.0-rc.1", + "@angular/router-deprecated": "2.0.0-rc.1", + "@angular/upgrade": "2.0.0-rc.1", "es6-shim": "^0.35.0", "reflect-metadata": "0.1.3", diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/test/karma_test_shim.js b/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/test/karma_test_shim.js index 7aa6c9ec90..26075e973d 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/test/karma_test_shim.js +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/test/karma_test_shim.js @@ -29,6 +29,7 @@ System.config({ '@angular/platform-browser': { main: 'index.js', defaultExtension: 'js' }, '@angular/platform-browser-dynamic': { main: 'index.js', defaultExtension: 'js' }, '@angular/router': { main: 'index.js', defaultExtension: 'js' }, + '@angular/router-deprecated': { main: 'index.js', defaultExtension: 'js' }, '@angular/upgrade': { main: 'index.js', defaultExtension: 'js' }, 'rxjs': { defaultExtension: 'js' } } @@ -37,8 +38,8 @@ System.config({ // #docregion ng2 System.import('@angular/core/testing').then(function(testing) { return System.import('@angular/platform-browser-dynamic/testing').then(function(browserTesting) { - testing.setBaseTestProviders(browserTesting.TEST_BROWSER_PLATFORM_PROVIDERS, - browserTesting.TEST_BROWSER_APPLICATION_PROVIDERS); + testing.setBaseTestProviders(browserTesting.TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS, + browserTesting.TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS); }); }).then(function() { return Promise.all( diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/test/unit/phone_detail.controller.spec.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/test/unit/phone_detail.controller.spec.ts index 1b2b7048e2..b28fc2d8c4 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/test/unit/phone_detail.controller.spec.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/test/unit/phone_detail.controller.spec.ts @@ -1,7 +1,7 @@ // #docregion -import {Observable} from 'rxjs/Rx'; +import { Observable } from 'rxjs/Rx'; import '../../app/js/phone_detail/phone_detail.module'; -import {Phones} from '../../app/js/core/phones.service'; +import { Phones } from '../../app/js/core/phones.service'; describe('PhoneDetailCtrl', () => { var scope, phones, $controller, diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/test/unit/phone_list.controller.spec.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/test/unit/phone_list.controller.spec.ts index 704d21bb10..3df1418d9a 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/test/unit/phone_list.controller.spec.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/test/unit/phone_list.controller.spec.ts @@ -1,7 +1,7 @@ // #docregion -import {Observable} from 'rxjs/Rx'; +import { Observable } from 'rxjs/Rx'; import '../../app/js/phone_list/phone_list.module'; -import {Phones} from '../../app/js/core/phones.service'; +import { Phones } from '../../app/js/core/phones.service'; describe('PhoneListCtrl', () => { var scope, ctrl, $httpBackend; diff --git a/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/test/unit/phones.service.spec.ts b/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/test/unit/phones.service.spec.ts index fd7b93c77e..8d3fc5270f 100644 --- a/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/test/unit/phones.service.spec.ts +++ b/public/docs/_examples/upgrade-phonecat/ts/ng2_initial/test/unit/phones.service.spec.ts @@ -1,7 +1,7 @@ // #docregion -import {describe, beforeEachProviders, it, inject} from '@angular/core/testing'; -import {HTTP_PROVIDERS} from '@angular/http'; -import {Phones} from '../../app/js/core/phones.service'; +import { describe, beforeEachProviders, it, inject } from '@angular/core/testing'; +import { HTTP_PROVIDERS } from '@angular/http'; +import { Phones } from '../../app/js/core/phones.service'; describe('Phones', () => { diff --git a/public/docs/_examples/user-input/ts/app/app.component.ts b/public/docs/_examples/user-input/ts/app/app.component.ts index bc76c0bbfb..2b6754f2aa 100644 --- a/public/docs/_examples/user-input/ts/app/app.component.ts +++ b/public/docs/_examples/user-input/ts/app/app.component.ts @@ -1,17 +1,17 @@ // #docregion -import {Component} from '@angular/core'; +import { Component } from '@angular/core'; -import {ClickMeComponent} from './click-me.component'; -import {ClickMeComponent2} from './click-me2.component'; +import { ClickMeComponent } from './click-me.component'; +import { ClickMeComponent2 } from './click-me2.component'; -import {LoopbackComponent} from './loop-back.component'; +import { LoopbackComponent } from './loop-back.component'; -import {KeyUpComponent_v1, +import { KeyUpComponent_v1, KeyUpComponent_v2, KeyUpComponent_v3, - KeyUpComponent_v4} from './keyup.components'; + KeyUpComponent_v4 } from './keyup.components'; -import {LittleTourComponent} from './little-tour.component'; +import { LittleTourComponent } from './little-tour.component'; @Component({ selector: 'my-app', diff --git a/public/docs/_examples/user-input/ts/app/click-me.component.ts b/public/docs/_examples/user-input/ts/app/click-me.component.ts index 6a8a90a120..20e77ad427 100644 --- a/public/docs/_examples/user-input/ts/app/click-me.component.ts +++ b/public/docs/_examples/user-input/ts/app/click-me.component.ts @@ -5,7 +5,7 @@ */ // #docregion -import {Component} from '@angular/core'; +import { Component } from '@angular/core'; // #docregion click-me-component @Component({ diff --git a/public/docs/_examples/user-input/ts/app/click-me2.component.ts b/public/docs/_examples/user-input/ts/app/click-me2.component.ts index b9ff83d3d4..b444e3594e 100644 --- a/public/docs/_examples/user-input/ts/app/click-me2.component.ts +++ b/public/docs/_examples/user-input/ts/app/click-me2.component.ts @@ -1,5 +1,5 @@ // #docregion -import {Component} from '@angular/core'; +import { Component } from '@angular/core'; @Component({ selector: 'click-me2', diff --git a/public/docs/_examples/user-input/ts/app/keyup.components.ts b/public/docs/_examples/user-input/ts/app/keyup.components.ts index 4fccd401be..c4acf742f5 100644 --- a/public/docs/_examples/user-input/ts/app/keyup.components.ts +++ b/public/docs/_examples/user-input/ts/app/keyup.components.ts @@ -1,6 +1,6 @@ // #docplaster // #docregion -import {Component} from '@angular/core'; +import { Component } from '@angular/core'; // #docregion key-up-component-1 @Component({ diff --git a/public/docs/_examples/user-input/ts/app/little-tour.component.ts b/public/docs/_examples/user-input/ts/app/little-tour.component.ts index 23a4fabdd5..f48abe3518 100644 --- a/public/docs/_examples/user-input/ts/app/little-tour.component.ts +++ b/public/docs/_examples/user-input/ts/app/little-tour.component.ts @@ -1,5 +1,5 @@ // #docregion -import {Component} from '@angular/core'; +import { Component } from '@angular/core'; // #docregion little-tour @Component({ diff --git a/public/docs/_examples/user-input/ts/app/loop-back.component.ts b/public/docs/_examples/user-input/ts/app/loop-back.component.ts index f7c089b4d0..f7c15f36bf 100644 --- a/public/docs/_examples/user-input/ts/app/loop-back.component.ts +++ b/public/docs/_examples/user-input/ts/app/loop-back.component.ts @@ -1,5 +1,5 @@ // #docregion -import {Component} from '@angular/core'; +import { Component } from '@angular/core'; // #docregion loop-back-component @Component({ selector: 'loop-back', diff --git a/public/docs/_examples/user-input/ts/app/main.ts b/public/docs/_examples/user-input/ts/app/main.ts index 07a96da44b..42dbeb9f7d 100644 --- a/public/docs/_examples/user-input/ts/app/main.ts +++ b/public/docs/_examples/user-input/ts/app/main.ts @@ -1,4 +1,5 @@ -import {bootstrap} from '@angular/platform-browser-dynamic'; -import {AppComponent} from './app.component'; +import { bootstrap } from '@angular/platform-browser-dynamic'; -bootstrap(AppComponent); \ No newline at end of file +import { AppComponent } from './app.component'; + +bootstrap(AppComponent); diff --git a/public/docs/_examples/user-input/ts/index.html b/public/docs/_examples/user-input/ts/index.html index 51405e2d2a..c20f29af88 100644 --- a/public/docs/_examples/user-input/ts/index.html +++ b/public/docs/_examples/user-input/ts/index.html @@ -16,7 +16,7 @@ diff --git a/public/docs/_examples/webpack/ts-snippets/webpack.config.snippets.ts b/public/docs/_examples/webpack/ts-snippets/webpack.config.snippets.ts new file mode 100644 index 0000000000..3211e5e2db --- /dev/null +++ b/public/docs/_examples/webpack/ts-snippets/webpack.config.snippets.ts @@ -0,0 +1,59 @@ +/* tslint:disable */ +// #docregion one-entry +entry: { + app: 'src/app.ts' +} +// #enddocregion one-entry + +// #docregion app-example +import { Component } from '@angular/core'; + +@Component({ + ... +}) +export class AppComponent {} +// #enddocregion app-example + +// #docregion one-output +output: { + filename: 'app.js' +} +// #enddocregion one-output + +// #docregion two-entries +entry: { + app: 'src/app.ts', + vendor: 'src/vendor.ts' +}, + +output: { + filename: '[name].js' +} +// #enddocregion two-entries + +// #docregion loaders +loaders: [ + { + test: /\.ts$/ + loaders: 'ts' + }, + { + test: /\.css$/ + loaders: 'style!css' + } +] +// #enddocregion loaders + +// #docregion imports +// #docregion single-import +import { AppComponent } from './app.component.ts'; +// #enddocregion single-import +import 'uiframework/dist/uiframework.css'; +// #enddocregion imports + +// #docregion plugins +plugins: [ + new webpack.optimize.UglifyJsPlugin() +] +// #enddocregion plugins +// #enddocregion diff --git a/public/docs/_examples/webpack/ts/.gitignore b/public/docs/_examples/webpack/ts/.gitignore new file mode 100644 index 0000000000..8628a5eef6 --- /dev/null +++ b/public/docs/_examples/webpack/ts/.gitignore @@ -0,0 +1,5 @@ +dist +!karma.webpack.conf.js +!webpack.config.js +!config/* +!public/css/styles.css diff --git a/public/docs/_examples/webpack/ts/config/helpers.js b/public/docs/_examples/webpack/ts/config/helpers.js new file mode 100644 index 0000000000..b760520f1c --- /dev/null +++ b/public/docs/_examples/webpack/ts/config/helpers.js @@ -0,0 +1,12 @@ +// #docregion +var path = require('path'); + +var _root = path.resolve(__dirname, '..'); + +function root(args) { + args = Array.prototype.slice.call(arguments, 0); + return path.join.apply(path, [_root].concat(args)); +} + +exports.root = root; +// #enddocregion \ No newline at end of file diff --git a/public/docs/_examples/webpack/ts/config/karma-test-shim.js b/public/docs/_examples/webpack/ts/config/karma-test-shim.js new file mode 100644 index 0000000000..7691460bcd --- /dev/null +++ b/public/docs/_examples/webpack/ts/config/karma-test-shim.js @@ -0,0 +1,22 @@ +// #docregion +Error.stackTraceLimit = Infinity; + +require('es6-shim'); +require('reflect-metadata'); + +require('zone.js/dist/zone'); +require('zone.js/dist/long-stack-trace-zone'); +require('zone.js/dist/jasmine-patch'); +require('zone.js/dist/async-test'); + +var appContext = require.context('../src', true, /\.spec\.ts/); + +appContext.keys().forEach(appContext); + +var testing = require('@angular/core/testing'); +var browser = require('@angular/platform-browser-dynamic/testing'); + +testing.setBaseTestProviders( + browser.TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS, + browser.TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS +); diff --git a/public/docs/_examples/webpack/ts/config/karma.conf.js b/public/docs/_examples/webpack/ts/config/karma.conf.js new file mode 100644 index 0000000000..3e2e34072f --- /dev/null +++ b/public/docs/_examples/webpack/ts/config/karma.conf.js @@ -0,0 +1,39 @@ +// #docregion +var webpackConfig = require('./webpack.test'); + +module.exports = function (config) { + var _config = { + basePath: '', + + frameworks: ['jasmine'], + + files: [ + {pattern: './config/karma-test-shim.js', watched: false} + ], + + preprocessors: { + './config/karma-test-shim.js': ['webpack', 'sourcemap'] + }, + + webpack: webpackConfig, + + webpackMiddleware: { + stats: 'errors-only' + }, + + webpackServer: { + noInfo: true + }, + + reporters: ['progress'], + port: 9876, + colors: true, + logLevel: config.LOG_INFO, + autoWatch: false, + browsers: ['PhantomJS'], + singleRun: true + }; + + config.set(_config); +}; +// #enddocregion diff --git a/public/docs/_examples/webpack/ts/config/webpack.common.js b/public/docs/_examples/webpack/ts/config/webpack.common.js new file mode 100644 index 0000000000..07e74adc65 --- /dev/null +++ b/public/docs/_examples/webpack/ts/config/webpack.common.js @@ -0,0 +1,64 @@ +// #docregion +var webpack = require('webpack'); +var HtmlWebpackPlugin = require('html-webpack-plugin'); +var ExtractTextPlugin = require('extract-text-webpack-plugin'); +var helpers = require('./helpers'); + +module.exports = { + // #docregion entries + entry: { + 'polyfills': './src/polyfills.ts', + 'vendor': './src/vendor.ts', + 'app': './src/main.ts' + }, + // #enddocregion + + // #docregion resolve + resolve: { + extensions: ['', '.js', '.ts'] + }, + // #enddocregion resolve + + // #docregion loaders + module: { + loaders: [ + { + test: /\.ts$/, + loader: 'ts' + }, + { + test: /\.html$/, + loader: 'html' + }, + { + test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/, + loader: 'file?name=assets/[name].[hash].[ext]' + }, + { + test: /\.css$/, + exclude: helpers.root('src', 'app'), + loader: ExtractTextPlugin.extract('style', 'css?sourceMap') + }, + { + test: /\.css$/, + include: helpers.root('src', 'app'), + loader: 'raw' + } + ] + }, + // #enddocregion loaders + + // #docregion plugins + plugins: [ + new webpack.optimize.CommonsChunkPlugin({ + name: ['app', 'vendor', 'polyfills'] + }), + + new HtmlWebpackPlugin({ + template: 'src/index.html' + }) + ] + // #enddocregion plugins +}; +// #enddocregion + diff --git a/public/docs/_examples/webpack/ts/config/webpack.dev.js b/public/docs/_examples/webpack/ts/config/webpack.dev.js new file mode 100644 index 0000000000..c1484a0caa --- /dev/null +++ b/public/docs/_examples/webpack/ts/config/webpack.dev.js @@ -0,0 +1,26 @@ +// #docregion +var webpackMerge = require('webpack-merge'); +var ExtractTextPlugin = require('extract-text-webpack-plugin'); +var commonConfig = require('./webpack.common.js'); +var helpers = require('./helpers'); + +module.exports = webpackMerge(commonConfig, { + devtool: 'cheap-module-eval-source-map', + + output: { + path: helpers.root('dist'), + publicPath: 'http://localhost:8080/', + filename: '[name].js', + chunkFilename: '[id].chunk.js' + }, + + plugins: [ + new ExtractTextPlugin('[name].css') + ], + + devServer: { + historyApiFallback: true, + stats: 'minimal' + } +}); +// #enddocregion \ No newline at end of file diff --git a/public/docs/_examples/webpack/ts/config/webpack.prod.js b/public/docs/_examples/webpack/ts/config/webpack.prod.js new file mode 100644 index 0000000000..0e897cb35a --- /dev/null +++ b/public/docs/_examples/webpack/ts/config/webpack.prod.js @@ -0,0 +1,36 @@ +// #docregion +var webpack = require('webpack'); +var webpackMerge = require('webpack-merge'); +var ExtractTextPlugin = require('extract-text-webpack-plugin'); +var commonConfig = require('./webpack.common.js'); +var helpers = require('./helpers'); + +const ENV = process.env.NODE_ENV = process.env.ENV = 'production'; + +module.exports = webpackMerge(commonConfig, { + devtool: 'source-map', + + output: { + path: helpers.root('dist'), + publicPath: '/', + filename: '[name].[hash].js', + chunkFilename: '[id].[hash].chunk.js' + }, + + htmlLoader: { + minimize: false // workaround for ng2 + }, + + plugins: [ + new webpack.NoErrorsPlugin(), + new webpack.optimize.DedupePlugin(), + new webpack.optimize.UglifyJsPlugin(), + new ExtractTextPlugin('[name].[hash].css'), + new webpack.DefinePlugin({ + 'process.env': { + 'ENV': JSON.stringify(ENV) + } + }) + ] +}); +// #enddocregion diff --git a/public/docs/_examples/webpack/ts/config/webpack.test.js b/public/docs/_examples/webpack/ts/config/webpack.test.js new file mode 100644 index 0000000000..5c24d4e81e --- /dev/null +++ b/public/docs/_examples/webpack/ts/config/webpack.test.js @@ -0,0 +1,31 @@ +// #docregion +module.exports = { + devtool: 'inline-source-map', + + resolve: { + extensions: ['', '.ts', '.js'] + }, + + module: { + loaders: [ + { + test: /\.ts$/, + loader: 'ts' + }, + { + test: /\.html$/, + loader: 'html' + + }, + { + test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/, + loader: 'null' + }, + { + test: /\.css$/, + loader: 'null' + } + ] + } +} +// #enddocregion diff --git a/public/docs/_examples/webpack/ts/example-config.json b/public/docs/_examples/webpack/ts/example-config.json new file mode 100644 index 0000000000..e69de29bb2 diff --git a/public/docs/_examples/webpack/ts/karma.webpack.conf.js b/public/docs/_examples/webpack/ts/karma.webpack.conf.js new file mode 100644 index 0000000000..e2a663e8de --- /dev/null +++ b/public/docs/_examples/webpack/ts/karma.webpack.conf.js @@ -0,0 +1,2 @@ +// #docregion +module.exports = require('./config/karma.conf.js'); diff --git a/public/docs/_examples/webpack/ts/package.webpack.json b/public/docs/_examples/webpack/ts/package.webpack.json new file mode 100644 index 0000000000..041c0b41e1 --- /dev/null +++ b/public/docs/_examples/webpack/ts/package.webpack.json @@ -0,0 +1,49 @@ +{ + "name": "angular2-webpack", + "version": "1.0.0", + "description": "A webpack starter for angular 2", + "scripts": { + "start": "webpack-dev-server --inline --progress --port 8080", + "test": "karma start", + "build": "rimraf dist && webpack --config config/webpack.prod.js --progress --profile --bail", + "postinstall": "typings install" + }, + "license": "MIT", + "dependencies": { + "@angular/common": "2.0.0-rc.1", + "@angular/compiler": "2.0.0-rc.1", + "@angular/core": "2.0.0-rc.1", + "@angular/http": "2.0.0-rc.1", + "@angular/platform-browser": "2.0.0-rc.1", + "@angular/platform-browser-dynamic": "2.0.0-rc.1", + "@angular/router-deprecated": "2.0.0-rc.1", + "es6-shim": "^0.35.0", + "reflect-metadata": "0.1.2", + "rxjs": "5.0.0-beta.6", + "zone.js": "0.6.12" + }, + "devDependencies": { + "css-loader": "^0.23.1", + "extract-text-webpack-plugin": "^1.0.1", + "file-loader": "^0.8.5", + "html-loader": "^0.4.3", + "html-webpack-plugin": "^2.15.0", + "jasmine-core": "^2.4.1", + "karma": "^0.13.22", + "karma-jasmine": "^0.3.8", + "karma-phantomjs-launcher": "^1.0.0", + "karma-sourcemap-loader": "^0.3.7", + "karma-webpack": "^1.7.0", + "null-loader": "^0.1.1", + "phantomjs-prebuilt": "^2.1.7", + "raw-loader": "^0.5.1", + "rimraf": "^2.5.2", + "style-loader": "^0.13.1", + "ts-loader": "^0.8.1", + "typescript": "^1.8.9", + "typings": "^0.7.12", + "webpack": "^1.12.14", + "webpack-dev-server": "^1.14.1", + "webpack-merge": "^0.9.0" + } +} diff --git a/public/docs/_examples/webpack/ts/public/css/styles.css b/public/docs/_examples/webpack/ts/public/css/styles.css new file mode 100644 index 0000000000..2d404ff5b9 --- /dev/null +++ b/public/docs/_examples/webpack/ts/public/css/styles.css @@ -0,0 +1,6 @@ +/* #docregion */ +body { + background: #0147A7; + color: #fff; +} +/* #enddocregion */ diff --git a/public/docs/_examples/webpack/ts/public/images/angular.png b/public/docs/_examples/webpack/ts/public/images/angular.png new file mode 100644 index 0000000000..a1d9790bc3 Binary files /dev/null and b/public/docs/_examples/webpack/ts/public/images/angular.png differ diff --git a/public/docs/_examples/webpack/ts/src/app/app.component.css b/public/docs/_examples/webpack/ts/src/app/app.component.css new file mode 100644 index 0000000000..bb624c5aae --- /dev/null +++ b/public/docs/_examples/webpack/ts/src/app/app.component.css @@ -0,0 +1,9 @@ +/* #docregion */ +main { + padding: 1em; + font-family: Arial, Helvetica, sans-serif; + text-align: center; + margin-top: 50px; + display: block; +} +/* #enddocregion */ diff --git a/public/docs/_examples/webpack/ts/src/app/app.component.html b/public/docs/_examples/webpack/ts/src/app/app.component.html new file mode 100644 index 0000000000..a333a7a72f --- /dev/null +++ b/public/docs/_examples/webpack/ts/src/app/app.component.html @@ -0,0 +1,7 @@ + +
    +

    Hello from Angular 2 App with Webpack

    + + +
    + diff --git a/public/docs/_examples/webpack/ts/src/app/app.component.spec.ts b/public/docs/_examples/webpack/ts/src/app/app.component.spec.ts new file mode 100644 index 0000000000..c2e85fd099 --- /dev/null +++ b/public/docs/_examples/webpack/ts/src/app/app.component.spec.ts @@ -0,0 +1,22 @@ +// #docregion +import { + it, + inject, + describe, + beforeEachProviders, + expect +} from '@angular/core/testing'; + +import { AppComponent } from './app.component'; + +describe('App', () => { + beforeEachProviders(() => [ + AppComponent + ]); + + it ('should work', inject([AppComponent], (app: AppComponent) => { + // Add real test here + expect(2).toBe(2); + })); +}); +// #enddocregion diff --git a/public/docs/_examples/webpack/ts/src/app/app.component.ts b/public/docs/_examples/webpack/ts/src/app/app.component.ts new file mode 100644 index 0000000000..590e5008ec --- /dev/null +++ b/public/docs/_examples/webpack/ts/src/app/app.component.ts @@ -0,0 +1,12 @@ +// #docregion +import { Component } from '@angular/core'; + +import '../../public/css/styles.css'; + +@Component({ + selector: 'my-app', + template: require('./app.component.html'), + styles: [require('./app.component.css')] +}) +export class AppComponent { } +// #enddocregion diff --git a/public/docs/_examples/webpack/ts/src/index.html b/public/docs/_examples/webpack/ts/src/index.html new file mode 100644 index 0000000000..503ea4a950 --- /dev/null +++ b/public/docs/_examples/webpack/ts/src/index.html @@ -0,0 +1,14 @@ + + + + + + Angular With Webpack + + + + + Loading... + + + diff --git a/public/docs/_examples/webpack/ts/src/main.ts b/public/docs/_examples/webpack/ts/src/main.ts new file mode 100644 index 0000000000..8ea0ea84ce --- /dev/null +++ b/public/docs/_examples/webpack/ts/src/main.ts @@ -0,0 +1,14 @@ +// #docregion +import { bootstrap } from '@angular/platform-browser-dynamic'; +import { enableProdMode } from '@angular/core'; + +import { AppComponent } from './app/app.component'; + +// #docregion enable-prod +if (process.env.ENV === 'production') { + enableProdMode(); +} +// #enddocregion enable-prod + +bootstrap(AppComponent, []); +// #enddocregion diff --git a/public/docs/_examples/webpack/ts/src/polyfills.ts b/public/docs/_examples/webpack/ts/src/polyfills.ts new file mode 100644 index 0000000000..617af577cf --- /dev/null +++ b/public/docs/_examples/webpack/ts/src/polyfills.ts @@ -0,0 +1,15 @@ +// #docregion +import 'es6-shim'; +import 'reflect-metadata'; +require('zone.js/dist/zone'); + +if (process.env.ENV === 'production') { + // Production + +} else { + // Development + + Error['stackTraceLimit'] = Infinity; + + require('zone.js/dist/long-stack-trace-zone'); +} diff --git a/public/docs/_examples/webpack/ts/src/vendor.ts b/public/docs/_examples/webpack/ts/src/vendor.ts new file mode 100644 index 0000000000..1a45c91d46 --- /dev/null +++ b/public/docs/_examples/webpack/ts/src/vendor.ts @@ -0,0 +1,15 @@ +// #docregion +// Angular 2 +import '@angular/platform-browser'; +import '@angular/platform-browser-dynamic'; +import '@angular/core'; +import '@angular/common'; +import '@angular/http'; +import '@angular/router-deprecated'; + +// RxJS +import 'rxjs'; + +// Other vendors for example jQuery, Lodash or Bootstrap +// You can import js, ts, css, sass, ... +// #enddocregion diff --git a/public/docs/_examples/webpack/ts/tsconfig.1.json b/public/docs/_examples/webpack/ts/tsconfig.1.json new file mode 100644 index 0000000000..302417ff3d --- /dev/null +++ b/public/docs/_examples/webpack/ts/tsconfig.1.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "target": "es5", + "module": "commonjs", + "moduleResolution": "node", + "sourceMap": true, + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "removeComments": false, + "noImplicitAny": true, + "suppressImplicitAnyIndexErrors": true + }, + "exclude": [ + "node_modules", + "typings/main", + "typings/main.d.ts" + ] +} diff --git a/public/docs/_examples/webpack/ts/typings.1.json b/public/docs/_examples/webpack/ts/typings.1.json new file mode 100644 index 0000000000..b5324f4199 --- /dev/null +++ b/public/docs/_examples/webpack/ts/typings.1.json @@ -0,0 +1,7 @@ +{ + "ambientDependencies": { + "es6-shim": "registry:dt/es6-shim#0.31.2+20160317120654", + "jasmine": "registry:dt/jasmine#2.2.0+20160412134438", + "node": "registry:dt/node#4.0.0+20160509154515" + } +} diff --git a/public/docs/_examples/webpack/ts/webpack.config.js b/public/docs/_examples/webpack/ts/webpack.config.js new file mode 100644 index 0000000000..66141706fe --- /dev/null +++ b/public/docs/_examples/webpack/ts/webpack.config.js @@ -0,0 +1,3 @@ +// #docregion +module.exports = require('./config/webpack.dev.js'); +// #enddocregion \ No newline at end of file diff --git a/public/docs/_layout.jade b/public/docs/_layout.jade index ba13f435a6..b5fbb2370a 100644 --- a/public/docs/_layout.jade +++ b/public/docs/_layout.jade @@ -19,11 +19,17 @@ html(lang="en" ng-app="angularIOApp" itemscope itemtype="http://schema.org/Frame else if current.path.indexOf('cheatsheet') > 0 != yield else - article(class="l-content-small grid-fluid docs-content") - != yield - - if (current.path[3] == 'guide' || current.path[3] == 'tutorial') && current.path[4] - != partial("../_includes/_next-item") + if current.path[3] == 'index' || current.path[3] == 'styleguide' + article(class="l-content-small grid-fluid docs-content") + != yield + else + article(class="l-content-small grid-fluid docs-content") + div(class="c10") + .showcase.shadow-1 + .showcase-content + != yield + if (current.path[3] == 'guide' || current.path[3] == 'tutorial') && current.path[4] + != partial("../_includes/_next-item") != partial("../_includes/_footer") != partial("../_includes/_scripts-include") \ No newline at end of file diff --git a/public/docs/dart/latest/_util-fns.jade b/public/docs/dart/latest/_util-fns.jade index 6af691a7bd..380b4ac7a1 100644 --- a/public/docs/dart/latest/_util-fns.jade +++ b/public/docs/dart/latest/_util-fns.jade @@ -1,32 +1,56 @@ include ../../../_includes/_util-fns -mixin liveExLinks(name) - :marked - [Run the live example](https://angular-examples.github.io/#{name}) | - [View its source code](https://github.com/angular-examples/#{name}) +//- See the _util-fns file included above for a description of the use of these variables. +- var _docsFor = 'dart'; +- var _decorator = 'annotation'; +- var _array = 'list'; +- var _an_array = 'a list'; //- Deprecate now that we have the articles +- var _a = 'an'; +- var _an = 'a'; +- var _priv = '_'; +- var _Lang = 'Dart'; +- var _Promise = 'Future'; +- var _Observable = 'Stream'; +- var _liveLink = 'sample repo'; -- var adjustExamplePath = function(path) { +mixin liveExampleLink(linkText, exampleUrlPartName) + a(href='https://angular-examples.github.io/#{exampleUrlPartName}' target="_blank")= linkText + +mixin liveExampleLink2(linkText, exampleUrlPartName) + - var liveExampleSourceLinkText = attributes.srcLinkText || 'view source' + | #[+liveExampleLink(linkText, exampleUrlPartName)] + | (#[a(href='https://github.com/angular-examples/#{exampleUrlPartName}' target="_blank") #{liveExampleSourceLinkText}]) + +- var adjustExamplePath = function(_path) { +- if(!_path) return _path; +- var path = _path.trim(); - var folder = getFolder(path); - var extn = getExtn(path); - // if(extn == 'dart') return path; -- var baseName = getBaseFileName(path); +- var baseName = getBaseFileName(path) || path; // TODO: have getBaseFileName() return path - var baseNameNoExt = baseName.substr(0,baseName.length - (extn.length + 1)); -- var inWebFolder = baseNameNoExt.match(/^(main|index)$/); -- // Adjust the folder path, e.g., ts -> dart -- folder = folder.replace(/(^|\/)ts\//, '$1dart/').replace(/(^|\/)app$/, inWebFolder ? '$1web' : '$1lib'); +- var inWebFolder = baseNameNoExt.match(/^(main|index(\.\d)?)$/); +- // Adjust the folder path, e.g., ts -> dart +- folder = folder.replace(/(^|\/)ts($|\/)/, '$1dart$2').replace(/(^|\/)app($|\/)/, inWebFolder ? '$1web$2' : '$1lib$2'); +- // Special case not handled above: e.g., index.html -> web/index.html +- if(baseNameNoExt.match(/^(index|styles)(\.\d)?$/)) folder = (folder ? folder + '/' : '') + 'web'; - // In file name, replace special characters with underscore - baseNameNoExt = baseNameNoExt.replace(/[\-\.]/g, '_'); - // Adjust the file extension - if(extn == 'ts') extn = 'dart'; -- return folder + '/' + baseNameNoExt + '.' + extn; +- return (folder ? folder + '/' : '') + baseNameNoExt + (extn ? '.' + extn : ''); - }; -- var adjustExampleTitle = function(title) { -- // Assume title is a path if it ends with an extension like '.foo'. -- if(title && title.match(/\.\w+$/) && adjustExamplePath) { -- var isAbsolutePath = title.match(/^\//); -- title = adjustExamplePath(title); -- if(!isAbsolutePath && title.match(/^\//)) title = title.substring(1); +- var adjustExampleTitle = function(_title) { +- if(!_title || !adjustExamplePath) return _title; +- var title = _title.trim(); +- // Assume title is a path if it ends with an extension like '.foo', +- // optionally followed by some comment in parentheses. +- var matches = title.match(/(.*\.\w+)($|\s*\([\w ]+\)$)/); +- if(matches && matches.length == 3) { +- // e.g. matches == ['abc.ts (excerpt)', 'abc.ts', ' (excerpt)'] +- var path = adjustExamplePath(matches[1]); +- title = path + matches[2]; - } - return title; - } diff --git a/public/docs/dart/latest/cheatsheet.jade b/public/docs/dart/latest/cheatsheet.jade index 4548cf52e0..694e02b0d2 100644 --- a/public/docs/dart/latest/cheatsheet.jade +++ b/public/docs/dart/latest/cheatsheet.jade @@ -1,6 +1,6 @@ - var base = current.path[4] ? '.' : './guide'; -.banner - p.text-body This cheat sheet is provisional and may change. Angular 2 is currently in Beta. +.banner.grid-fluid + p.text-body.c10 This cheat sheet is provisional and may change. Angular 2 is currently in Beta. article(class="l-content-small grid-fluid docs-content") .cheatsheet diff --git a/public/docs/dart/latest/guide/_data.json b/public/docs/dart/latest/guide/_data.json index 68921b910a..fe30a34965 100644 --- a/public/docs/dart/latest/guide/_data.json +++ b/public/docs/dart/latest/guide/_data.json @@ -100,9 +100,15 @@ "intro": "Pipes transform displayed values within a template." }, + "router-deprecated": { + "title": "Router (Deprecated Beta)", + "intro": "The deprecated Beta Router." + }, + "router": { "title": "Routing & Navigation", - "intro": "Discover the basics of screen navigation with the Angular 2 router." + "intro": "Discover the basics of screen navigation with the Angular 2 router.", + "hide": true }, "structural-directives": { @@ -128,6 +134,12 @@ "hide": true }, + "webpack": { + "title": "Introduction to Webpack", + "intro": "Create your Angular 2 applications with a Webpack based tooling", + "hide": true + }, + "glossary": { "title": "Glossary", "intro": "Brief definitions of the most important words in the Angular 2 vocabulary", diff --git a/public/docs/dart/latest/guide/attribute-directives.jade b/public/docs/dart/latest/guide/attribute-directives.jade index 25afd1888d..350cd60b88 100644 --- a/public/docs/dart/latest/guide/attribute-directives.jade +++ b/public/docs/dart/latest/guide/attribute-directives.jade @@ -1,12 +1,9 @@ -include ../_util-fns +extends ../../../ts/latest/guide/attribute-directives.jade -:marked - We're working on the Dart version of this chapter. - In the meantime, please see these resources: - - * [Attribute Directives](/docs/ts/latest/guide/attribute-directives.html): - The TypeScript version of this chapter - - * [Dart source code](https://github.com/angular/angular.io/tree/master/public/docs/_examples/attribute-directives/dart): - A preliminary version of the example code that will appear in this chapter +block includes + include ../_util-fns +block highlight-directive-1 + :marked + We begin by importing the Angular `core`. + Then we define the directive metadata by means of the `@Directive` annotation. diff --git a/public/docs/dart/latest/guide/component-styles.jade b/public/docs/dart/latest/guide/component-styles.jade index f8df2a84a6..71507a7d01 100644 --- a/public/docs/dart/latest/guide/component-styles.jade +++ b/public/docs/dart/latest/guide/component-styles.jade @@ -1 +1,36 @@ -!= partial("../../../_includes/_ts-temp") \ No newline at end of file +extends ../../../ts/latest/guide/component-styles.jade + +block includes + include ../_util-fns + +//- TODO: consider adding material equivalent to TS Appendices 1 & 2 if relevant. + +block style-url + :marked + Note that the URLs in `styleUrls` are relative to the component. + +block module-bundlers + //- TODO: determine if an equivalent of the TS material is relevant for Dart. + //- Leaving empty for now. + +block css-import-url + :marked + In *this* case the URL is relative to the CSS file into which we are importing. + .alert.is-important + :marked + URLs are currently not interpreted in this way, see + [issue 8518](href="https://github.com/angular/angular/issues/8518"). + Until this issue is fixed, absolute package-reference style URLs must + be given as is illustrated below. + +block module-id + p. + Thankfully, this is the default interpretation of relative URLs in + Angular2 for Dart: + +makeExample('component-styles/ts/app/quest-summary.component.ts', 'urls')(format='.') + :marked + Note that special measures must be taken in Angular2 for TypeScript, if + relative URLs are to have the same interpretation. See + [here](../../../ts/latest/guide/component-styles.html#!#relative-urls) + for details. + diff --git a/public/docs/dart/latest/guide/hierarchical-dependency-injection.jade b/public/docs/dart/latest/guide/hierarchical-dependency-injection.jade index 1756f4eca4..153e3c8108 100644 --- a/public/docs/dart/latest/guide/hierarchical-dependency-injection.jade +++ b/public/docs/dart/latest/guide/hierarchical-dependency-injection.jade @@ -2,6 +2,3 @@ extends ../../../ts/latest/guide/hierarchical-dependency-injection.jade block includes include ../_util-fns - -block liveExample - +liveExLinks('hierarchical-dependency-injection') diff --git a/public/docs/dart/latest/guide/index.jade b/public/docs/dart/latest/guide/index.jade index 8ef237ed68..417bf9ea8d 100644 --- a/public/docs/dart/latest/guide/index.jade +++ b/public/docs/dart/latest/guide/index.jade @@ -1,93 +1,13 @@ -include ../_util-fns +extends ../../../ts/latest/guide/index.jade -:marked - This Developers Guide is a practical guide to Angular for experienced programmers who - are building client applications in HTML and Dart. -figure - img(src="/resources/images/devguide/intro/people.png" alt="Us" align="left" style="width:200px; margin-left:-40px;margin-right:10px" ) -:marked - We are on a journey together to understand how Angular works and, more importantly, - how to make it work for us. We look at our application requirements and we see problems to solve. -
    +block includes + include ../_util-fns - * How do we get data onto the screen and handle user interactions? - * How do we organize our code into manageable, cohesive chunks of functionality that work together? - * What are the essential Angular building blocks and how do they help? - * How do we minimize routine, mechanical coding in favor of declarative, higher level constructs without losing control? - - This chapter begins the journey. - - -:marked - # How to read this guide - Each chapter of this guide targets an Angular feature, - showing how to use it to solve a programming problem. - - All the chapters include code snippets ... snippets we can reuse in our own applications. - Typically, these snippets are excerpts from a sample application that accompanies the chapter. - - **All the source files** for each sample app are displayed together at the **end of each chapter.** - - - - - - - - Here is a learning path we might follow: - - 1. First, be familiar with Dart programming and with web concepts such as - the DOM, HTML, and CSS. Dart tutorials such as - [Get Started](https://www.dartlang.org/docs/tutorials/get-started/) and - [Connect Dart & HTML](https://www.dartlang.org/docs/tutorials/connect-dart-html/) - are a great way to start. - - 1. Follow the [QuickStart](../quickstart.html), which is the "Hello, World" of Angular 2. - It shows how to set up the libraries and tools needed to write *any* Angular app. - It ends with a "proof of life", a running Angular app. - - 1. Next, read the Developers Guide chapters in order: - - 1. The rest of this chapter, especially the Architecture overview - 1. [Displaying Data](displaying-data.html) - 1. [User Input](user-input.html) - 1. [Forms](forms.html) - - - - 1. Consider hopping over to the [TypeScript docs](/docs/ts/latest/) - since they're currently ahead of the Dart docs. (We're working on that!) - Especially check out the [Tutorial](/docs/ts/latest/tutorial/) and - [Cheat Sheet](/docs/ts/latest/guide/cheatsheet.html), and the guide chapters - [Dependency Injection](/docs/ts/latest/guide/dependency-injection.html) - and [Template Syntax](/docs/ts/latest/guide/template-syntax.html). - - - - Don't miss the [Cheat Sheet](cheatsheet.html), a handy map to Angular. - - -.l-main-section -:marked - # Appendix: The Hero Staffing Agency - - There's a backstory to the samples in this guide. - - The world is full of crises large and small. - Fortunately, courageous heroes are prepared to take on every challenge. - The shadowy Hero Staffing Agency matches crises to heroes. - - We are contract developers, hired by the Agency to build an application to manage their operations. - The Agency maintains a stable of heroes with special powers. - Ordinary humans submit crises as job requests. The heroes bid to take the job, and the Agency - assigns each job accordingly. - - Our application handles every detail of recruiting, tracking, and job assignment. - For example, the [Forms](forms.html) chapter features a screen for - entering personal information about heroes: - -figure.image-display - img(src="/resources/images/devguide/forms/hero-form-1.png" width="400px" alt="Clean Form") +block example-links + :marked + Look for a link to that sample near the top of each page. + For example, the sample repo https://github.com/angular-examples/architecture + contains the code + for the [Architecture](architecture.html) chapter's sample. + A running version of that sample is at + https://angular-examples.github.io/architecture/. diff --git a/public/docs/dart/latest/guide/lifecycle-hooks.jade b/public/docs/dart/latest/guide/lifecycle-hooks.jade index da0e14d7ee..5a57169bbb 100644 --- a/public/docs/dart/latest/guide/lifecycle-hooks.jade +++ b/public/docs/dart/latest/guide/lifecycle-hooks.jade @@ -1,12 +1,11 @@ -include ../_util-fns +extends ../../../ts/latest/guide/lifecycle-hooks.jade -:marked - We're working on the Dart version of this chapter. - In the meantime, please see these resources: +block includes + include ../_util-fns - * [Lifecycle Hooks](/docs/ts/latest/guide/lifecycle-hooks.html): - The TypeScript version of this chapter - - * [Dart source code](https://github.com/angular/angular.io/tree/master/public/docs/_examples/lifecycle-hooks/dart): - A preliminary version of the example code that will appear in this chapter +block optional-interfaces + //- n/a for Dart +block tick-methods + :marked + The `LoggerService.tick` method, which returns a `Future`, postpones the update one turn of the of the browser's update cycle ... and that's long enough. diff --git a/public/docs/dart/latest/guide/pipes.jade b/public/docs/dart/latest/guide/pipes.jade index 7348505632..ae4e3aeead 100644 --- a/public/docs/dart/latest/guide/pipes.jade +++ b/public/docs/dart/latest/guide/pipes.jade @@ -1,12 +1,11 @@ -include ../_util-fns +extends ../../../ts/latest/guide/pipes.jade -:marked - We're working on the Dart version of this chapter. - In the meantime, please see these resources: +block includes + include ../_util-fns - * [Pipes](/docs/ts/latest/guide/pipes.html): - The TypeScript version of this chapter - - * [Dart source code](https://github.com/angular/angular.io/tree/master/public/docs/_examples/pipes/dart): - A preliminary version of the example code that will appear in this chapter +block pure-change + :marked + Angular executes a *pure pipe* only when it detects a *pure change* to the input value. + In Angular Dart, a *pure change* results only from a change in object reference + (given that [everything is an object in Dart](https://www.dartlang.org/docs/dart-up-and-running/ch02.html#important-concepts)). diff --git a/public/docs/dart/latest/guide/router-deprecated.jade b/public/docs/dart/latest/guide/router-deprecated.jade new file mode 100644 index 0000000000..f8df2a84a6 --- /dev/null +++ b/public/docs/dart/latest/guide/router-deprecated.jade @@ -0,0 +1 @@ +!= partial("../../../_includes/_ts-temp") \ No newline at end of file diff --git a/public/docs/dart/latest/guide/server-communication.jade b/public/docs/dart/latest/guide/server-communication.jade index 12631f8570..9572a51b0f 100644 --- a/public/docs/dart/latest/guide/server-communication.jade +++ b/public/docs/dart/latest/guide/server-communication.jade @@ -1,11 +1,82 @@ -include ../_util-fns +extends ../../../ts/latest/guide/server-communication.jade -:marked - We're working on the Dart version of this chapter. - In the meantime, please see these resources: +block includes + include ../_util-fns - * [Http Client](/docs/ts/latest/guide/server-communication.html): - The TypeScript version of this chapter. +block http-providers + //- TODO(chalin): mention the Angular transformer resolved_identifiers. + //- Maybe not yet at this point in the chapter. - * [Dart source code](https://github.com/angular/angular.io/tree/master/public/docs/_examples/server-communication/dart): - A preliminary version of the example code that will appear in this chapter. +block getheroes-and-addhero + :marked + The hero service `getHeroes()` and `addHero()` asynchronous methods return the + [`Future`](https://api.dartlang.org/stable/1.16.0/dart-async/Future-class.html) + values of the current hero list and the newly added hero, + respectively. The hero list component methods of the same name specifying + the actions to be taken when the asynchronous method calls succeed or fail. + + For more information about `Future`s, consult any one + of the [articles](https://www.dartlang.org/articles/) on asynchronous + programming in Dart, or the tutorial on + [_Asynchronous Programming: Futures_](https://www.dartlang.org/docs/tutorials/futures/). + +block http-client-service + :marked + The imported `BrowserClient` client service gets + [injected](dependency-injection.html) into the `HeroService` constructor. + Note that `BrowserClient` is not part of the Angular core. + It's an optional service provided by the Dart + [`http` package](https://pub.dartlang.org/packages/http). + +block rxjs + //- N/A + +block non-success-status-codes + :marked + Because a status code outside the 200-299 range _is an error_ from the + application point of view, we test for this condition and throw an + exception when detected. + +block parse-json + :marked + The response data are in JSON string form. + We must parse that string into JavaScript objects which we do by calling + the `JSON.decode()` method from the `dart:convert` library. + +block error-handling + //- TODO: describe `_handleError`? + +block hlc-error-handling + :marked + Back in the `HeroListComponent`, we wrapped our call to + `#{_priv}heroService.getHeroes()` in a `try` clause. When an exception is + caught, the `errorMessage` variable — which we've bound conditionally in the + template — gets assigned to. + +block hero-list-comp-add-hero + :marked + Back in the `HeroListComponent`, we see that *its* `addHero()` + awaits for the *service's* asynchronous `addHero()` to return, and when it does, + the new hero is added to the `heroes` list for presentation to the user. + +makeExample('server-communication/ts/app/toh/hero-list.component.ts', 'addHero', 'app/toh/hero-list.component.ts (addHero)')(format=".") + +block promises + //- N/A + +block wikipedia-jsonp+ + :marked + Wikipedia offers both `CORS` and `JSONP` search APIs. + .alert.is-important + :marked + The remaining content of this section is coming soon. + In the meantime, consult the + [example sources](https://github.com/angular-examples/server-communication) + to see how to access Wikipedia via its `JSONP` API. + +block redirect-to-web-api + :marked + To achieve this, we have Angular inject an in-memory web API server + instance as a provider for the `BrowserClient`. This is possible because + the in-memory web API server class extends `BrowserClient`. Here are the + pertinent details, excerpt from `TohComponent`: + +makeExample('server-communication/ts/app/toh/toh.component.ts', 'in-mem-web-api', 'app/toh.component.ts (excerpt)')(format=".") diff --git a/public/docs/dart/latest/guide/structural-directives.jade b/public/docs/dart/latest/guide/structural-directives.jade index 98544357aa..ecae8ac2ee 100644 --- a/public/docs/dart/latest/guide/structural-directives.jade +++ b/public/docs/dart/latest/guide/structural-directives.jade @@ -1,12 +1,9 @@ -include ../_util-fns +extends ../../../ts/latest/guide/structural-directives.jade -:marked - We're working on the Dart version of this chapter. - In the meantime, please see these resources: +block includes + include ../_util-fns - * [Structural Directives](/docs/ts/latest/guide/structural-directives.html): - The TypeScript version of this chapter - - * [Dart source code](https://github.com/angular/angular.io/tree/master/public/docs/_examples/structural-directives/dart): - A preliminary version of the example code that will appear in this chapter - +block unless-intro + :marked + Creating a directive is similar to creating a component. + Here is how we begin: diff --git a/public/docs/dart/latest/guide/webpack.jade b/public/docs/dart/latest/guide/webpack.jade new file mode 100644 index 0000000000..6778b6af28 --- /dev/null +++ b/public/docs/dart/latest/guide/webpack.jade @@ -0,0 +1 @@ +!= partial("../../../_includes/_ts-temp") diff --git a/public/docs/dart/latest/quickstart.jade b/public/docs/dart/latest/quickstart.jade index 96d1c2c1d7..46424744ab 100644 --- a/public/docs/dart/latest/quickstart.jade +++ b/public/docs/dart/latest/quickstart.jade @@ -1,239 +1,210 @@ -include _util-fns +extends ../../ts/latest/quickstart.jade -:marked - Let's start from zero and build a super simple Angular 2 application in Dart. +block includes + include _util-fns + - var _Install = 'Get' + - var _prereq = 'the Dart SDK' + - var _angular_browser_uri = 'package:angular2/platform/browser.dart' + - var _angular_core_uri = 'package:angular2/core.dart' + - var _appDir = 'lib' + - var _indexHtmlDir = 'web' -.callout.is-helpful - header Don't want Dart? +block setup-tooling :marked - Although we're getting started in Dart, you can also write Angular 2 apps - in TypeScript and JavaScript. - Just select either of those languages from the combo-box in the banner. + Install the **[Dart SDK](https://www.dartlang.org/downloads/)**, + if not already on your machine, and any tools you like to use with Dart. + The Dart SDK includes tools such as **[pub][pub]**, the Dart package manager. + If you don't have a favorite Dart editor already, try + [WebStorm][WS], which comes with a Dart plugin. + You can also download [Dart plugins for other IDEs and editors][DT]. -p. - These instructions assume that you already have the - Dart SDK - and any tools you like to use with Dart. - If you don't have a favorite editor already, try - WebStorm, - which comes with a Dart plugin. - You can also download - Dart plugins for - other IDEs and editors. - Once you have the Dart SDK and any other tools you want, return here. + [WS]: https://confluence.jetbrains.com/display/WI/Getting+started+with+Dart + [DT]: https://www.dartlang.org/tools + [pub]: https://www.dartlang.org/tools/pub +block download-source + // exclude this section from Dart -//- ########################## -.l-main-section - h2#section-install-angular Set up a new app directory - +block package-and-config-files :marked - Create a new directory, - and put a file named `pubspec.yaml` in it. + In the project folder just created, create a file named + **[pubspec.yaml][pubspec]** with the code below. + This pubspec must specify the **angular2** and **browser** + packages as dependencies, as well as the `angular2` transformer. + It can also specify other packages and transformers for the app to use, + such as [dart_to_js_script_rewriter](https://pub.dartlang.org/packages/dart_to_js_script_rewriter). + Angular 2 is still changing, so provide an exact version: **2.0.0-beta.17**. + + [pubspec]: https://www.dartlang.org/tools/pub/pubspec.html + + +makeExample('quickstart/dart/pubspec.yaml', null, 'pubspec.yaml') + +block install-packages + :marked + From the project folder, run `pub get` to install the angular2 and browser + packages (along with the packages they depend on). code-example(language="sh"). - > mkdir angular2_getting_started - > cd angular2_getting_started - > vim pubspec.yaml # Use your favorite editor! - - p. - In pubspec.yaml, - specify the angular2 and browser packages as dependencies, - as well as the angular2 transformer. - Angular 2 is still changing, so provide an exact version: - 2.0.0-beta.17. - - +makeExample('quickstart/dart/pubspec.yaml', 'no-rewriter', 'pubspec.yaml') - - p. - In the same directory, create a web directory, and then - run pub get to install the angular2 and browser packages - (along with the packages they depend on). - - code-example(language="sh"). - > mkdir web > pub get Resolving dependencies... - //- PENDING: Create template? Link to pub/pubspec docs? - - -//- ########################## -.l-main-section - h2#section-transpile Create a Dart file - - p. - Create a file under web named main.dart. - - code-example(language="sh"). - > vim web/main.dart # Use your favorite editor! - - p. - Paste the following code into web/main.dart: - - +makeExample('quickstart/dart/web/main.dart', null, 'web/main.dart') - +block annotation-fields :marked - You've just defined an Angular 2 **component**, - one of the most important Angular 2 features. - Components are the primary way to create application views - and support them with application logic. - - This component is an empty, do-nothing class named `AppComponent`. - You can add properties and application logic to it later, - when you're ready to build a substantive application. - - Above the class is the `@Component` annotation, - which tells Angular that this class *is an Angular component*. The call to the `@Component` constructor has two named parameters, `selector` and `template`. - The `selector` parameter specifies a CSS selector for - a host HTML element named `my-app`. - Angular creates and displays an instance of `AppComponent` - wherever it encounters a `my-app` element. - - The `template` parameter is the component's companion template - that tells Angular how to render a view. - In this case, the template is a single line of HTML announcing - "My First Angular 2 App". - - The main() function - calls Angular's bootstrap() function, - which tells Angular to start the application with `AppComponent` - at the application root. - Someday the application will - consist of more components arising in tree-like fashion from this root. - - The top lines import two libraries. - *All* Dart files that use Angular APIs import `core.dart`. - Only files that call `bootstrap()` import `platform/browser.dart`. - -//- ########################## -.l-main-section - - - h2#section-angular-create-account Create an HTML file - +block create-main p. - Create a file named web/index.html that contains - the following code: + Now we need something to tell Angular to load the root component. + Create: + ul + li a #[b folder named #[code web]] + li a file named #[code #[+adjExPath('app/main.ts')]] with the following content: - +makeExample('quickstart/dart/web/index.html', null, 'web/index.html') - - :marked - The `` tag in the `` is - the custom HTML element defined in the Dart file. - - -//- ########################## -.l-main-section - - h2#section-angular-run-app Run the app +block index-html-commentary-for-ts + //- N/A +block run-app p. - You have a few options for running your app. + We have a few options for running our app. One is to launch a local HTTP server and then view the app in Dartium. - You can use whatever server you like, such as WebStorm's server + We can use any web server, such as WebStorm's server or Python's SimpleHTTPServer. - p. Another option is to build and serve the app using pub serve, - and then run it by visiting http://localhost:8080 in any modern browser. - Pub serve generates the JavaScript on the fly, - which can take a while when you first visit the page. - + and then run it by visiting http://localhost:8080 in any modern browser. + Pub serve generates JavaScript on the fly, + which can take a while when first visiting the page. + Pub serve also runs in watch mode, and will recompile and subsequently serve + any changed assets. p. - Once the app is running, - you should see My First Angular 2 App in your browser window. + Once the app is running, the browser window should show the following: - :marked - If you don't see that, make sure you've entered all the code correctly - and run `pub get`. +block build-app + .alert.is-important + :marked + If you don't see **My First Angular 2 App**, make sure you've entered all the code correctly, + in the [proper folders](#wrap-up), + and run `pub get`. -//- ########################## -.l-main-section + .l-verbose-section + h3#section-angular-run-app Building the app (generating JavaScript) - h2#section-angular-run-app Generate JavaScript + :marked + Before deploying the app, we need to generate JavaScript files. + The `pub build` command makes that easy. - :marked - Before you can deploy your app, you need to generate JavaScript files. - Pub build makes that easy. - To improve your app's performance, convert the - HTML file to directly include the generated JavaScript; - one way to do that is with dart_to_js_script_rewriter. - - :marked - Add the dart_to_js_script_rewriter package to your pubspec, - in both the `dependencies` and `transformers` sections. - - - var stylePattern = { pnk: /(dart_to_js_script_rewriter.*$)|(- dart_to_js_script_rewriter.*$)/gm, otl: /(dependencies:)|(transformers:)/g }; - +makeExample('quickstart/dart/pubspec.yaml', null, 'pubspec.yaml', stylePattern) - - p. - Then compile your Dart code to JavaScript, - using pub build. - - code-example(language="basic"). - > pub build - Loading source assets... - - p. - The generated JavaScript appears, along with supporting files, - under the build directory. - - p. - When you generate JavaScript for an Angular app, - be sure to use the Angular transformer. - It analyzes your code, - converting reflection-using code to static code - that Dart's build tools can compile to faster, smaller JavaScript. - The highlighted lines in pubspec.yaml - configure the Angular transformer: - - - var stylePattern = { otl: /(transformers:)|(- angular2:)|(entry_points.*$)/gm }; - +makeExample('quickstart/dart/pubspec.yaml', null, 'pubspec.yaml', stylePattern) - - p. - The entry_points item - identifies the Dart file in your app - that has a main() function. - For more information, see the - Angular - transformer wiki page. - - - #performance.l-sub-section - h3 Performance, the transformer, and Angular 2 libraries + code-example(language="sh"). + > pub build + Loading source assets... p. - When you import bootstrap.dart, - you also get dart:mirrors, - a reflection library that - causes performance problems when compiled to JavaScript. - Don't worry, - the Angular transformer converts your entry points - (entry_points in pubspec.yaml) - so that they don't use mirrors. + The generated JavaScript appears, along with supporting files, + under a directory named build. + h4#angular_transformer Using the Angular transformer -//- WHAT'S NEXT... ########################## -.l-main-section - h2#section-transpile Great job! Next step... + p. + When generating JavaScript for an Angular app, + be sure to use the Angular transformer. + It analyzes the Dart code, + converting reflection-using code to static code + that Dart's build tools can compile to faster, smaller JavaScript. + The highlighted lines in pubspec.yaml + configure the Angular transformer: - + - var stylePattern = { otl: /(transformers:)|(- angular2:)|(entry_points.*$)/gm }; + +makeExample('quickstart/dart/pubspec.yaml', null, 'pubspec.yaml', stylePattern) - p. - Follow the developer guide - to continue playing with Angular 2 for Dart. + p. + The entry_points item + identifies the Dart file in our app + that has a main() function. + For more information, see the + Angular + transformer wiki page. - p. - Or read more about Angular or Dart: + #performance.l-sub-section + h3 Performance, the transformer, and Angular 2 libraries + p. + When an app imports bootstrap.dart, + it also gets dart:mirrors, + a reflection library that + causes performance problems when compiled to JavaScript. + Don't worry, + the Angular transformer converts the app's entry points + (entry_points in pubspec.yaml) + so that they don't use mirrors. - ul - li - Angular resources - li - dartlang.org + h4#dart_to_js_script_rewriter Using dart_to_js_script_rewriter + + :marked + To improve the app's performance, convert the + HTML file to directly include the generated JavaScript; + one way to do that is with `dart_to_js_script_rewriter`. + To use the rewriter, specify `dart_to_js_script_rewriter` in both + the `dependencies` and `transformers` sections of the pubspec. + + - var stylePattern = { otl: /(dart_to_js_script_rewriter.*$)|(- dart_to_js_script_rewriter.*$)|(dependencies:)|(transformers:)/gm }; + +makeExample('quickstart/dart/pubspec.yaml', null, 'pubspec.yaml', stylePattern) + + .alert.is-important + :marked + The `dart_to_js_script_rewriter` transformer must be + **after** the `angular2` transformer in `pubspec.yaml`. + + :marked + For more information, see the docs for + [dart_to_js_script_rewriter](https://pub.dartlang.org/packages/dart_to_js_script_rewriter). + +block server-watching + :marked + To see the new version, just reload the page. + + .alert.is-important + :marked + Be sure to terminate the `pub serve` process once you stop working on this app. + +block project-file-structure + .filetree + .file angular2-quickstart + .children + .file lib + .children + .file app_component.dart + .file pubspec.yaml + .file web + .children + .file index.html + .file main.dart + .file styles.css + + .l-verbose-section + :marked + This figure doesn't show generated files and directories. + For example, a `pubspec.lock` file + specifies versions and other identifying information for + the packages that our app depends on. + The `pub build` command creates a `build` directory + containing the JavaScript version of our app. + Pub, IDEs, and other tools often create + other directories and dotfiles. + +block project-files + +makeTabs(` + quickstart/ts/app/app.component.ts, + quickstart/ts/app/main.ts, + quickstart/ts/index.html, + quickstart/dart/pubspec.yaml, + quickstart/ts/styles.1.css` + ,null, + `app/app.component.ts, + app/main.ts, + index.html, + pubspec.yaml, + styles.css`) + +block what-next-ts-overhead + //- N/A diff --git a/public/docs/js/latest/_data.json b/public/docs/js/latest/_data.json index 539400f8b1..44be71ef79 100644 --- a/public/docs/js/latest/_data.json +++ b/public/docs/js/latest/_data.json @@ -3,7 +3,7 @@ "icon": "home", "title": "Angular Docs", "menuTitle": "Docs Home", - "banner": "Welcome to Angular in JavaScript! The current Angular 2 release is rc.0. Please consult the Change Log about recent enhancements, fixes, and breaking changes." + "banner": "Welcome to Angular in JavaScript! The current Angular 2 release is rc.1. Please consult the Change Log about recent enhancements, fixes, and breaking changes." }, "quickstart": { diff --git a/public/docs/js/latest/cheatsheet.jade b/public/docs/js/latest/cheatsheet.jade index 4548cf52e0..694e02b0d2 100644 --- a/public/docs/js/latest/cheatsheet.jade +++ b/public/docs/js/latest/cheatsheet.jade @@ -1,6 +1,6 @@ - var base = current.path[4] ? '.' : './guide'; -.banner - p.text-body This cheat sheet is provisional and may change. Angular 2 is currently in Beta. +.banner.grid-fluid + p.text-body.c10 This cheat sheet is provisional and may change. Angular 2 is currently in Beta. article(class="l-content-small grid-fluid docs-content") .cheatsheet diff --git a/public/docs/js/latest/guide/_data.json b/public/docs/js/latest/guide/_data.json index f4f44835c0..62a168eae5 100644 --- a/public/docs/js/latest/guide/_data.json +++ b/public/docs/js/latest/guide/_data.json @@ -99,9 +99,15 @@ "intro": "Pipes transform displayed values within a template." }, + "router-deprecated": { + "title": "Router (Deprecated Beta)", + "intro": "The deprecated Beta Router." + }, + "router": { "title": "Routing & Navigation", - "intro": "Discover the basics of screen navigation with the Angular 2 router." + "intro": "Discover the basics of screen navigation with the Angular 2 router.", + "hide": true }, "structural-directives": { @@ -126,6 +132,12 @@ "intro": "Angular 1 applications can be incrementally upgraded to Angular 2." }, + "webpack": { + "title": "Introduction to Webpack", + "intro": "Create your Angular 2 applications with a Webpack based tooling", + "hide": true + }, + "glossary": { "title": "Glossary", "intro": "Brief definitions of the most important words in the Angular 2 vocabulary", diff --git a/public/docs/js/latest/guide/router-deprecated.jade b/public/docs/js/latest/guide/router-deprecated.jade new file mode 100644 index 0000000000..f8df2a84a6 --- /dev/null +++ b/public/docs/js/latest/guide/router-deprecated.jade @@ -0,0 +1 @@ +!= partial("../../../_includes/_ts-temp") \ No newline at end of file diff --git a/public/docs/js/latest/guide/webpack.jade b/public/docs/js/latest/guide/webpack.jade new file mode 100644 index 0000000000..6778b6af28 --- /dev/null +++ b/public/docs/js/latest/guide/webpack.jade @@ -0,0 +1 @@ +!= partial("../../../_includes/_ts-temp") diff --git a/public/docs/js/latest/quickstart.jade b/public/docs/js/latest/quickstart.jade index 1f32224176..298e9b0946 100644 --- a/public/docs/js/latest/quickstart.jade +++ b/public/docs/js/latest/quickstart.jade @@ -205,7 +205,7 @@ code-example(format=""). :marked The `template` property holds the component's companion template. A template is a form of HTML that tells Angular how to render a view. - Our template is a single line of HTML announcing "My First Angular App". + Our template is a single line of HTML announcing "My First Angular 2 App". Now we need something to tell Angular to load this component. diff --git a/public/docs/ts/latest/_data.json b/public/docs/ts/latest/_data.json index ac22881392..241caa4e64 100644 --- a/public/docs/ts/latest/_data.json +++ b/public/docs/ts/latest/_data.json @@ -3,7 +3,7 @@ "icon": "home", "title": "Angular文档", "menuTitle": "文档首页", - "banner": "欢迎来到 Angular in TypeScript! 当前的Angular版本是 rc.0。请参考Change Log来了解最近的增强、修正和破坏性变更。" + "banner": "欢迎来到 Angular in TypeScript! 当前的Angular版本是 rc.1。请参考变更记录。" }, "quickstart": { diff --git a/public/docs/ts/latest/_util-fns.jade b/public/docs/ts/latest/_util-fns.jade index 63d13cdd4d..5c3d720cf3 100644 --- a/public/docs/ts/latest/_util-fns.jade +++ b/public/docs/ts/latest/_util-fns.jade @@ -1 +1,12 @@ -include ../../../_includes/_util-fns \ No newline at end of file +include ../../../_includes/_util-fns + +//- See the _util-fns file included above for a description of the use of these variables. +- var _docsFor = 'ts'; +//- Other values match the defaults. + +mixin liveExampleLink(linkText, exampleUrlPartName) + a(href='/resources/live-examples/#{exampleUrlPartName}/ts/plnkr.html' target="_blank")= linkText + +mixin liveExampleLink2(linkText, exampleUrlPartName) + //- In Dart this also gives a link to the source. + | #[+liveExampleLink(linkText, exampleUrlPartName)] diff --git a/public/docs/ts/latest/cookbook/component-communication.jade b/public/docs/ts/latest/cookbook/component-communication.jade index 057c4a0b71..5b43ee1622 100644 --- a/public/docs/ts/latest/cookbook/component-communication.jade +++ b/public/docs/ts/latest/cookbook/component-communication.jade @@ -344,12 +344,13 @@ a(id="countdown-tests") 把子组件的视图插入到父组件类需要做一点额外的工作。 We import references to the `ViewChild` decorator and the `AfterViewInit` lifecycle hook. - + 我们需要通过`ViewChild`装饰器导入这个引用,并挂上`AfterViewInit`生命周期钩子。 - We inject the child `CountdownTimerComponent` into the private `_timerComponent` property via the `@ViewChild` property decoration. + We inject the child `CountdownTimerComponent` into the private `timerComponent` property + via the `@ViewChild` property decoration. - 我们通过`@ViewChild`属性装饰器,将子组件`CountdownTimerComponent`注入到私有属性`_timerComponent`里面。 + 我们通过`@ViewChild`属性装饰器,将子组件`CountdownTimerComponent`注入到私有属性`timerComponent`里面。 The `#timer` local variable is gone from the component metadata. Instead we bind the buttons to the parent component's own `start` and `stop` methods and present the ticking seconds in an interpolation around the parent component's `seconds` method. diff --git a/public/docs/ts/latest/cookbook/dependency-injection.jade b/public/docs/ts/latest/cookbook/dependency-injection.jade index f1583cfa10..4ac2f67c5b 100644 --- a/public/docs/ts/latest/cookbook/dependency-injection.jade +++ b/public/docs/ts/latest/cookbook/dependency-injection.jade @@ -321,7 +321,7 @@ figure.image-display 所以,在根部的`AppComponent`提供的依赖单例就能被注入到应用程序中*任何地方*的*任何*组件。 - That isn't always desireable. + That isn't always desirable. Sometimes we want to restrict service availability to a particular region of the application. 但这不一定总是我们想要的。有时候我们想要把服务的有效性限制到应用程序的一个特定区域。 @@ -491,7 +491,7 @@ a(id="qualify-dependency-lookup") +makeExample('cb-dependency-injection/ts/app/hero-bio.component.ts','template','app/hero-bio.component.ts (template)')(format='.') :marked - It looks like this, with the heroe's telephone number from `HeroContactComponent` projected above the hero description: + It looks like this, with the hero's telephone number from `HeroContactComponent` projected above the hero description: 从`HeroContactComponent`获得的英雄电话号码,被投射到上面的英雄描述里,看起来像这样: @@ -510,17 +510,17 @@ figure.image-display +makeExample('cb-dependency-injection/ts/app/hero-contact.component.ts','ctor-params','app/hero-contact.component.ts')(format='.') :marked - The `@Host()` function decorating the `_heroCache` property ensures that + The `@Host()` function decorating the `heroCache` property ensures that we get a reference to the cache service from the parent `HeroBioComponent`. Angular throws if the parent lacks that service, even if a component higher in the component tree happens to have that service. - `@Host()`函数是`_heroCache`属性的装饰器,确保我们从其父组件`HeroBioComponent`得到一个缓存服务。如果该父组件不存在这个服务,Angular就会抛出错误,即使组件树里的再上级有某个组件拥有这个服务,Angular也会抛出错误。 + `@Host()`函数是`heroCache`属性的装饰器,确保我们从其父组件`HeroBioComponent`得到一个缓存服务。如果该父组件不存在这个服务,Angular就会抛出错误,即使组件树里的再上级有某个组件拥有这个服务,Angular也会抛出错误。 - A second `@Host()` function decorates the `_loggerService` property. + A second `@Host()` function decorates the `loggerService` property. We know the only `LoggerService` instance in the app is provided at the `AppComponent` level. The host `HeroBioComponent` doesn't have its own `LoggerService` provider. - 另一个`@Host()`函数是属性`_loggerService`的装饰器,我们知道在应用程序中,只有一个`LoggerService`实例,也就是在`AppComponent`级提供的服务。 + 另一个`@Host()`函数是属性`loggerService`的装饰器,我们知道在应用程序中,只有一个`LoggerService`实例,也就是在`AppComponent`级提供的服务。 该宿主`HeroBioComponent`没有自己的`LoggerService`供应商。 Angular would throw an error if we hadn't also decorated the property with the `@Optional()` function. @@ -544,8 +544,8 @@ figure.image-display :marked If we comment out the `@Host()` decorator, Angular now walks up the injector ancestor tree until it finds the logger at the `AppComponent` level. The logger logic kicks in and the hero display updates - with the gratuituous "!!!", indicating that the logger was found. - + with the gratuitous "!!!", indicating that the logger was found. + 如果我们注释掉`@Host()`装饰器,Angular就会沿着注入器树往上走,直到在`AppComponent`中找到该日志服务。日志服务的逻辑加入进来,更新了英雄的显示信息,这表明确实找到了日志服务。 figure.image-display img(src="/resources/images/cookbooks/dependency-injection/hero-bio-contact-no-host.png" alt="Without @Host") @@ -639,7 +639,7 @@ figure.image-display Where did the injector get that value? It may already have that value in its internal container. - It it doesn't, it may be able to make one with the help of a ***provider***. + If it doesn't, it may be able to make one with the help of a ***provider***. A *provider* is a recipe for delivering a service associated with a *token*. 注入器从哪儿得到的依赖? @@ -1098,9 +1098,9 @@ figure.image-display 我们强烈推荐简单的构造函数。它们应该***只***用来初始化变量。这个规则会帮助我们在测试环境中放心的构造组件,以免在构造它们时,无意做了一些非常戏剧化的动作(比如连接服务)。 这就是为什么我们要在`ngOnInit`里面调用`HeroService`,而不是在构造函数中。 - We explain the mysterious `_afterGetHeroes` below. + We explain the mysterious `afterGetHeroes` below. - 我们在下面解释这个神秘的`_afterGetHeroes`。 + 我们在下面解释这个神秘的`afterGetHeroes`。 :marked Users want to see the heroes in alphabetical order. @@ -1120,7 +1120,7 @@ figure.image-display +makeExample('cb-dependency-injection/ts/app/sorted-heroes.component.ts','sorted-heroes','app/sorted-heroes.component.ts (SortedHeroesComponent)') :marked - Now take note of the `_afterGetHeroes` method. + Now take note of the `afterGetHeroes` method. Our first instinct was to create an `ngOnInit` method in `SortedHeroesComponent` and do the sorting there. But Angular calls the *derived* class's `ngOnInit` *before* calling the base class's `ngOnInit` so we'd be sorting the heroes array *before they arrived*. That produces a nasty error. @@ -1129,9 +1129,9 @@ figure.image-display 我们第一反应是在`SortedHeroesComponent`组件里面建一个`ngOnInit`方法来做排序。但是Angular会先调用*派生*类的`ngOnInit`,后调用基类的`ngOnInit`, 所以我们可能在*英雄到达之前*就开始排序。这就产生了一个讨厌的错误。 - Overriding the base class's `_afterGetHeroes` method solves the problem + Overriding the base class's `afterGetHeroes` method solves the problem - 覆盖基类的`_afterGetHeroes`方法可以解决这个问题。 + 覆盖基类的`afterGetHeroes`方法可以解决这个问题。 These complications argue for *avoiding component inheritance*. diff --git a/public/docs/ts/latest/glossary.jade b/public/docs/ts/latest/glossary.jade index f3522499ab..09b191e405 100644 --- a/public/docs/ts/latest/glossary.jade +++ b/public/docs/ts/latest/glossary.jade @@ -95,8 +95,8 @@ include _util-fns 我们可以在`heroes`目录下添加一个封装桶(按规约叫做`index`),它导出所有这三条: code-example(format=''). - import * from './hero.model.ts'; // re-export all of its exports - import * from './hero.service.ts'; // re-export all of its exports + export * from './hero.model.ts'; // re-export all of its exports + export * from './hero.service.ts'; // re-export all of its exports export { HeroComponent } from './hero.component.ts'; // re-export the named thing :marked Now a consumer can import what it needs from the barrel. @@ -309,8 +309,7 @@ include _util-fns @Component({...}) export class AppComponent { constructor(@Inject('SpecialFoo') public foo:Foo) {} - @Input() - name:string; + @Input() name:string; } ``` @@ -988,7 +987,8 @@ include _util-fns The browser DOM and JavaScript have a limited number of asynchronous activities, activities such as DOM events (e.g., clicks), - [promises](#promise), and + [promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ + Promise), and [XHR](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) calls to remote servers. diff --git a/public/docs/ts/latest/guide/_data.json b/public/docs/ts/latest/guide/_data.json index 7d18c40b07..40ec6ee038 100644 --- a/public/docs/ts/latest/guide/_data.json +++ b/public/docs/ts/latest/guide/_data.json @@ -99,9 +99,16 @@ "intro": "管道可以在模板中转换显示的内容。" }, + + "router-deprecated": { + "title": "Router (Deprecated Beta)", + "intro": "The deprecated Beta Router." + }, + "router": { "title": "路由与导航", "intro": "揭示通过Angular 2路由在屏幕上导航的基本原理。" + "hide": true }, "structural-directives": { @@ -124,6 +131,11 @@ "intro": "Angular 1应用可以逐步升级到Angular 2。" }, + "webpack": { + "title": "Introduction to Webpack", + "intro": "Create your Angular 2 applications with a Webpack based tooling" + }, + "glossary": { "title": "词汇表", "intro": "Angular 2重要词汇的简短定义。", diff --git a/public/docs/ts/latest/guide/attribute-directives.jade b/public/docs/ts/latest/guide/attribute-directives.jade index 4c250509cc..f5194ad229 100644 --- a/public/docs/ts/latest/guide/attribute-directives.jade +++ b/public/docs/ts/latest/guide/attribute-directives.jade @@ -1,4 +1,5 @@ -include ../_util-fns +block includes + include ../_util-fns :marked An **Attribute** directive changes the appearance or behavior of a DOM element. @@ -9,19 +10,18 @@ include ../_util-fns In this chapter we will 本章中我们将: - * write an attribute directive to change the background color - * 写一个用来改变背景色的Attribute型指令 - * apply the attribute directive to an element in a template - * 把这个Attribute型指令应用到模板中的元素 - * respond to user-initiated events - * 响应用户引发的事件 - * pass values into the directive using data binding - * 使用数据绑定把值传到指令中 - - [Live Example](/resources/live-examples/attribute-directives/ts/plnkr.html) - - [在线例子](/resources/live-examples/attribute-directives/ts/plnkr.html) + * [write an attribute directive to change the background color](#write-directive) + * [写一个用来改变背景色的Attribute型指令](#write-directive) + * [apply the attribute directive to an element in a template](#apply-directive) + * [把这个Attribute型指令应用到模板中的元素](#apply-directive) + * [respond to user-initiated events](#respond-to-user) + * [响应用户引发的事件](#respond-to-user) + * [pass values into the directive using data binding](#bindings) + * [使用数据绑定把值传到指令中](#bindings) +p. + #[+liveExampleLink2('Live example', 'attribute-directives')]. +:marked ## Directives overview ## 指令概览 @@ -35,20 +35,20 @@ include ../_util-fns 1. Attribute directives 1. Attribute型指令 - The *Component* is really a directive with a template. - It's the most common of the three directives and we write lots of them as we build our application. - + A *Component* is really a directive with a template. + It's the most common of the three directives and we tend to write lots of them as we build applications. + *组件*其实是一个带模板的指令。 它是这三种指令中最常用的,我们在构建应用程序时会写大量组件。 - The [*Structural* directive](structural-directives.html) changes the DOM layout by adding and removing DOM elements. - [NgFor](template-syntax.html#ng-for) and [NgIf](template-syntax.html#ng-if) are two familiar examples. + [*Structural* directives](structural-directives.html) can change the DOM layout by adding and removing DOM elements. + [NgFor](template-syntax.html#ngFor) and [NgIf](template-syntax.html#ngIf) are two familiar examples. [*结构型*指令](structural-directives.html)会通过添加/删除DOM元素来更改DOM树布局。 [NgFor](template-syntax.html#ng-for)和[NgIf](template-syntax.html#ng-if)就是两个最熟悉的例子。 - The *Attribute* directive changes the appearance or behavior of an element. - The built-in [NgStyle](template-syntax.html#ng-style) directive, for example, + An *Attribute* directive can change the appearance or behavior of an element. + The built-in [NgStyle](template-syntax.html#ngStyle) directive, for example, can change several element styles at the same time. *Attribute型*指令改变一个元素的外观或行为。 @@ -65,9 +65,8 @@ include ../_util-fns 其实我们并不需要*任何*指令来设置背景色。 我们可以通过[样式绑定](template-syntax.html#style-binding)来设置它,就像这样: - code-example. - <p [style.background]="'lime'">I am green with envy!</p> -
    + +makeExample('attribute-directives/ts/app/app.component.1.html','p-style-background') + :marked That wouldn't be nearly as much fun as creating our own directive. @@ -79,15 +78,16 @@ include ../_util-fns 我们不仅要*设置*颜色,还要响应用户的动作(鼠标悬浮),来*修改*这个颜色。 .l-main-section +a#write-directive :marked ## Build a simple attribute directive ## 创建一个简单的Attribute型指令 - An attribute directive minimally requires building a controller class annotated with a - `Directive` decorator. The `Directive` decorator specifies the selector identifying + An attribute directive minimally requires building a controller class annotated with + `@Directive`, which specifies the selector identifying the attribute associated with the directive. The controller class implements the desired directive behavior. - Attribute型指令至少需要一个带有`Directive`装饰器的控制器类。`Directive`装饰器指定了一个选择器,用于指出与此指令相关的Attribute。 + Attribute型指令至少需要一个带有`@Directive`装饰器的控制器类。该装饰器指定了一个选择器,用于指出与此指令相关的Attribute。 控制器类实现了指令需要具备的行为。 Let's build a small illustrative example together. @@ -103,31 +103,34 @@ include ../_util-fns include ../_quickstart_repo :marked - Add a new file to the `app` folder called `highlight.directive.ts` and add the following code: + Create the following source file in the indicated folder with the given code: - 在`app`文件夹中创建一个名叫`highlight.directive.ts`的文件,并且添加下列代码: + 在指定的文件夹下创建下列源码文件: +makeExample('attribute-directives/ts/app/highlight.directive.1.ts', null, 'app/highlight.directive.ts') +block highlight-directive-1 + :marked + We begin by importing some symbols from the Angular `core`. + We need the `Directive` symbol for the `@Directive` decorator. + We need the `ElementRef` to [inject](dependency-injection.html) into the directive's constructor + so we can access the DOM element. + We don't need `Input` immediately but we will need it later in the chapter. + + 我们先从Angular库中导入一些符号。 + 我们要为使用`@Directive`装饰器而导入`Directive`。 + 我们要为[注入](dependency-injection.html)到指令的构造函数中而导入`ElementRef`,这样我们才能访问DOM元素。 + 虽然眼下还不需要`Input`,但在稍后的章节中我们很快就会用到它。 + + Then we define the directive metadata in a configuration object passed + as an argument to the `@Directive` decorator function. + + 然后,我们通过给`@Directive`装饰器函数传入一个“配置对象”来定义指令的元数据。 :marked - We begin by importing some symbols from the Angular library. - We need the `Directive` symbol for the `@Directive` decorator. - We need the `ElementRef` to [inject](dependency-injection.html) into the directive's constructor - so we can access the DOM element. - We don't need `Input` immediately but we will need it later in the chapter. - - 我们先从Angular库中导入一些符号。 - 我们要为使用`@Directive`装饰器而导入`Directive`。 - 我们要为[注入](dependency-injection.html)到指令的构造函数中而导入`ElementRef`,这样我们才能访问DOM元素。 - 虽然眼下还不需要`Input`,但在稍后的章节中我们很快就会用到它。 - - Then we define the directive metadata in a configuration object passed - as an argument to the `@Directive` decorator function. A `@Directive` decorator for an attribute directive requires a css selector to identify the HTML in the template that is associated with our directive. - The [css selector for an attribute](https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors) + The [CSS selector for an attribute](https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors) is the attribute name in square brackets. - - 然后,我们通过给`@Directive`装饰器函数传入一个“配置对象”来定义指令的元数据。 + Attribute型指令的`@Directive`装饰器需要一个css选择器,以便从模板中识别出关联到我们这个指令的HTML。 [css中的attribute选择器](https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors)就是Attribute名称加方括号。 @@ -151,23 +154,23 @@ include ../_quickstart_repo 当我们使用自己的前缀时,也会减少和第三方指令发生命名冲突的风险。 We do **not** prefix our `highlight` directive name with **`ng`**. - That prefix belongs to Angular and - we don't want to confuse our directives with their directives. + That prefix belongs to Angular. 我们**不能**给自己的`highlight`指令添加**`ng`**前缀。 - 那个前缀属于Angular,我们肯定不会希望自己的指令和内建指令相混淆。 + 那个前缀属于Angular。 We need a prefix of our own, preferably short, and `my` will do for now. - 我们需要一个自己的前缀,最好短点儿,所以用`my`就不错。 - + 我们需要一个自己的前缀,最好短点儿,目前用的这个`my`前缀就不错。 +p + | After the `@Directive` metadata comes the directive's controller class, which contains the logic for the directive. + +ifDocsFor('ts') + | We export `HighlightDirective` to make it accessible to other components. +p + | `@Directive`元数据的后面就是指令的控制器类,它包括了指令的工作逻辑。 + +ifDocsFor('ts') + | 我们导出`HighlightDirective`以便让它可以被其他组件访问。 :marked - After the `@Directive` metadata comes the directive's controller class which we are exporting - to make it accessible to other components. - The directive's controller class contains the logic for the directive. - - 在`@Directive`元数据的后面,是指令的控制器类,我们导出它,以便让它能被其它组件访问。类里的代码就是指令的逻辑。 - Angular creates a new instance of the directive's controller class for each matching element, injecting an Angular `ElementRef` into the constructor. @@ -182,21 +185,26 @@ include ../_quickstart_repo 我们所要做的,就是使用浏览器的DOM API来设置这个元素的背景色。 .l-main-section +a#apply-directive :marked ## Apply the attribute directive ## 应用Attribute型指令 The `AppComponent` in this sample is a test harness for our `HighlightDirective`. Let's give it a new template that - applies the directive as an attribute to a `span` element. - In Angular terms, the `` element will be the attribute **host**. + applies the directive as an attribute to a paragraph (`p`) element. + In Angular terms, the `

    ` element will be the attribute **host**. 这个例子中的`AppComponent`只是我们用来测试`HighlightDirective`的一个壳儿。 - 我们来给它一个新的模板,把这个指令作为Attribute应用到一个`span`元素上。 - 用Angular的话说,``元素就是这个Attribute型指令的**宿主**。 - - We'll put the template in its own `app.component.html` file that looks like this: - - 我们把这个模板放到它自己的`app.component.html`文件中,就像这样: + 我们来给它一个新的模板,把这个指令作为Attribute应用到一个段落(`p`)元素上。 + 用Angular的话说,`

    `元素就是这个Attribute型指令的**宿主**。 +p + | We'll put the template in its own + code #[+adjExPath('app.component.html')] + | file that looks like this: +p + | 我们把这个模板放到自己的 + code #[+adjExPath('app.component.html')] + | 文件中,就像这样: +makeExample('attribute-directives/ts/app/app.component.1.html',null,'app/app.component.html')(format=".") :marked A separate template file is clearly overkill for a 2-line template. @@ -208,14 +216,14 @@ include ../_quickstart_repo 同时,我们要修改`AppComponent`,使其引用这个模板。 +makeExample('attribute-directives/ts/app/app.component.ts',null,'app/app.component.ts') :marked - We've added an `import` statement to fetch the 'Highlight' directive and - added that class to a `directives` array in the component metadata so that Angular + We've added an `import` statement to fetch the 'Highlight' directive and, + added that class to a `directives` component metadata so that Angular will recognize our directive when it encounters `myHighlight` in the template. 我们添加了一个`import`语句来获得'Highlight'指令类,并把这个类添加到`AppComponent`组件的`directives`数组中。 这样,当Angular在模板中遇到`myHighlight`时,就能认出这是我们的指令了。 - We run the app and see that our directive highlights the span text. + We run the app and see that our directive highlights the paragraph text. 运行应用,就会看到我们的指令确实高亮了span中的文本。 @@ -223,19 +231,19 @@ figure.image-display img(src="/resources/images/devguide/attribute-directives/first-highlight.png" alt="First Highlight") .l-sub-section :marked - #### Why isn't my directive working? - #### 为什么我的指令不能工作? + ### Your directive isn't working? + ### 你的指令没生效? - Did you remember to set the `directives` array? It is easy to forget! + Did you remember to set the `directives` attribute of `@Component`? It is easy to forget! 你记着设置`directives`数组了吗?它很容易被忘掉。 Open the console in the browser tools and look for an error like this: 打开浏览器调试工具的控制台,会看到像这样的错误信息: - code-example.format(""). + code-example(format="nocode"). EXCEPTION: Template parse errors: - Can't bind to 'myHighlight' since it isn't a known native property + Can't bind to 'myHighlight' since it isn't a known native property :marked Angular detects that we're trying to bind to *something* but it doesn't know what. We have to tell it by listing `HighlightDirective` in the `directives` metadata array. @@ -247,23 +255,24 @@ figure.image-display 我们来概括一下发生了什么。 - Angular found the `myHighlight` attribute on the `` element. It created + Angular found the `myHighlight` attribute on the `

    ` element. It created an instance of the `HighlightDirective` class, injecting a reference to the element into the constructor - where we set the `` element's background style to yellow. + where we set the `

    ` element's background style to yellow. - Angular在``元素上发现了一个`myHighlight`属性。 + Angular在`

    `元素上发现了一个`myHighlight`属性。 然后它创建了一个`HighlightDirective`类的实例,并把所在元素的引用注入到了指令的构造函数中。 - 在构造函数中,我们把``元素的背景设置为了黄色。 + 在构造函数中,我们把`

    `元素的背景设置为了黄色。 .l-main-section +a#respond-to-user :marked ## Respond to user action ## 响应用户的操作 We are not satisfied to simply set an element color. Our directive should set the color in response to a user action. - Specifically, we want to set the color when the user mouses over the element. + Specifically, we want to set the color when the user hovers over an element. 我们不能满足于设置元素的颜色。 我们的指令设置颜色是要用来响应用户的操作。 @@ -272,28 +281,27 @@ figure.image-display We'll need to 我们需要: - 1. detect when the user mouses into and out of the element + 1. detect when the user hovers into and out of the element, 1. 检测用户的鼠标啥时候进入和离开这个元素。 - 1. respond to those actions by setting and clearing the highlight color. - 1. 通过设置和清除背景颜色来响应这些操作。 + 1. respond to those actions by setting and clearing the highlight color, respectively. + 1. 通过设置和清除高亮的颜色来响应这些操作。 - Start with event detection. - We add a `host` property to the directive metadata and give it a configuration object - that specifies two mouse events and the directive methods to call when they are raised. - - 从事件检测开始。 + Let's start with event detection. + Add a `host` property to the directive metadata and give it a configuration object + that specifies two mouse events and the directive methods to call when they are raised: + + 从事件检测开始吧。 我们把`host`属性加入指令的元数据中,并给它一个配置对象,用来指定两个鼠标事件,并在它们被触发时,调用指令中的方法。 +makeExample('attribute-directives/ts/app/highlight.directive.2.ts','host')(format=".") -:marked + .l-sub-section :marked - The `host` property refers to the DOM element that hosts our attribute directive, the `` in our case. + The `host` property refers to the DOM element that hosts our attribute directive, the `

    ` in our case. - `host`属性引用的是我们这个Attribute指令的宿主元素,在这个例子中就是``。 + `host`属性引用的是我们这个Attribute指令的宿主元素,在这个例子中就是`

    `。 - We could have attached an event listener to the native element (`el.nativeElement`) with - plain old JavaScript. - There are at least three problems with that approach: + We could have attached event listeners by manipulating the host DOM element directly, but + there are at least three problems with such an approach: 我们可以通过老旧的JavaScript方式来给这个原生元素(`el.nativeElement`)挂上一个事件监听器。 但这种方法至少有三个问题: @@ -308,16 +316,16 @@ figure.image-display 我们还是围绕`host`属性来吧。 :marked - Now we implement those two mouse event handlers: + Now we implement the two mouse event handlers: 现在,我们实现那两个鼠标事件处理器: +makeExample('attribute-directives/ts/app/highlight.directive.2.ts','mouse-methods')(format=".") :marked - Notice that they delegate to a helper method that sets the color via a private local variable, `_el`. - We revise the constructor to capture the `ElementRef.nativeElement` in `_el`. - - 注意,它们把处理逻辑委托给了一个辅助方法,这个方法会通过一个私有变量`_el`来设置颜色。 - 我们要修改构造函数,来把`ElementRef.nativeElement`存进私有变量`_el`。 + Notice that they delegate to a helper method that sets the color via a private local variable, `#{_priv}el`. + We revise the constructor to capture the `ElementRef.nativeElement` in this variable. + + 注意,它们把处理逻辑委托给了一个辅助方法,这个方法会通过一个私有变量`#{_priv}el`来设置颜色。 + 我们要修改构造函数,来把`ElementRef.nativeElement`存进这个私有变量。 +makeExample('attribute-directives/ts/app/highlight.directive.2.ts','ctor')(format=".") :marked @@ -326,24 +334,24 @@ figure.image-display 这里是更新过的指令: +makeExample('attribute-directives/ts/app/highlight.directive.2.ts',null, 'app/highlight.directive.ts') :marked - We run the app and confirm that the background color appears as we move the mouse over the `span` and + We run the app and confirm that the background color appears as we move the mouse over the `p` and disappears as we move out. 运行本应用,我们就可以确认:当把鼠标移到`span`上的时候,背景色就出现了,而移开的时候,它消失了。 figure.image-display img(src="/resources/images/devguide/attribute-directives/highlight-directive-anim.gif" alt="Second Highlight") -:marked .l-main-section +a#bindings :marked ## Configure the directive with binding ## 通过绑定来配置指令 Currently the highlight color is hard-coded within the directive. That's inflexible. - We should set the highlight color externally with a binding like this: - + We should set the color externally with a binding like this: + 现在的高亮颜色是在指令中硬编码进去的。这样没有弹性。 我们应该通过绑定从外部设置这个高亮颜色。就像这样: -+makeExample('attribute-directives/ts/app/app.component.html','span') ++makeExample('attribute-directives/ts/app/app.component.html','pHost') :marked We'll extend our directive class with a bindable **input** `highlightColor` property and use it when we highlight text. @@ -354,17 +362,17 @@ figure.image-display 这里是该类的最终版: +makeExample('attribute-directives/ts/app/highlight.directive.ts', 'class-1', 'app/highlight.directive.ts (class only)') - +a#input :marked - The new `highlightColor` property is called an "input" property because data flows from the binding expression into our directive. - Notice that we call the `@Input()` decorator function while defining the property. - + The new `highlightColor` property is called an *input* property because data flows from the binding expression into our directive. + Notice the `@Input()` #{_decorator} applied to the property. + 新的`highlightColor`属性被称为“输入”属性,这是因为数据流是从绑定表达式到这个指令的。 - 注意,我们在定义这个属性的时候,调用了`@Input()`装饰器函数。 + 注意,我们在定义这个属性的时候,调用了`@Input()`#{_decoratorCn}。 +makeExample('attribute-directives/ts/app/highlight.directive.ts', 'color') :marked - This `@Input` decorator adds metadata to the class that makes the `highlightColor` property available for property binding - under the `myHighlight` alias. + `@Input` adds metadata to the class that makes the `highlightColor` property available for + property binding under the `myHighlight` alias. We must add this input metadata or Angular will reject the binding. See the [appendix](#why-input) below to learn why. @@ -373,33 +381,32 @@ figure.image-display 参见下面的[附录](#why-input)来了解为何如此。 .l-sub-section :marked - ### @Input(alias) - ### @Input(别名) - The developer who uses our directive expects to bind to the attribute name, `myHighlight`. + ### @Input(_alias_) + ### @Input(_别名_) + The developer who uses this directive expects to bind to the attribute name, `myHighlight`. The directive property name is `highlightColor`. That's a disconnect. 使用我们这个指令的开发人员会期望绑定到Attribute名`myHighlight`上, 而指令中的属性名是`highlightColor`。两者联系不起来。 - We can resolve the discrepancy by renaming the property to `myHighlight` and define it as follows: + We could resolve the discrepancy by renaming the property to `myHighlight` and define it as follows: 我们固然可以通过把属性名改为`myHighlight`来解决这个矛盾,就像这样: +makeExample('attribute-directives/ts/app/highlight.directive.ts', 'highlight') -
    :marked Maybe we don't want that property name inside the directive perhaps because it doesn't express our intention well. We can **alias** the `highlightColor` property with the attribute name by - passing `myHighlight` into the `@Input` decorator: + passing `myHighlight` into the `@Input` #{_decorator}: 但我们可能在指令中不想要那样一个属性名,因为它不能很好的表示我们的意图。 - 我们可以通过把`myHighlight`传给`@Input`装饰器来把这个Attribute名字作为`highlightColor`属性的别名。 + 我们可以通过把`myHighlight`传给`@Input`#{_decoratorCn}来把这个Attribute名字作为`highlightColor`属性的别名。 +makeExample('attribute-directives/ts/app/highlight.directive.ts', 'color') :marked Now that we're getting the highlight color as an input, we modify the `onMouseEnter()` method to use it instead of the hard-coded color name. - We also define a red default color as a fallback in case + We also define red as the default color to fallback on in case the user neglects to bind with a color. 现在,我们通过输入型属性得到了高亮的颜色,然后修改`onMouseEnter()`来使用它代替我们硬编码的那个颜色名。 @@ -461,7 +468,7 @@ figure.image-display 我们的指令只有一个可定制属性,如果有***两个***呢? - Let's let the template developer set the default color, the color that prevails until the user picks a highlight color. + Let's allow the template developer to set the default color, the color that prevails until the user picks a highlight color. We'll add a second **input** property to `HighlightDirective` called `defaultColor`: 我们要让模板开发者设置一个默认颜色,直到用户选择了一个高亮颜色才失效。 @@ -508,17 +515,17 @@ figure.image-display :marked ## Summary ## 总结 - Now we know how to - + We now know how to + 现在,我们知道了该如何: - - build a simple **attribute directive** to attach behavior to an HTML element, - - 构建一个简单的**Attribute型指令**来为一个HTML元素添加行为, - - use that directive in a template, - - 在模板中使用那个指令, - - respond to **events** to change behavior based on an event, - - 响应**事件**,以便基于事件改变行为。 - - and use **binding** to pass values to the attribute directive. - - 以及使用**绑定**来把值传给Attribute型指令。 + - [build a simple **attribute directive** to attach behavior to an HTML element](#write-directive), + - [构建一个简单的**Attribute型指令**来为一个HTML元素添加行为](#write-directive), + - [use that directive in a template](#apply-directive), + - [在模板中使用那个指令](#apply-directive), + - [respond to **events** to change behavior based on an event](#respond-to-user), + - [响应**事件**,以便基于事件改变行为](#respond-to-user), + - and [use **binding** to pass values to the attribute directive](#bindings). + - 以及[使用**绑定**来把值传给Attribute型指令](#bindings)。 The final source: @@ -539,7 +546,7 @@ figure.image-display `) - +a#why-input .l-main-section :marked ### Appendix: Input properties @@ -570,7 +577,7 @@ figure.image-display 如果它出现在了**方括号**([ ])中,并且出现在等号(=)的**左侧**,它就是一个*目标*…… 就像在我们绑定到`HighlightDirective`的`myHighlight`属性时所做的那样。 -+makeExample('attribute-directives/ts/app/app.component.html','span')(format=".") ++makeExample('attribute-directives/ts/app/app.component.html','pHost')(format=".") :marked The 'color' in `[myHighlight]="color"` is a binding ***source***. A source property doesn't require a declaration. diff --git a/public/docs/ts/latest/guide/component-styles.jade b/public/docs/ts/latest/guide/component-styles.jade index 6a71bc3af5..3b58a1ec86 100644 --- a/public/docs/ts/latest/guide/component-styles.jade +++ b/public/docs/ts/latest/guide/component-styles.jade @@ -1,4 +1,5 @@ -include ../_util-fns +block includes + include ../_util-fns :marked Angular 2 applications are styled with regular CSS. That means we can apply @@ -14,13 +15,13 @@ include ../_util-fns * [Using Component Styles](#using-component-styles) * [Special selectors](#special-selectors) - * [Loading Styles into Components](#loading-style) - * [Controlling View Encapsulation: Emulated, Native, and None](#controlling-view-encapsulation-native-emulated-and-none) + * [Loading Styles into Components](#loading-styles) + * [Controlling View Encapsulation: Emulated, Native, and None](#view-encapsulation) * [Appendix 1: Inspecting the generated runtime component styles](#inspect-generated-css) * [Appendix 2: Loading Styles with Relative URLs](#relative-urls) - - **[Run the live code](/resources/live-examples/component-styles/ts/plnkr.html) - shown in this chapter.** +p + | #[+liveExampleLink2('Run the live example', 'component-styles')]  + | of the code shown in this chapter. .l-main-section :marked @@ -31,7 +32,7 @@ include ../_util-fns specifying any selectors, rules, and media queries that we need. One way to do this is to set the `styles` property in the component metadata. - The `styles` property takes an array of strings that contain CSS code. + The `styles` property takes #{_an_array} of strings that contain CSS code. Usually we give it one string as in this example: +makeExample('component-styles/ts/app/hero-app.component.ts')(format='.') @@ -39,8 +40,8 @@ include ../_util-fns :marked Component styles differ from traditional, global styles in a couple of ways. - Firstly, the selectors we put into a component's styles *only apply withing the template - of that component*. The `h1 { }` selector in the example above only applies to the `

    ` tag + Firstly, the selectors we put into a component's styles *only apply within the template + of that component*. The `h1` selector in the example above only applies to the `

    ` tag in the template of `HeroAppComponent`. Any `

    ` elements elsewhere in the application are unaffected. @@ -65,7 +66,7 @@ a(id="special-selectors") ## Special selectors Component styles have a few special *selectors* from the world of - shadow DOM style scoping. + [shadow DOM style scoping](https://www.w3.org/TR/css-scoping-1): ### :host @@ -122,7 +123,7 @@ a(id="special-selectors") :marked The `/deep/` and `>>>` selectors should only be used with **emulated** view encapsulation. This is the default and it is what we use most of the time. See the - [Controlling View Encapsulation](#controlling-view-encapsulation-native-emulated-and-none) + [Controlling View Encapsulation](#view-encapsulation) section for more details. a(id='loading-styles') @@ -139,8 +140,8 @@ a(id='loading-styles') ### Styles in Metadata - We can add a `styles` array property to the `@Component` decorator. - Each string in the array (usually just one string) defines the css. + We can add a `styles` #{_array} property to the `@Component` #{_decorator}. + Each string in the #{_array} (usually just one string) defines the CSS. +makeExample('component-styles/ts/app/hero-app.component.ts') @@ -156,37 +157,42 @@ a(id='loading-styles') ### Style URLs in Metadata We can load styles from external CSS files by adding a `styleUrls` attribute - into a component's `@Component` or `@View` decorator: + into a component's `@Component` or `@View` #{_decorator}: +makeExample('component-styles/ts/app/hero-details.component.ts', 'styleurls') - -.alert.is-important - :marked - The URL is ***relative to the application root*** which is usually the - location of the `index.html` web page that hosts the application. - The style file URL is *not* relative to the component file. - That's why the example URL begins `app/`. - See [Appendix 2](#relative-urls) to specify a URL relative to the component file. - -.l-sub-section - :marked - Users of module bundlers like Webpack may also use the `styles` attribute to load - styles from external files at build time. They could write: - - `styles: [require('my.component.css')]` - We set the `styles` property, **not** `styleUrls` property! The module bundler is loading the CSS strings, not Angular. - Angular only sees the CSS strings *after* the bundler loads them. To Angular it is as if - we wrote the `styles` array by hand. - Refer to the module bundler's documentation for information on loading CSS in this manner. +block style-url + .alert.is-important + :marked + The URL is ***relative to the application root*** which is usually the + location of the `index.html` web page that hosts the application. + The style file URL is *not* relative to the component file. + That's why the example URL begins `app/`. + See [Appendix 2](#relative-urls) to specify a URL relative to the + component file. + +block module-bundlers + .l-sub-section + :marked + Users of module bundlers like Webpack may also use the `styles` attribute + to load styles from external files at build time. They could write: + + `styles: [require('my.component.css')]` + + We set the `styles` property, **not** `styleUrls` property! The module + bundler is loading the CSS strings, not Angular. + Angular only sees the CSS strings *after* the bundler loads them. + To Angular it is as if we wrote the `styles` array by hand. + Refer to the module bundler's documentation for information on + loading CSS in this manner. :marked ### Template Link Tags We can also embed `` tags into the component's HTML template. - As with `styleUrls`, the link tag's `href` URL is relative to the HTML host page of the application, - not relative to the component file. + As with `styleUrls`, the link tag's `href` URL is relative to the + application root, not relative to the component file. +makeExample('component-styles/ts/app/hero-team.component.ts', 'stylelink') @@ -196,10 +202,13 @@ a(id='loading-styles') We can also import CSS files into our CSS files by using the standard CSS [`@import` rule](https://developer.mozilla.org/en/docs/Web/CSS/@import). - In *this* case the URL is relative to the CSS file into which we are importing. +block css-import-url + :marked + In *this* case the URL is relative to the CSS file into which we are importing. +makeExample('component-styles/ts/app/hero-details.component.css', 'import', 'app/hero-details.component.css (excerpt)') - + +a#view-encapsulation .l-main-section :marked ## Controlling View Encapsulation: Native, Emulated, and None @@ -227,13 +236,14 @@ a(id='loading-styles') Set the components encapsulation mode using the `encapsulation` property in the component metadata: +makeExample('component-styles/ts/app/quest-summary.component.ts', 'encapsulation.native')(format='.') + :marked `Native` view encapsulation only works on [browsers that have native support for Shadow DOM](http://caniuse.com/#feat=shadowdom). The support is still limited, which is why `Emulated` view encapsulation is the default mode and recommended in most cases. -a(id="inspect-generated-css") +a#inspect-generated-css .l-main-section :marked ## Appendix 1: Inspecting The CSS Generated in Emulated View Encapsulation @@ -283,7 +293,7 @@ code-example(format=""). We'll likely live with *emulated* mode until shadow DOM gains traction. -a(id="relative-urls") +a#relative-urls .l-main-section :marked ## Appendix 2: Loading Styles with Relative URLs @@ -294,54 +304,63 @@ code-example(format=''). quest-summary.component.ts quest-summary.component.html quest-summary.component.css + :marked We include the template and CSS files by setting the `templateUrl` and `styleUrls` metadata properties respectively. Because these files are co-located with the component, it would be nice to refer to them by name without also having to specify a path back to the root of the application. - - We'd *prefer* to write this: -+makeExample('component-styles/ts/app/quest-summary.component.ts', 'urls')(format='.') -:marked - We can't do that by default. Angular can't find the files and throws an error: - `EXCEPTION: Failed to load quest-summary.component.html` - - Why can't Angular calculate the HTML and CSS URLs from the component file's location? - - Unfortunately, that location is not readily known. - Angular apps can be loaded in many ways: from individual files, from SystemJS packages, or - from CommonJS packages, to name a few. - With this diversity of load strategies, it's not easy to tell at runtime where these files actually reside. - - The only location Angular can be sure of is the URL of the `index.html` home page. - So by default it resolves template and style paths relative to the URL of `index.html`. - That's why we previously wrote our CSS file URLs with an `app/` base path prefix. - - Although this works with any code loading scheme, it is very inconvenient. - We move file folders around all the time during the evolution of our applications. - It's no fun patching the style and template URLs when we do. - - ### *moduleId* - - We can change the way Angular calculates the full URL be setting the component metadata's `moduleId` property. - - If we knew the component file's base path, we'd set `moduleId` to that and - let Angular construct the full URL from this base path plus the CSS and template file names. - - Our challenge is to calculate the base path with minimal effort. - If it's too hard, we shouldn't bother; we should just write the full path to the root and move on. - - Fortunately, *certain* module loaders make it easy. - SystemJS (starting in v.0.19.19) sets a special `__moduleName` variable to the URL of the component file. -.alert.is-important +block module-id :marked - Caution: we currently regard the *__moduleName* feature as experimental. -:marked - Now it's trivial to set the `moduleId` to the `__moduleName` and write module-relative paths for style and template URLs. - -+makeExample('component-styles/ts/app/quest-summary.component.ts','', 'app/quest-summary.component.ts') + We'd *prefer* to write this: + + +makeExample('component-styles/ts/app/quest-summary.component.ts', 'urls')(format='.') -.l-sub-section :marked - With a module bundler like Webpack we are more likely to set the `styles` and `template` properties with the bundler's - `require` mechanism rather than bother with `styleUrls` and `templateUrl`. + We can't do that by default. Angular can't find the files and throws an error: + + `EXCEPTION: Failed to load quest-summary.component.html` + + Why can't Angular calculate the HTML and CSS URLs from the component file's location? + + Unfortunately, that location is not readily known. + Angular apps can be loaded in many ways: from individual files, from SystemJS packages, or + from CommonJS packages, to name a few. + With this diversity of load strategies, it's not easy to tell at runtime where these files actually reside. + + The only location Angular can be sure of is the URL of the `index.html` home page. + So by default it resolves template and style paths relative to the URL of `index.html`. + That's why we previously wrote our CSS file URLs with an `app/` base path prefix. + + Although this works with any code loading scheme, it is very inconvenient. + We move file folders around all the time during the evolution of our applications. + It's no fun patching the style and template URLs when we do. + + ### *moduleId* + + We can change the way Angular calculates the full URL be setting the component metadata's `moduleId` property. + + If we knew the component file's base path, we'd set `moduleId` to that and + let Angular construct the full URL from this base path plus the CSS and template file names. + + Our challenge is to calculate the base path with minimal effort. + If it's too hard, we shouldn't bother; we should just write the full path to the root and move on. + Fortunately, *certain* module loaders make it relatively easy to find the base path. + + SystemJS (starting in v.0.19.19) sets a *semi-global* variable to the URL of the component file. + That makes it trivial to set the component metadata `moduleId` property to the component's URL + and let Angular determine the module-relative paths for style and template URLs from there. + + The name of the *semi-global* variable depends upon whether we told TypeScript to transpile to + 'system' or 'commonjs' format (see the `module` option in the + [TypeScript compiler documentation](http://www.typescriptlang.org/docs/handbook/compiler-options.html)). + The variables are `__moduleName` and `module.id` respectively. + + Here's an example in which we set the metadata `moduleId` to `module.id`. + + +makeExample('component-styles/ts/app/quest-summary.component.ts','', 'app/quest-summary.component.ts') + + .l-sub-section + :marked + With a module bundler like Webpack we are more likely to set the `styles` and `template` properties with the bundler's + `require` mechanism rather than bother with `styleUrls` and `templateUrl`. diff --git a/public/docs/ts/latest/guide/dependency-injection.jade b/public/docs/ts/latest/guide/dependency-injection.jade index 50e0a7de15..c5a32936f7 100644 --- a/public/docs/ts/latest/guide/dependency-injection.jade +++ b/public/docs/ts/latest/guide/dependency-injection.jade @@ -604,7 +604,7 @@ include ../_util-fns app/heroes/hero.service (v.1)`) // #docregion di-service-service-2 :marked - The constructor now asks for an injected instance of a `Logger` and stores it in a private property called `_logger`. + The constructor now asks for an injected instance of a `Logger` and stores it in a private property called `logger`. We call that property within our `getHeroes` method when anyone asks for heroes. 现在,这个构造函数会要求一个`Logger`类的实例注入进来,并且把它存到一个名为`_logger`的私有属性中。 @@ -786,11 +786,11 @@ code-example(format, language="html"). - var decorator = lang == 'dart' ? 'annotation' : 'decorator' - var decoratorCn = lang == 'dart' ? '注解' : '装饰器' :marked - #{rewrite} the constructor with the `@Optional()` #{decorator} preceding the private `_logger` parameter. - That tells the injector that `_logger` is optional. - - #{rewriteCn}使用`@Optional`#{decoratorCn}前缀重写构造函数的`private _logger`参数就可以了。 - 它就会告诉注入器`_logger`是可选的。 + #{rewrite} the constructor with the `@Optional()` #{decorator} preceding the private `logger` parameter. + That tells the injector that `logger` is optional. + + #{rewriteCn}使用`@Optional`#{decoratorCn}前缀重写构造函数的`private logger`参数就可以了。 + 它就会告诉注入器`logger`是可选的。 // #enddocregion logger-service-5 +makeExample('dependency-injection/ts/app/providers.component.ts','provider-10-ctor')(format='.') diff --git a/public/docs/ts/latest/guide/displaying-data.jade b/public/docs/ts/latest/guide/displaying-data.jade index 9ce1ac4226..765c524ee1 100644 --- a/public/docs/ts/latest/guide/displaying-data.jade +++ b/public/docs/ts/latest/guide/displaying-data.jade @@ -19,12 +19,26 @@ include ../_util-fns 最终的UI是这样的: figure.image-display - img(src="/resources/images/devguide/displaying-data/final.png" alt="最终的UI") - -:marked - [Run the live example](/resources/live-examples/displaying-data/ts/plnkr.html) + img(src="/resources/images/devguide/displaying-data/final.png" alt="Final UI") - [运行在线例子](/resources/live-examples/displaying-data/ts/plnkr.html) +:marked + # Table Of Contents + # 目录 + + * [Showing component properties with interpolation](#interpolation) + * [通过插值表达式显示组件的属性](#interpolation) + * [Showing an array property with NgFor](#ngFor) + * [通过NgFor显示数组型属性](#ngFor) + * [Conditional display with NgIf](#ngIf) + * [通过NgIf实现按条件显示](#ngIf) + +.l-sub-section + :marked + The [live example](/resources/live-examples/displaying-data/ts/plnkr.html) + demonstrates all of the syntax and code snippets described in this chapter. + + 这个[在线例子](/resources/live-examples/displaying-data/ts/plnkr.html) + 演示了本章中描述的所有语法和代码片段。 .l-main-section diff --git a/public/docs/ts/latest/guide/forms.jade b/public/docs/ts/latest/guide/forms.jade index 382481df61..269010591b 100644 --- a/public/docs/ts/latest/guide/forms.jade +++ b/public/docs/ts/latest/guide/forms.jade @@ -875,7 +875,7 @@ figure.image-display 一致性统治一切! Now we can control visibility of the "name" error message by binding properties of the `name` control to the message `
    ` element's `hidden` property. - + 现在,通过把`div`元素的`hidden`属性绑定到`name`控件的属性,我们就可以控制“姓名”字段错误信息的可见性了。 +makeExample('forms/ts/app/hero-form.component.html', diff --git a/public/docs/ts/latest/guide/hierarchical-dependency-injection.jade b/public/docs/ts/latest/guide/hierarchical-dependency-injection.jade index 97afced3f5..72f6b2bf74 100644 --- a/public/docs/ts/latest/guide/hierarchical-dependency-injection.jade +++ b/public/docs/ts/latest/guide/hierarchical-dependency-injection.jade @@ -12,10 +12,8 @@ block includes interesting and useful results. In this chapter we explore these points and write some code. - -block liveExample - :marked - [Live Example](/resources/live-examples/hierarchical-dependency-injection/ts/plnkr.html). +p + | Try the #[+liveExampleLink2('live example', 'hierarchical-dependency-injection')]. .l-main-section :marked @@ -64,11 +62,11 @@ figure.image-display .l-sub-section :marked - There's a third possibililty. An intermediate component can declare that it is the "host" component. + There's a third possibility. An intermediate component can declare that it is the "host" component. The hunt for providers will climb no higher than the injector for this host component. We'll reserve discussion of this option for another day. :marked - Such a proliferation of injectors makes little sense until we consider the possiblity that injectors at different levels can be + Such a proliferation of injectors makes little sense until we consider the possibility that injectors at different levels can be configured with different providers. We don't *have* to re-configure providers at every level. But we *can*. If we don't re-configure, the tree of injectors appears to be flat. All requests bubble up to the root injector that we @@ -84,7 +82,7 @@ figure.image-display Behind the scenes each component sets up its own injector with one or more providers defined for that component itself. When we resolve an instance of `Car` at the deepest component (C), - it's injector produces an instance of `Car` resolved by injector (C) with an `Engine` resolved by injector (B) and + its injector produces an instance of `Car` resolved by injector (C) with an `Engine` resolved by injector (B) and `Tires` resolved by the root injector (A). figure.image-display @@ -96,7 +94,7 @@ figure.image-display In the previous section, we talked about injectors and how they are organized like a tree. Lookups follow the injector tree upwards until they find the requested thing to inject. But when do we actually want to provide providers on the root injector and when do we want to provide them on a child injector? - Consider you are building a component to show a list of super heroes that displays each super hero in a card with it’s name and superpower. There should also be an edit button that opens up an editor to change the name and superpower of our hero. + Consider you are building a component to show a list of super heroes that displays each super hero in a card with its name and superpower. There should also be an edit button that opens up an editor to change the name and superpower of our hero. One important aspect of the editing functionality is that we want to allow multiple heroes to be in edit mode at the same time and that one can always either commit or cancel the proposed changes. @@ -127,16 +125,16 @@ figure.image-display +makeExample('hierarchical-dependency-injection/ts/app/hero-editor.component.ts', null, 'app/hero-editor.component.ts') :marked - Now here it’s getting interesting. The `HeroEditorComponent`defines a template with an input to change the name of the hero and a `cancel` and a `save` button. Remember that we said we want to have the flexibility to cancel our editing and restore the old value? This means we need to maintain two copies of our `Hero` that we want to edit. Thinking ahead this is a perfect use case to abstract it into it’s own generic service since we have probably more cases like this in our app. + Now here it’s getting interesting. The `HeroEditorComponent`defines a template with an input to change the name of the hero and a `cancel` and a `save` button. Remember that we said we want to have the flexibility to cancel our editing and restore the old value? This means we need to maintain two copies of our `Hero` that we want to edit. Thinking ahead, this is a perfect use case to abstract it into its own generic service since we have probably more cases like this in our app. And this is where the `RestoreService` enters the stage. +makeExample('hierarchical-dependency-injection/ts/app/restore.service.ts', null, 'app/restore.service.ts') :marked - All this tiny service does is define an API to set a value of any type which can be altered, retrieved or set back to it’s initial value. That’s exactly what we need to implement the desired functionality. + All this tiny service does is define an API to set a value of any type which can be altered, retrieved or set back to its initial value. That’s exactly what we need to implement the desired functionality. - Our `HeroEditComponent` uses this services under the hood for it’s `hero` property. It intercepts the `get` and `set` method to delegate the actual work to our `RestoreService` which in turn makes sure that we won’t work on the original item but on a copy instead. + Our `HeroEditComponent` uses this services under the hood for its `hero` property. It intercepts the `get` and `set` method to delegate the actual work to our `RestoreService` which in turn makes sure that we won’t work on the original item but on a copy instead. At this point we may be scratching our heads asking what this has to do with component injectors? Look closely at the metadata for our `HeroEditComponent`. Notice the `providers` property. @@ -148,7 +146,7 @@ figure.image-display +makeExample('hierarchical-dependency-injection/ts/app/main.ts', 'bad-alternative') :marked - Technically we could, but our component wouldn’t quite behave the way it is supposed to. Remember that each injector treats the services that it provides as singletons. However, in order to be able to have multiple instances of `HeroEditComponent` edit multiple heroes at the same time we need to have multiple instances of the `RestoreService`. More specifically each instance of `HeroEditComponent` needs to be bound to it’s own instance of the `RestoreService`. + Technically we could, but our component wouldn’t quite behave the way it is supposed to. Remember that each injector treats the services that it provides as singletons. However, in order to be able to have multiple instances of `HeroEditComponent` edit multiple heroes at the same time we need to have multiple instances of the `RestoreService`. More specifically, each instance of `HeroEditComponent` needs to be bound to its own instance of the `RestoreService`. By configuring a provider for the `RestoreService` on the `HeroEditComponent`, we get exactly one new instance of the `RestoreService`per `HeroEditComponent`. diff --git a/public/docs/ts/latest/guide/index.jade b/public/docs/ts/latest/guide/index.jade index 168c56aa05..a910e4b1f2 100644 --- a/public/docs/ts/latest/guide/index.jade +++ b/public/docs/ts/latest/guide/index.jade @@ -1,4 +1,5 @@ -include ../_util-fns +block includes + include ../_util-fns // #docregion intro - var langName = current.path[1] == 'ts' ? 'TypeScript' : 'JavaScript' @@ -34,15 +35,21 @@ table(width="100%") col(width="15%") col tr(style=top) + td + p QuickStart + p 快速起步 + td + :marked + The foundation for every chapter and sample in this documentation. + + 本文档中每一个章节和范例的基础工作。 + td p Tutorial p 教程 td :marked - A step-by-step, immersive approach to learning Angular. - It begins with the [QuickStart](../quickstart.html), - the foundation for every chapter and sample in this documentation, - followed by the [*Tour of Heroes* tutorial](../tutorial) that + A step-by-step, immersive approach to learning Angular that introduces the major features of Angular in an application context. 一场按部就班、沉浸式的Angular学习之旅。 @@ -63,7 +70,7 @@ table(width="100%") p 开发人员指南 td :marked - In depth analysis of Angular features and development practices. + In-depth analysis of Angular features and development practices. 深入分析Angular的特性和开发实践。 tr(style=top) @@ -77,59 +84,49 @@ table(width="100%") 一组解决实际应用中某些特定挑战的食谱,大部分是代码片段,也有少量的详细阐述。 tr(style=top) td - p Reference - p 参考 + p API Reference + p API 参考 td :marked - Angular-specific reference material, most notably the [API Guide](../api) - with its authoritative details about each member in the Angular libraries. + Authoritative details about each member of the Angular libraries. - 特定于Angular的参考资料,最受欢迎的[API 指南](../api),包括Angular库中每一个成员的详尽、权威的资料。 - tr(style=top) - td - p Resources - p 资源 - td - :marked - Other places to go for help and information. - - 可以获得帮助、获取消息的其它地方。 + 关于Angular库中每一个成员的详尽、权威的资料。 :marked # Learning Path # 学习路径 - We don't have to read the guide straight through. Most chapters stand on their own. + We don't have to read the guide straight through. Most chapters stand on their own. 我们并不需要从头到尾依次阅读本指南。大部分章节都是独立的。 - We recommend a learning path for those new to Angular. + We recommend a learning path for those new to Angular. Most of that path runs through the *Basics* section: 这里我们只给Angular新手推荐一个学习路径。 此路径上的大部分文章都在*基础知识*区。 - 1. Read the [Architecture Overview](architecture.html) to get the big picture. + 1. Read the [Architecture](architecture.html) overview to get the big picture. 1. 阅读[架构概览](architecture.html)以获得宏观视图。 - 1. Try the [QuickStart](../quickstart.html). The QuickStart is the "Hello, World" of Angular 2. - It shows us how to setup the libraries and tools we'll need to write *any* Angular app. - + 1. Try the [QuickStart](../quickstart.html). The QuickStart is the "Hello, World" of Angular 2. + It shows us how to set up the libraries and tools we'll need to write *any* Angular app. + 1. 试用[“快速起步”](../quickstart.html)。“快速起步”是Angular 2世界中的“Hello, World”。 它会告诉我们如何安装写*任何*Angular应用时都会用到的那些库和工具。 - 1. Take the *Tour of Heroes* [Tutorial](../tutorial) which picks up from where the QuickStart leaves off - and builds a simple data-driven app. + 1. Take the *Tour of Heroes* [Tutorial](../tutorial), which picks up from where the QuickStart leaves off + and builds a simple data-driven app. Simple, yes, but with the essential characteristics we'd expect of a professional application: - a sensible project structure, data binding, master/detail, services, dependency injection, navigation, and remote data access. - + a sensible project structure, data binding, master/detail, services, dependency injection, navigation, and remote data access. + 1. 学习*英雄指南*[教程](../tutorial) ,它将从“快速起步”出发,最终构建出一个简单的“数据驱动”的应用。 它虽简单,但也具有我们写一个专业应用时所需的一切基本特性: 实用的项目结构、数据绑定、主从视图、服务、依赖注入、导航,以及远程数据访问。 Return to the *Basics* section and continue in the suggested order: - + 返回*基础知识*区,继续按建议的顺序前进: - + 1. [Displaying Data](displaying-data.html) explains how to get information on to the screen. 1. [显示数据](displaying-data.html)解释了如何把信息显示到屏幕上。 @@ -147,7 +144,7 @@ table(width="100%") 1. [依赖注入](dependency-injection.html)这种方式,让我们能把小型、单一用途的部件组装成大型、可维护的应用。 - 1. [Template Syntax](template-syntax.html) is a comprehensive study of Angular template HTML. + 1. [Template Syntax](template-syntax.html) is a comprehensive study of Angular template HTML. 1. [模板语法](template-syntax.html)是对Angular模板HTML的全面讲解。 @@ -160,34 +157,36 @@ table(width="100%") # Code Samples # 代码范例 - Every chapter includes code snippets that we can reuse in our own applications. + Every chapter includes code snippets that we can reuse in our own applications. These snippets are excerpts from a sample application that accompanies the chapter. - + 每一章都包含一些能在我们自己的应用中复用的代码片段。 这些片段节选自那一章附带的范例应用。 - - Look for a link to a running version of that sample near the top of each page - such as this [live example](/resources/live-examples/architecture/ts/plnkr.html) from the [Architecture](architecture.html) chapter. - - 在每页靠近顶部的地方都可以看到一个链接,指向这个范例的可执行版本,比如[架构](architecture.html)一章中的[在线例子](/resources/live-examples/architecture/ts/plnkr.html)。 - - The link launches a browser-based code editor where we can inspect, modify, save, and download the code. - - 这个链接启动一个基于浏览器的代码编辑器,在这里,我们可以调试、修改、保存和下载这些代码。 - - A few early chapters are written as tutorials and are clearly marked as such. - Most chapters are *not* tutorials. + +block example-links + :marked + Look for a link to a running version of that sample near the top of each page, + such as this [live example](/resources/live-examples/architecture/ts/plnkr.html) from the [Architecture](architecture.html) chapter. + + 在每页靠近顶部的地方都可以看到一个链接,指向这个范例的可执行版本,比如[架构](architecture.html)一章中的[在线例子](/resources/live-examples/architecture/ts/plnkr.html)。 + + The link launches a browser-based code editor where we can inspect, modify, save, and download the code. + + 这个链接启动一个基于浏览器的代码编辑器,在这里,我们可以调试、修改、保存和下载这些代码。 +:marked + A few early chapters are written as tutorials and are clearly marked as such. + Most chapters are *not* tutorials. They highlight key points in code rather than explain each step necessary to build the sample. - We can always get the full source by way of the live link. + We can always get the full source by way of the #{_liveLink}. 少量早期章节是作为教程来写的,并被清晰的标注出来。 但大部分章节都不在教程中。 它们的目的是展示代码中的关键点,而不是解释构建这个范例所需的每一个步骤。 我们可以从在线例子的链接找到完整的源代码。 + + # Reference pages + # 参考资料 - ## References - ## 参考资料 - The [Cheat Sheet](cheatsheet.html) lists Angular syntax for common scenarios. [小抄](cheatsheet.html)列出了Angular在常见场景下的语法。 @@ -196,22 +195,22 @@ table(width="100%") [词汇表](glossary.html)定义了Angular开发者需要知道的词汇。 - The [API Guide](../api/) is the authority on every public-facing member of the Angular libraries. + The [API Reference](../api/) is the authority on every public-facing member of the Angular libraries. [API指南](../api/)是关于Angular库中每一个公有成员的权威指南。 - + # Feedback # 提供反馈 - + We welcome feedback! Leave a comment by clicking the icon in upper right corner of the banner. 我们期待您的反馈!请点击Banner右上角的图标,给我们留言。 - Post *documentation* issues and pull requests on the + Post *documentation* issues and pull requests on the [angular.io](https://github.com/angular/angular.io) github repository. 如果有*文档方面*的问题或Pull Requests,请到Github上的[angular.io](https://github.com/angular/angular.io)仓库。 - + Post issues with *Angular 2 itself* to the [angular](https://github.com/angular/angular) github repository. 如果有*Angular 2本身*的问题,请到Github上的[angular](https://github.com/angular/angular)仓库。 diff --git a/public/docs/ts/latest/guide/lifecycle-hooks.jade b/public/docs/ts/latest/guide/lifecycle-hooks.jade index b373d638ac..903160ca97 100644 --- a/public/docs/ts/latest/guide/lifecycle-hooks.jade +++ b/public/docs/ts/latest/guide/lifecycle-hooks.jade @@ -1,4 +1,5 @@ -include ../_util-fns +block includes + include ../_util-fns - var top="vertical-align:top" @@ -22,14 +23,10 @@ include ../_util-fns * [DoCheck](#docheck) * [AfterViewInit and AfterViewChecked](#afterview) * [AfterContentInit and AfterContentChecked](#aftercontent) - - Try the [Live Example](/resources/live-examples/lifecycle-hooks/ts/plnkr.html) - +p Try the #[+liveExampleLink2('live example', 'lifecycle-hooks')]. -a(id="hooks-overview") +a#hooks-overview .l-main-section :marked ## Component lifecycle Hooks @@ -37,7 +34,7 @@ a(id="hooks-overview") as Angular creates, updates, and destroys them. Developers can tap into key moments in that lifecycle by implementing - one or more of the *Lifecycle Hook* interfaces in the `angular2/core` library. + one or more of the *Lifecycle Hook* interfaces in the Angular `core` library. Each interface has a single hook method whose name is the interface name prefixed with `ng`. For example, the `OnInit` interface has a hook method named `ngOnInit`. @@ -45,24 +42,23 @@ a(id="hooks-overview") +makeExample('lifecycle-hooks/ts/app/peek-a-boo.component.ts', 'ngOnInit', 'peek-a-boo.component.ts (excerpt)')(format='.') :marked No directive or component will implement all of them and some of the hooks only make sense for components. - Angular only calls a directive/component hook method *if it is defined*. +block optional-interfaces + .l-sub-section + :marked + ### Interface optional? + The interfaces are optional for JavaScript and Typescript developers from a purely technical perspective. + The JavaScript language doesn't have interfaces. + Angular can't see TypeScript interfaces at runtime because they disappear from the transpiled JavaScript. -.l-sub-section - :marked - ### Interface optional? - The interfaces are optional for JavaScript and Typescript developers from a purely technical perspective. - The JavaScript language doesn't have interfaces. - Angular can't see TypeScript interfaces at runtime because they disappear from the transpiled JavaScript. + Fortunately, they aren't necessary. + We don't have to add the lifecycle hook interfaces to our directives and components to benefit from the hooks themselves. - Fortunately, they aren't necessary. - We don't have to add the lifecycle hook interfaces to our directives and components to benefit from the hooks themselves. + Angular instead inspects our directive and component classes and calls the hook methods *if they are defined*. + Angular will find and call methods like `ngOnInit()`, with or without the interfaces. - Angular instead inspects our directive and component classes and calls the hook methods *if they are defined*. - Angular will find and call methods like `ngOnInit()`, with or without the interfaces. - - Nonetheless, we strongly recommend adding interfaces to TypeScript directive classes - in order to benefit from strong typing and editor tooling. + Nonetheless, we strongly recommend adding interfaces to TypeScript directive classes + in order to benefit from strong typing and editor tooling. :marked Here are the component lifecycle hook methods: @@ -189,7 +185,7 @@ a(id="other-lifecycles") :marked ## Other lifecycle hooks - Other Angular sub-system may have their own lifecycle hooks apart from the component hooks we've listed. + Other Angular sub-systems may have their own lifecycle hooks apart from the component hooks we've listed. The router, for instance, also has it's own [router lifecycle hooks](router.html#router-lifecycle-hooks) that allow us to tap into specific moments in route navigation. @@ -199,15 +195,14 @@ a(id="other-lifecycles") 3rd party libraries might implement their hooks as well in order to give us, the developers, more control over how these libraries are used. -a(id="the-sample") +a#the-sample .l-main-section -:marked - ## Lifecycle exercises - - The [live example](/resources/live-examples/lifecycle-hooks/ts/plnkr.html) +h2 Lifecycle exercises +p. + The #[+liveExampleLink('live example', 'lifecycle-hooks')] demonstrates the lifecycle hooks in action through a series of exercises presented as components under the control of the root `AppComponent`. - +:marked They follow a common pattern: a *parent* component serves as a test rig for a *child* component that illustrates one or more of the lifecycle hook methods. @@ -246,7 +241,7 @@ table(width="100%") td DoCheck td :marked - Implements a `ngDoCheck` method with custom change detection. + Implements an `ngDoCheck` method with custom change detection. See how often Angular calls this hook and watch it post changes to a log. tr(style=top) td AfterView @@ -299,7 +294,7 @@ figure.image-display We log in it to confirm that input properties (the `name` property in this case) have no assigned values at construction. :marked Had we clicked the *Update Hero* button, we'd have seen another `OnChanges` and two more triplets of - `DoCheck, `AfterContentChecked` and `AfterViewChecked`. + `DoCheck`, `AfterContentChecked` and `AfterViewChecked`. Clearly these three hooks fire a *lot* and we must keep the logic we put in these hooks as lean as possible! @@ -338,7 +333,7 @@ figure.image-display We can apply the spy to any native or component element and it'll be initialized and destroyed at the same time as that element. Here we attach it to the repeated hero `
    ` -+makeExample('lifecycle-hooks/ts/app/spy.component.ts', 'template')(format=".") ++makeExample('lifecycle-hooks/ts/app/spy.component.html', 'template')(format=".") :marked Each spy's birth and death marks the birth and death of the attached hero `
    ` @@ -457,7 +452,7 @@ figure.image-display The `ngDoCheck` hook is called with enormous frequency — after _every_ change detection cycle no matter where the change occurred. - It's called over twenty time in this example before the user can do anything. + It's called over twenty times in this example before the user can do anything. Most of these initial checks are triggered by Angular's first rendering of *unrelated data elsewhere on the page*. Mere mousing into another input box triggers a call. @@ -466,14 +461,14 @@ figure.image-display .l-sub-section :marked - We see also that the `ngOnChanges` method is called in contradiction of the + We also see that the `ngOnChanges` method is called in contradiction of the [incorrect API documentation](../api/core/DoCheck-interface.html). .l-main-section :marked ## AfterView The *AfterView* sample explores the `AfterViewInit` and `AfterViewChecked` hooks that Angular calls - *after* Angular creates a component's child views. + *after* it creates a component's child views. Here's a child view that displays a hero's name in an input box: +makeExample('lifecycle-hooks/ts/app/after-view.component.ts', 'child-view', 'ChildComponent')(format=".") @@ -489,19 +484,22 @@ figure.image-display .a(id="wait-a-tick") :marked ### Abide by the unidirectional data flow rule - The `_doSomething` method updates the screen when the hero name exceeds 10 characters. + The `doSomething` method updates the screen when the hero name exceeds 10 characters. -+makeExample('lifecycle-hooks/ts/app/after-view.component.ts', 'do-something', 'AfterViewComponent (_doSomething)')(format=".") ++makeExample('lifecycle-hooks/ts/app/after-view.component.ts', 'do-something', 'AfterViewComponent (doSomething)')(format=".") :marked - Why does the `_doSomething` method waits a tick w/ `setTimeout` before updating `comment`? + Why does the `doSomething` method wait a tick before updating `comment`? - We must adhere to Angular's unidirectional data flow rule which says that + Because we must adhere to Angular's unidirectional data flow rule which says that we may not update the view *after* it has been composed. Both hooks fire after the component's view has been composed. Angular throws an error if we update component's data-bound `comment` property immediately (try it!). - The `setTimeout` postpones the update one turn of the of the browser's JavaScript cycle ... and that's long enough. +block tick-methods + :marked + The `LoggerService.tick` methods, which are implemented by a call to `setTimeout`, postpone the update one turn of the of the browser's JavaScript cycle ... and that's long enough. +:marked Here's *AfterView* in action figure.image-display img(src='/resources/images/devguide/lifecycle-hooks/after-view-anim.gif' alt="AfterView") @@ -531,23 +529,23 @@ figure.image-display the `AfterContentComponent`'s parent. Here's the parent's template. +makeExample('lifecycle-hooks/ts/app/after-content.component.ts', 'parent-template', 'AfterContentParentComponent (template excerpt)')(format=".") :marked - Notice that the `` tag is tucked between the `` tags. + Notice that the `` tag is tucked between the `` tags. We never put content between a component's element tags *unless we intend to project that content into the component*. Now look at the component's template: +makeExample('lifecycle-hooks/ts/app/after-content.component.ts', 'template', 'AfterContentComponent (template)')(format=".") :marked - The `` tags are the *placeholder* for the external content. + The `` tag is a *placeholder* for the external content. They tell Angular where to insert that content. - In this case, the projected content is the `` from the parent. + In this case, the projected content is the `` from the parent. figure.image-display img(src='/resources/images/devguide/lifecycle-hooks/projected-child-view.png' width="230" alt="Projected Content") :marked .l-sub-section :marked The tell-tale signs of *content projection* are (a) HTML between component element tags - and (b) the presence of `` tags in the component's template. + and (b) the presence of `` tags in the component's template. :marked ### AfterContent hooks *AfterContent* hooks are similar to the *AfterView* hooks. The key difference is the kind of child component @@ -568,7 +566,7 @@ figure.image-display :marked ### No unidirectional flow worries - This component's `_doSomething` method update's the component's data-bound `comment` property immediately. + This component's `doSomething` method update's the component's data-bound `comment` property immediately. There's no [need to wait](#wait-a-tick). Recall that Angular calls both *AfterContent* hooks before calling either of the *AfterView* hooks. diff --git a/public/docs/ts/latest/guide/npm-packages.jade b/public/docs/ts/latest/guide/npm-packages.jade index e7e9e002db..2ae1b9fa33 100644 --- a/public/docs/ts/latest/guide/npm-packages.jade +++ b/public/docs/ts/latest/guide/npm-packages.jade @@ -19,10 +19,10 @@ include ../_util-fns (b) they include everything we'll need to build and run the sample applications in this documentation series. .l-sub-section :marked - *Almost* everything. A cookbook or guide chapter may require an additional library such *jQuery*. + *Almost* everything. A cookbook or guide chapter may require an additional library such as *jQuery*. :marked This is far more than we need for QuickStart. - In deed, it's more than we need for most applications. + Indeed, it's more than we need for most applications. There is no harm in installing more than we need. We only serve to the client those packages that the application actually requests. @@ -103,7 +103,7 @@ a(id="polyfills") :marked See "[Why peerDependencies?](#why-peer-dependencies)" below for background on this requirement. :marked - ***es6-shim*** - monkey patches the global context (window) with essential features of ES2016 (ES6). + ***es6-shim*** - monkey patches the global context (window) with essential features of ES2015 (ES6). Developers may substitute an alternative polyfill that provides the same core APIs. This dependency should go away once these APIs are implemented by all supported ever-green browsers. @@ -126,7 +126,7 @@ a(id="other") :marked ### Other helper libraries - ***angular2-in-memory-web-api*** - An Angular-supported library that simulates a remote servers web api + ***angular2-in-memory-web-api*** - An Angular-supported library that simulates a remote server's web api without requiring an actual server or real http calls. Good for demos, documentation samples, and early stage development (before we even have a server). Learn about it in the [Http Client](server-communication.html#appendix-tour-of-heroes-in-memory-server) chapter. diff --git a/public/docs/ts/latest/guide/pipes.jade b/public/docs/ts/latest/guide/pipes.jade index 0116e3e841..4fa76296bc 100644 --- a/public/docs/ts/latest/guide/pipes.jade +++ b/public/docs/ts/latest/guide/pipes.jade @@ -1,23 +1,23 @@ -include ../_util-fns +block includes + include ../_util-fns + :marked Every application starts out with what seems like a simple task: get data, transform them, and show them to users. - Getting data could be as simple as creating a local variable or as complex as streaming data over a Websocket. - Once data arrive, we could push their raw `toString` values directly to screen. + Once data arrive, we could push their raw `toString` values directly to the view. That rarely makes for a good user experience. - Almost everyone prefers a simple birthday date - (April 15, 1988) to the original raw string format - ( Fri Apr 15 1988 00:00:00 GMT-0700 (Pacific Daylight Time) ). + E.g., almost everyone prefers a simple birthday date like + April 15, 1988 to the original raw string format + — Fri Apr 15 1988 00:00:00 GMT-0700 (Pacific Daylight Time). Clearly some values benefit from a bit of massage. We soon discover that we desire many of the same transformations repeatedly, both within and across many applications. We almost think of them as styles. In fact, we'd like to apply them in our HTML templates as we do styles. - +p. Welcome, Angular pipes, the simple display-value transformations that we can declare in our HTML! - - [Live Example](/resources/live-examples/pipes/ts/plnkr.html). + Try the #[+liveExampleLink2('live example', 'pipes')]. .l-main-section :marked @@ -26,11 +26,14 @@ include ../_util-fns A pipe takes in data as input and transforms it to a desired output. We'll illustrate by transforming a component's birthday property into a human-friendly date: + +makeExample('pipes/ts/app/hero-birthday1.component.ts', null, 'app/hero-birthday1.component.ts')(format='.') :marked Focus on the component's template. + +makeExample('pipes/ts/app/app.component.html', 'hero-birthday-template')(format=".") + :marked Inside the interpolation expression we flow the component's `birthday` value through the [pipe operator](./template-syntax.html#pipe) ( | ) to the [Date pipe](../api/common/DatePipe-class.html) @@ -39,26 +42,27 @@ include ../_util-fns .l-main-section :marked ## Built-in pipes - Angular comes with a stock set of pipes such as + Angular comes with a stock of pipes such as `DatePipe`, `UpperCasePipe`, `LowerCasePipe`, `CurrencyPipe`, and `PercentPipe`. They are all immediately available for use in any template. + .l-sub-section :marked Learn more about these and many other built-in pipes in the the [API Reference](../api/#!?apiFilter=pipe); filter for entries that include the word "pipe". - Angular 2 doesn't have a `FilterPipe` or an `OrderByPipe` for reasons explained in an [appendix below](#no-filter-pipe) + Angular 2 doesn't have a `FilterPipe` or an `OrderByPipe` for reasons explained in an [appendix below](#no-filter-pipe). .l-main-section :marked ## Parameterizing a Pipe - A pipe may accept any number of optional parameters to fine-tune its output. + A pipe may accept any number of optional parameters to fine-tune its output. We add parameters to a pipe by following the pipe name with a colon ( : ) and then the parameter value (e.g., `currency:'EUR'`). If our pipe accepts multiple parameters, we separate the values with colons (e.g. `slice:1:5`) We'll modify our birthday template to give the date pipe a format parameter. - After formatting the hero's April 15th birthday should display as **04/15/88**. + After formatting the hero's April 15th birthday, it should render as **04/15/88**. +makeExample('pipes/ts/app/app.component.html', 'format-birthday')(format=".") @@ -70,16 +74,20 @@ include ../_util-fns Let's write a second component that *binds* the pipe's format parameter to the component's `format` property. Here's the template for that component: + +makeExample('pipes/ts/app/hero-birthday2.component.ts', 'template', 'app/hero-birthday2.component.ts (template)')(format=".") + :marked - We also added a button to the template and bound its click event to the component's `toggleFormat` method. + We also added a button to the template and bound its click event to the component's `toggleFormat()` method. That method toggles the component's `format` property between a short form - ('shortDate') and a longer form ('fullDate'). + (`'shortDate'`) and a longer form (`'fullDate'`). + +makeExample('pipes/ts/app/hero-birthday2.component.ts', 'class', 'app/hero-birthday2.component.ts (class)')(format='.') + :marked As we click the button, the displayed date alternates between - "**04/15/1988**" and - "**Friday, April 15, 1988**". + "**04/15/1988**" and + "**Friday, April 15, 1988**". figure.image-display img(src='/resources/images/devguide/pipes/date-format-toggle-anim.gif' alt="Date Format Toggle") @@ -88,52 +96,48 @@ figure.image-display .l-sub-section :marked Learn more about the `DatePipes` format options in the [API Docs](../api/common/DatePipe-class.html). + :marked ## Chaining pipes + We can chain pipes together in potentially useful combinations. In the following example, we chain the birthday to the `DatePipe` and on to the `UpperCasePipe` so we can display the birthday in uppercase. The following birthday displays as - **APR 15, 1988** + **APR 15, 1988** +makeExample('pipes/ts/app/app.component.html', 'chained-birthday')(format=".") :marked - If we pass a parameter to a filter, we have to add parentheses - to help the template compiler with the evaluation order. - The following example displays - **FRIDAY, APRIL 15, 1988** + This example — which displays **FRIDAY, APRIL 15, 1988** — + chains the same pipes as above, but passes in a parameter to `date` as well. +makeExample('pipes/ts/app/app.component.html', 'chained-parameter-birthday')(format=".") -:marked - We can add parentheses to alter the evaluation order or - to provide extra clarity: -+makeExample('pipes/ts/app/app.component.html', 'chained-parameter-birthday-parens')(format=".") - .l-main-section :marked ## Custom Pipes We can write our own custom pipes. - Here's a custom pipe named `ExponentialStrengthPipe` that can boost a hero's powers: +makeExample('pipes/ts/app/exponential-strength.pipe.ts', null, 'app/exponential-strength.pipe.ts')(format=".") + :marked This pipe definition reveals several key points * A pipe is a class decorated with pipe metadata. * The pipe class implements the `PipeTransform` interface's `transform` method that - accepts an input value and an optional array of parameters and returns the transformed value. + accepts an input value followed by optional parameters and returns the transformed value. - * There will be one item in the parameter array for each parameter passed to the pipe + * There will be one additional argument to the `transform` method for each parameter passed to the pipe. + Our pipe has one such parameter: the `exponent`. * We tell Angular that this is a pipe by applying the - `@Pipe` decorator which we import from the core Angular library. + `@Pipe` #{_decorator} which we import from the core Angular library. - * The `@Pipe` decorator takes an object with a name property whose value is the - pipe name that we'll use within a template expression. It must be a valid JavaScript identifier. + * The `@Pipe` #{_decorator} allows us to define the + pipe name that we'll use within template expressions. It must be a valid JavaScript identifier. Our pipe's name is `exponentialStrength`. .l-sub-section @@ -154,20 +158,23 @@ figure.image-display Two things to note: 1. We use our custom pipe the same way we use the built-in pipes. - 1. We must list our pipe in the `pipes` array of the `@Component` decorator. + 1. We must include our pipe in the `pipes` #{_array} of the `@Component` #{_decorator}. .callout.is-helpful - header Remember the pipes array! + header Remember the pipes #{_array}! :marked Angular reports an error if we neglect to list our custom pipe. We didn't list the `DatePipe` in our previous example because all Angular built-in pipes are pre-registered. Custom pipes must be registered manually. -:marked - If we try the [live code](/resources/live-examples/pipes/ts/plnkr.html) example, + +p. + If we try the #[+liveExampleLink('live code', 'pipes')] example, we can probe its behavior by changing the value and the optional exponent in the template. +:marked ## Power Boost Calculator (extra-credit) + It's not much fun updating the template to test our custom pipe. We could upgrade the example to a "Power Boost Calculator" that combines our pipe and two-way data binding with `ngModel`. @@ -178,29 +185,34 @@ figure.image-display img(src='/resources/images/devguide/pipes/power-boost-calculator-anim.gif' alt="Power Boost Calculator") .l-main-section -a(id="change-detection") +a#change-detection :marked ## Pipes and Change Detection + Angular looks for changes to data-bound values through a *change detection* process that runs after every JavaScript event: - every keystroke, mouse move, timer tick, and server response. It could be expensive. + every keystroke, mouse move, timer tick, and server response. This could be expensive. Angular strives to lower the cost whenever possible and appropriate. Angular picks a simpler, faster change detection algorithm when we use a pipe. Let's see how. ### No pipe + The component in our next example uses the default, aggressive change detection strategy to monitor and update - its display of every hero in the `heroes` array. Here's the template: + its display of every hero in the `heroes` #{_array}. Here's the template: + +makeExample('pipes/ts/app/flying-heroes.component.html', 'template-1', 'app/flying-heroes.component.html (v1)')(format='.') + :marked - The companion component class provides heroes, pushes new heroes into the array, and can reset the array. + The companion component class provides heroes, adds new heroes into the #{_array}, and can reset the #{_array}. +makeExample('pipes/ts/app/flying-heroes.component.ts', 'v1', 'app/flying-heroes.component.ts (v1)')(format='.') + :marked We can add a new hero and Angular updates the display when we do. - The `reset` button replaces `heroes` with a new array of the original heroes and Angular updates the display when we do. - If we added the ability to remove or change a hero, Angular would detect those changes too and update the display again. - add or remove heroes. It updates the display when we modify a hero. + The `reset` button replaces `heroes` with a new #{_array} of the original heroes and Angular updates the display when we do. + If we added the ability to remove or change a hero, Angular would detect those changes too and update the display as well. ### Flying Heroes pipe + Let's add a `FlyingHeroesPipe` to the `*ngFor` repeater that filters the list of heroes to just those heroes who can fly. +makeExample('pipes/ts/app/flying-heroes.component.html', 'template-flying-heroes', 'app/flying-heroes.component.html (flyers)')(format='.') :marked @@ -217,25 +229,24 @@ a(id="change-detection") Look at how we're adding a new hero: +makeExample('pipes/ts/app/flying-heroes.component.ts', 'push')(format='.') :marked - We're pushing the new hero into the `heroes` array. The object reference to the array hasn't changed. - It's the same array. That's all Angular cares about. From its perspective, *same array, no change, no display update*. + We're adding the new hero into the `heroes` #{_array}. The reference to the #{_array} hasn't changed. + It's the same #{_array}. That's all Angular cares about. From its perspective, *same #{_array}, no change, no display update*. - We can fix that. Let's use `concat` to create a new array with the new hero appended and assign that to `heroes`. - This time Angular detects that the array object reference has changed. - It executes the pipe and updates the display with the new array which includes the new flying hero. - - *If we **mutate** the array, no pipe and no display update; - if we **replace** the array, the pipe executes and the display updates*. + We can fix that. Let's create a new #{_array} with the new hero appended and assign that to `heroes`. + This time Angular detects that the #{_array} reference has changed. + It executes the pipe and updates the display with the new #{_array} which includes the new flying hero. + *If we **mutate** the #{_array}, no pipe is invoked and no display updated; + if we **replace** the #{_array}, then the pipe executes and the display is updated*. The *Flying Heroes* in the [live example](/resources/live-examples/pipes/ts/plnkr.html) extends the code with checkbox switches and additional displays to help us experience these effects. + figure.image-display img(src='/resources/images/devguide/pipes/flying-heroes-anim.gif' alt="Flying Heroes") :marked - Replacing the array is an efficient way to signal to Angular that it should update the display. - When do we replace the array? When the data change. - + Replacing the #{_array} is an efficient way to signal to Angular that it should update the display. + When do we replace the #{_array}? When the data change. That's an easy rule to follow in *this toy* example where the only way to change the data is by adding a new hero. @@ -243,7 +254,6 @@ figure.image-display especially in applications that mutate data in many ways, perhaps in application locations far away. A component is such an application usually can't know about those changes. - Moreover, it's unwise to distort our component design to accommodate a pipe. We strive as much as possible to keep the component class independent of the HTML. The component should be unaware of pipes. @@ -255,29 +265,31 @@ figure.image-display ## Pure and Impure Pipes There are two categories of pipes: **pure** and **impure**. - - Pipes are pure by default. Every pipe we've seen so far has been pure. - + Pipes are pure by default. Every pipe we've seen so far has been pure. We make a pipe impure by setting its pure flag to false. We could make the `FlyingHeroesPipe` - impure with a flip of the switch: + impure like this: +makeExample('pipes/ts/app/flying-heroes.pipe.ts', 'pipe-decorator')(format='.') + :marked Before we do that, let's understand the difference between *pure* and *impure*, starting with a *pure* pipe. ### Pure pipes - Angular executes a *pure pipe* only when it detects a *pure change* to the input value. +block pure-change + :marked + Angular executes a *pure pipe* only when it detects a *pure change* to the input value. + A ***pure change*** is *either* a change to a primitive input value (`String`, `Number`, `Boolean`, `Symbol`) + *or* a changed object reference (`Date`, `Array`, `Function`, `Object`). - A *pure change* is *either* a change to a primitive input value (`String`, `Number`, `Boolean`, `Symbol`) - *or* a changed object reference (`Date`, `Array`, `Function`, `Object`). - - Angular ignores changes *within* the object itself. - It won't call a pure pipe if we change the input month, add to the input array, or update an input object property. +:marked + Angular ignores changes *within* (composite) objects. + It won't call a pure pipe if we change an input month, add to an input #{_array}, or update an input object property. This may seem restrictive but is is also fast. - An object reference check is fast ... much faster than a deep check for differences. - ... so Angular can quickly determine if it can skip both the pipe execution and a screen update. + An object reference check is fast — much faster than a deep check for + differences — so Angular can quickly determine if it can skip both the + pipe execution and a view update. For this reason, we prefer a pure pipe if we can live with the change detection strategy. When we can't, we *may* turn to the impure pipe. @@ -287,8 +299,10 @@ figure.image-display Or we might not use a pipe at all. It may be better to pursue the pipe's purpose with a property of the component, a point we take up later. + :marked ### Impure pipes + Angular executes an *impure pipe* during *every* component change detection cycle. An impure pipe will be called a lot, as often as every keystroke or mouse-move. @@ -304,6 +318,7 @@ figure.image-display 'pipes/ts/app/flying-heroes.pipe.ts, pipes/ts/app/flying-heroes.pipe.ts', 'impure, pure', 'FlyingHeroesImpurePipe, FlyingHeroesPipe')(format='.') + :marked We inherit from `FlyingHeroesPipe` to prove the point that nothing changed internally. The only difference is the `pure` flag in the pipe metadata. @@ -316,19 +331,23 @@ figure.image-display :marked The only substantive change is the pipe. We can confirm in the [live example](/resources/live-examples/pipes/ts/plnkr.html) - that the *flying heroes* display updates as we enter new heroes even when we mutate the `heroes` array. - + that the *flying heroes* display updates as we enter new heroes even when we mutate the `heroes` #{_array}. +- var _dollar = _docsFor === 'ts' ? '$' : ''; +:marked ### The impure *AsyncPipe* + The Angular `AsyncPipe` is an interesting example of an impure pipe. - The `AsyncPipe` accepts a `Promise` or `Observable` as input + The `AsyncPipe` accepts a `#{_Promise}` or `#{_Observable}` as input and subscribes to the input automatically, eventually returning the emitted value(s). It is also stateful. - The pipe maintains a subscription to the input `Observable` and - keeps delivering values from that `Observable` as they arrive. + The pipe maintains a subscription to the input `#{_Observable}` and + keeps delivering values from that `#{_Observable}` as they arrive. + + In this next example, we bind an `#{_Observable}` of message strings + (`message#{_dollar}`) to a view with the `async` pipe. - In this next example, we bind an `Observable` of message strings (`messages$`) to a view with the `async` pipe. +makeExample('pipes/ts/app/hero-async-message.component.ts', null, 'app/hero-async-message.component.ts') :marked @@ -340,12 +359,10 @@ figure.image-display ### An impure caching pipe - Let's write one more impure pipe, a pipe that makes an http request to the server. - + Let's write one more impure pipe, a pipe that makes an HTTP request to the server. Normally, that's a horrible idea. It's probably a horrible idea no matter what we do. We're forging ahead anyway to make a point. - Remember that impure pipes are called every few microseconds. If we're not careful, this pipe will punish the server with requests. @@ -366,10 +383,13 @@ figure.image-display the nework tab in the browser developer tools confirms that there is only one request for the file. The component renders like this: + figure.image-display img(src='/resources/images/devguide/pipes/hero-list.png' alt="Hero List") + :marked ### *JsonPipe* + The second binding involving the `FetchPipe` uses more pipe chaining. We take the same fetched results displayed in the first binding and display them again, this time in JSON format by chaining through to the built-in `JsonPipe`. @@ -380,8 +400,10 @@ figure.image-display The [JsonPipe](../api/common/JsonPipe-class.html) provides an easy way to diagnosis a mysteriously failing data binding or inspect an object for future binding. + :marked Here's the complete component implementation: + +makeExample('pipes/ts/app/hero-list.component.ts', null, 'app/hero-list.component.ts') a(id="pure-pipe-pure-fn") @@ -389,7 +411,6 @@ a(id="pure-pipe-pure-fn") ### Pure pipes and pure functions A pure pipe uses pure functions. - Pure functions process inputs and return values without detectable side-effects. Given the same input they should always return the same output. @@ -397,7 +418,6 @@ a(id="pure-pipe-pure-fn") The built-in `DatePipe` is a pure pipe with a pure function implementation. So is our `ExponentialStrengthPipe`. So is our `FlyingHeroesPipe`. - A few steps back we reviewed the `FlyingHeroesImpurePipe` — *an impure pipe with a pure function*. But a *pure pipe* must always be implemented with a *pure function*. Failure to heed this warning will bring about many a console errors regarding expressions that have changed after they were checked. @@ -418,14 +438,14 @@ a(id="no-filter-pipe") .l-main-section :marked ## No *FilterPipe* or *OrderByPipe* + Angular does not ship with pipes for filtering or sorting lists. Developers familiar with Angular 1 know these as `filter` and `orderBy`. There are no equivalents in Angular 2. This is not an oversight. Angular 2 is unlikely to offer such pipes because (a) they perform poorly and (b) they prevent aggressive minification. - - Both *filter* and *orderBy* require parameters that reference object properties. + Both `filter` and `orderBy` require parameters that reference object properties. We learned earlier that such pipes must be [*impure*](#pure-and-impure-pipes) and that Angular calls impure pipes in almost every change detection cycle. @@ -436,8 +456,8 @@ a(id="no-filter-pipe") by offering `filter` and `orderBy` in the first place. The minification hazard is also compelling if less obvious. Imagine a sorting pipe applied to a list of heroes. - We might sort the list by hero `name` and `planet` origin properties something like this: -code-example(format="." language="html") + We might sort the list by hero `name` and `planet` of origin properties something like this: +code-example(language="html") <!-- NOT REAL CODE! --> <div *ngFor="let hero of heroes | orderBy:'name,planet'"></div> :marked diff --git a/public/docs/ts/latest/guide/router-aux.jade b/public/docs/ts/latest/guide/router-aux.jade deleted file mode 100644 index e44662b202..0000000000 --- a/public/docs/ts/latest/guide/router-aux.jade +++ /dev/null @@ -1,185 +0,0 @@ -// - TODO: REVIVE AUX ROUTE MATERIAL WHEN THAT FEATURE WORKS AS EXPECTED - - PLEASE DO NOT CREATE ISSUES OR PULL REQUESTS FOR THIS PAGE - - - .l-main-section - :marked - ## Milestone #4: Auxiliary Routes - Auxiliary routes are routes that can be activated independently of the current - route. They are entirely optional, depending on your app needs. - - For example, your application may have a modal that appears and this could - be an auxiliary route. The modal may have its own navigation needs, such as a slideshow - and that auxiliary route is able to manage the navigation stack independently of the - primary routes. - - In our sample application, we also want to have a chat feature that allows people - the ability to have a live agent assist them. The chat window will have first an - initial route that contains a prompt to ask the visitor if they'd like to chat with - an agent. Once they initiate a chat, they go to a new route for the chat experience. - - .alert.is-critical Make diagram of chat routes - - :marked - In this auxiliary chat experience, it overlays the current screen and persists. - If you navigate from the Heroes to Crisis Center, the chat auxiliary route remains - active and in view. - - Therefore the auxiliary routing is truly independent of the other - routing. In most respects, an auxiliary route behaves the same outside of it is rendered - in its own outlet and modifies the url differently. - - We'll look at how to setup an auxiliary route and considerations for when to use them. - - ### Auxiliary Route Outlet - In order to get an auxiliary route, it needs a place to be rendered. So far the app has - a single `RouterOutet` that the rest of our routes are rendered into. Auxiliary routes need to - have their own `RouterOutlet`, and that is done by giving it a name attribute. Open the - `app.component.ts` file and let's add the new outlet to the template. - .alert.is-critical Should remove app.component.4.ts based example (next) when we know what's what - +_makeExample('router/ts/app/app.component.4.ts', 'chat-outlet', 'app/app.component.ts') - .alert.is-critical Should be able to project from app.component.ts like this - +_makeExample('router/ts/app/app.component.ts', 'template', 'app/app.component.ts (excerpt)') - :marked - The name of the outlet must be unique to the component. You could reuse the name across - different components, so you don't have to worry about collisions. - - Here we give it a name of "chat", which will be used by the router when we setup our - route configs. The app component needs to know about this Auxiliary route, so we - import the `ChatComponent`, add a new ROUTE_NAME (`chat`), - and add a new 'Chat' route to the `ROUTES` in `app.routes.ts` (just below the redirect) . - +_makeExample('router/ts/app/routes.ts', null, 'app/routes.ts') - :marked - Look again at the 'Chat' route - +_makeExample('router/ts/app/routes.ts','chat-route') - :marked - You can see the route definition is nearly the same, except instead of `path` there is - an `aux`. The `aux` property makes this an Auxiliary route. - - @TODO Explain how a named outlet is paired with an aux route. - - The chat component defines its own routes just like the other components, even though - it is an Auxiliary route. - - +_makeExample('router/ts/app/chat/routes.ts', null, 'app/chat/routes.ts') - :marked - Even though this is an Auxiliary route, you notice there is no difference in how we've - configured the route config for the primary chat component. The chat component also has - the `RouterOutlet` Directive in the template so the child components render inside of - the chat window. - - In the chat components, we can use `RouterLink` to reference routes just the same as - a normal route. Since this is inside of an Auxiliary route, these relative links will - resolve within the chat component and not change the primary route (the Crisis Center or - Heroes pages). - - +_makeExample('router/ts/app/chat/chat-init.component.ts', 'chat-links') - - :marked - When the chat component opens, it first initializes this template to ask the user if - they'd like to chat or not. If they agree, it takes them to the chat window where they - begin to send messages to the 'live' agent. - - The behavior of the chat components may be interesting, but have no additional insights - for routing, except for the ability to deactivate an active Auxiliary route. - - ### Exiting an Auxiliary Route - - @TODO Figure out how to close/deactivate an aux route - - ### Auxiliary Route URLs - - Auxiliary Routes do modify the url using parens, like so. - code-example(format=".", language="bash"). - localhost:3002/crisis-center(chat)/2(details) - :marked - This would be the url on a page where the user was viewing an item in the Crisis Center, - in this case the "Dragon Burning Cities" crisis, and the `(chat)` Auxiliary Route would - active and on the details child route. - - ### Multiple Auxiliary Routes - - There is no limit to how many Auxiliary Routes you have defined or active. There is probably - a practical limit where too much appears on the screen for a user, but you can have as many - Auxiliary Routes as you have named `RouteOutlet`s. - - :marked - ### Auxiliary Route Summary - - * Auxiliary routes are normal routes that are rendered outside of the primary `RouterOutlet` - * They must use a named `RouterOutlet` to render. - * Can be activated as long as the parent component is active. - * Links inside of child components are resolved against the aux parent component. - * Auxiliary routes are deactivated by @TODO? - * Routes are indicated in the url using parens. - * Multiple aux routes can be active at once. - - ### Chat - The "Chat" feature area within the `chat` folder looks like this: - ``` - app/ - chat/ - ├── chat-detail.component.ts - ├── chat-init.component.ts - ├── chat.component.ts - ├── chat.service.ts - └── routes.ts - ``` - +_makeTabs( - `router/ts/app/chat/chat.component.ts, - router/ts/app/chat/routes.ts, - router/ts/app/chat/chat-init.component.ts, - router/ts/app/chat/chat-detail.component.ts, - router/ts/app/chat/chat.service.ts - `, - null, - `chat.component.ts, - chat/routes.ts, - chat-init.component.ts, - chat-detail.component.ts, - chat.service.ts, - `) - - - The following are styles extracted from `styles.css` - that only belong if/when we add chat back - ``` - /* chat styles */ - .chat { - position: fixed; - bottom: 0; - right: 20px; - border: 1px solid #1171a3; - width: 400px; - height: 300px; - } - .chat h2 { - background: #1171a3; - color: #fff; - margin: 0; - padding: 8px; - } - .chat .close { - float: right; - display: block; - padding: 0 10px; - cursor: pointer; - } - .chat .chat-content { - padding: 10px; - } - .chat .chat-messages { - height: 190px; - overflow-y: scroll; - } - .chat .chat-input { - border-top: 1px solid #ccc; - padding-top: 10px; - } - .chat .chat-input input { - width: 370px; - padding: 3px; - } - ``` diff --git a/public/docs/ts/latest/guide/router-deprecated.jade b/public/docs/ts/latest/guide/router-deprecated.jade new file mode 100644 index 0000000000..464dc57882 --- /dev/null +++ b/public/docs/ts/latest/guide/router-deprecated.jade @@ -0,0 +1,1480 @@ +include ../_util-fns + +.alert.is-critical + :marked + This chapter describes the *deprecated beta* Component Router which is + replaced by the *release candidate* Component Router. We are documenting that now. + +:marked + The Angular ***Component Router*** enables navigation from one [view](./glossary.html#view) to the next + as users perform application tasks. + + We cover the router's primary features in this chapter, illustrating them through the evolution + of a small application that we can [run live](/resources/live-examples/router-deprecated/ts/plnkr.html). +.l-sub-section + img(src='/resources/images/devguide/plunker-separate-window-button.png' alt="pop out the window" align="right" style="margin-right:-20px") + :marked + To see the URL changes in the browser address bar, + pop out the preview window by clicking the blue 'X' button in the upper right corner. + +.l-main-section +:marked + ## Overview + + The browser is a familiar model of application navigation. + We enter a URL in the address bar and the browser navigates to a corresponding page. + We click links on the page and the browser navigates to a new page. + We click the browser's back and forward buttons and the browser navigates + backward and forward through the history of pages we've seen. + + The Angular ***Component Router*** ("the router") borrows from this model. + It can interpret a browser URL as an instruction + to navigate to a client-generated view and pass optional parameters along to the supporting view component + to help it decide what specific content to present. + We can bind the router to links on a page and it will navigate to + the appropriate application view when the user clicks a link. + We can navigate imperatively when the user clicks a button, selects from a drop box, + or in response to some other stimulus from any source. And the router logs activity + in the browser's history journal so the back and forward buttons work as well. + + We'll learn many router details in this chapter which covers + + * Setting the [base href](#base-href) + * Importing from the [router library](#import) + * [configuring a router](#route-config) + * the [link parameters array](#link-parameters-array) that propels router navigation + * navigating when the user clicks a data-bound [RouterLink](#router-link) + * navigating under [program control](#navigate) + * embedding critical information in the URL with [route parameters](#route-parameters) + * creating a [child router](#child-router) with its own routes + * setting a [default route](#default) + * confirming or canceling navigation with [router lifecycle hooks](#lifecycle-hooks) + * passing optional information in [query parameters](#query-parameters) + * choosing the "HTML5" or "hash" [URL style](#browser-url-styles) + + We proceed in phases marked by milestones building from a simple two-pager with placeholder views + up to a modular, multi-view design with child routes. + + But first, an overview of router basics. + +.l-main-section +:marked + ## The Basics + Let's begin with a few core concepts of the Component Router. + Then we can explore the details through a sequence of examples. + +:marked + ### *<base href>* + Most routing applications should add a `` element to the **`index.html`** just after the `` tag + to tell the router how to compose navigation URLs. + + If the `app` folder is the application root, as it is for our sample application, + set the `href` value *exactly* as shown here. ++makeExample('router-deprecated/ts/index.1.html','base-href', 'index.html (base href)')(format=".") + +:marked + ### Router imports + The Angular Component Router is an optional service that presents a particular component view for a given URL. + It is not part of the Angular 2 core. It is in its own library package, `'@angular/router-deprecated`. + We import what we need from it as we would from any other Angular package. + ++makeExample('router-deprecated/ts/app/app.component.1.ts','import-router', 'app/app.component.ts (import)')(format=".") +.l-sub-section + :marked + We cover other options in the [details below](#browser-url-styles). +:marked + ### Configuration + When the browser's URL changes, the router looks for a corresponding **`RouteDefinition`** + from which it can determine the component to display. + + A router has no route definitions until we configure it. + The preferred way to simultaneously create a router and add its routes is with a **`@RouteConfig`** [decorator](glossary.html#decorator) + applied to the router's host component. + + In this example, we configure the top-level `AppComponent` with three route definitions ++makeExample('router-deprecated/ts/app/app.component.2.ts', 'route-config', 'app.component.ts (excerpt)')(format=".") +:marked + +.l-sub-section + :marked + There are several flavors of `RouteDefinition`. + The most common by far is the named **`Route`** which maps a URL path to a component + + The `name` field is the route name which **must** be spelled in **PascalCase** + to avoid potential confusion with the route `path`. + + The `:id` in the third route is a token for a route parameter. In a URL such as `/hero/42`, "42" + is the value of the `id` parameter. The corresponding `HeroDetailComponent` + will use that value to find and present the hero whose `id` is 42. + We'll learn more about route parameters later in this chapter. +:marked + ### Router Outlet + Now we know how the router gets its configuration. + When the browser URL for this application becomes `/heroes`, + the router matches that URL to the `RouteDefinition` named *Heroes* and displays the `HeroListComponent` + in a **`RouterOutlet`** that we've placed in the host view's HTML. +code-example(format="", language="html"). + <!-- Routed views go here --> + <router-outlet></router-outlet> +:marked + ### Router Links + Now we have routes configured and a place to render them, but + how do we navigate? The URL could arrive directly from the browser address bar. + But most of the time we navigate as a result of some user action such as the click of + an anchor tag. + + We add a **`RouterLink`** directive to the anchor tag and bind it to a template expression that + returns an array of route link parameters (the **link parameters array**). The router ultimately resolves that array + into a URL and a component view. + + We see such bindings in the following `AppComponent` template: ++makeExample('router-deprecated/ts/app/app.component.1.ts', 'template')(format=".") +.l-sub-section + :marked + We're adding two anchor tags with `RouterLink` directives. + We bind each `RouterLink` to an array containing the string name of a route definition. + 'CrisisCenter' and 'Heroes' are the names of the `Routes` we configured above. + + We'll learn to write more complex link expressions — and why they are arrays — + [later](#link-parameters-array) in the chapter. +:marked + ### Let's summarize + + The `@RouterConfig` configuration tied the `AppComponent` to a router configured with routes. + The component has a `RouterOutlet` where it can display views produced by the router. + It has `RouterLinks` that users can click to navigate via the router. + + The `AppComponent` has become a ***Routing Component***, a component that can route. + + Here are the key *Component Router* terms and their meanings: +table + tr + th Router Part + th Meaning + tr + td Router + td. + Displays the application component for the active URL. + Manages navigation from one component to the next. + tr + td @RouteConfig + td. + Configures a router with RouteDefinitions, each mapping a URL path to a component. + tr + td RouteDefinition + td. + Defines how the router should navigate to a component based on a URL pattern. + tr + td Route + td. + The most common form of RouteDefinition consisting of a path, a route name, + and a component type. + tr + td RouterOutlet + td. + The directive (<router-outlet>) that marks where the router should display a view. + tr + td RouterLink + td. + The directive for binding a clickable HTML element to + a route. Clicking an anchor tag with a routerLink directive + that is bound to a Link Parameters Array triggers a navigation. + tr + td Link Parameters Array + td. + An array that the router inteprets into a routing instruction. + We can bind a RouterLink to that array or pass the array as an argument to + the Router.navigate method. + tr + td Routing Component + td. + An Angular component with an attached router. +:marked + We've barely touched the surface of the router and its capabilities. + + The following detail sections describe a sample routing application + as it evolves over a sequence of milestones. + We strongly recommend taking the time to read and understand this story. + +.l-main-section +:marked + ## The Sample Application + We have an application in mind as we move from milestone to milestone. + +.l-sub-section + :marked + While we make incremental progress toward the ultimate sample application, this chapter is not a tutorial. + We discuss code and design decisions pertinent to routing and application design. + We gloss over everything in between. + + The full source is available in the [live example](/resources/live-examples/router-deprecated/ts/plnkr.html). +:marked + Our client is the Hero Employment Agency. + Heroes need work and The Agency finds Crises for them to solve. + + The application has two main feature areas: + 1. A *Crisis Center* where we maintain the list of crises for assignment to heroes. + 1. A *Heroes* area where we maintain the list of heroes employed by The Agency. + + Run the [live example](/resources/live-examples/router-deprecated/ts/plnkr.html). + It opens in the *Crisis Center*. We'll come back to that. + + Click the *Heroes* link. We're presented with a list of Heroes. +figure.image-display + img(src='/resources/images/devguide/router/hero-list.png' alt="Hero List" width="250") +:marked + We select one and the application takes us to a hero editing screen. +figure.image-display + img(src='/resources/images/devguide/router/hero-detail.png' alt="Crisis Center Detail" width="250") +:marked + Our changes take effect immediately. We click the "Back" button and the + app returns us to the Heroes list. + + We could have clicked the browser's back button instead. + That would have returned us to the Heroes List as well. + Angular app navigation updates the browser history as normal web navigation does. + + Now click the *Crisis Center* link. We go to the *Crisis Center* and its list of ongoing crises. +figure.image-display + img(src='/resources/images/devguide/router/crisis-center-list.png' alt="Crisis Center List" ) +:marked + We select one and the application takes us to a crisis editing screen. +figure.image-display + img(src='/resources/images/devguide/router/crisis-center-detail.png' alt="Crisis Center Detail") +:marked + This is a bit different from the *Hero Detail*. *Hero Detail* saves the changes as we type. + In *Crisis Detail* our changes are temporary until we either save or discard them by pressing the "Save" or "Cancel" buttons. + Both buttons navigate back to the *Crisis Center* and its list of crises. + + Suppose we click a crisis, make a change, but ***do not click either button***. + Maybe we click the browser back button instead. Maybe we click the "Heroes" link. + + Do either. Up pops a dialog box. +figure.image-display + img(src='/resources/images/devguide/router/confirm-dialog.png' alt="Confirm Dialog" width="300") +:marked + We can say "OK" and lose our changes or click "Cancel" and continue editing. + + The router supports a `routerCanDeactivate` lifecycle hook that gives us a chance to clean-up + or ask the user's permission before navigating away from the current view. + + Here we see an entire user session that touches all of these features. + +figure.image-display + img(src='/resources/images/devguide/router/router-anim.gif' alt="App in action" ) +:marked + Here's a diagram of all application routing options: +figure.image-display + img(src='/resources/images/devguide/router/complete-nav.png' alt="Navigation diagram" ) +:marked + This app illustrates the router features we'll cover in this chapter + + * navigating to a component (*Heroes* link to "Heroes List") + * including a route parameter (passing the Hero `id` while routing to the "Hero Detail") + * child routes (the *Crisis Center* has its own routes) + * the `routerCanDeactivate` lifecycle hook (ask permission to discard unsaved changes) + + +.l-main-section +:marked + ## Milestone #1: Getting Started with the Router + + Let's begin with a simple version of the app that navigates between two empty views. +figure.image-display + img(src='/resources/images/devguide/router/router-1-anim.gif' alt="App in action" ) + + +:marked + + ### Set the *<base href>* + The Component Router uses the browser's + [history.pushState](https://developer.mozilla.org/en-US/docs/Web/API/History_API#Adding_and_modifying_history_entries) + for navigation. Thanks to `pushState`, we can make our in-app URL paths look the way we want them to + look, e.g. `localhost:3000/crisis-center`. Our in-app URLs can be indistinguishable from server URLs. + + Modern HTML 5 browsers were the first to support `pushState` which is why many people refer to these URLs as + "HTML 5 style" URLs. + + We must **add a [<base href> element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base) tag** + to the `index.html` to make `pushState` routing work. + The browser also needs the base `href` value to prefix *relative* URLs when downloading and linking to + css files, scripts, and images. + + Add the base element just after the `` tag. + If the `app` folder is the application root, as it is for our application, + set the `href` value in **`index.html`** *exactly* as shown here. + ++makeExample('router-deprecated/ts/index.1.html','base-href', 'index.html (base href)')(format=".") +.l-sub-section + :marked + HTML 5 style navigation is the Component Router default. + Learn why "HTML 5" style is preferred, how to adjust its behavior, and how to switch to the + older hash (#) style if necessary in the [Browser URL Styles](#browser-url-styles) appendix below. + +:marked +.l-sub-section + :marked + #### Live example note + We have to get tricky when we run the live example because the host service sets + the application base address dynamically. That's why we replace the `` with a + script that writes a `` tag on the fly to match. + code-example(format="") + <script>document.write('<base href="' + document.location + '" />');</script> + :marked + We should only need this trick for the live example, not production code. + + +:marked + ### Import from the Component Router library + The Component Router is not part of the Angular 2 core. It is in its own library. + The router is an optional service because not all applications need routing and, + depending on your requirements, you may need a different routing library. + + The Component Router library is in its own `'@angular/router-deprecated` package. + We import what we need from it as we would from any Angular package: ++makeExample('router-deprecated/ts/app/app.component.1.ts','import-router', 'app/app.component.ts (import)')(format=".") + +:marked + ### Booting with the router service providers + Our app launches from the `main.ts` file in the `/app` folder so let's start there. + It's short and all of it is relevant to routing. ++makeExample('router-deprecated/ts/app/main.1.ts','all', 'main.ts')(format=".") +:marked + We import our root `AppComponent` and Angular's `bootstrap` function as expected. + + We also import `ROUTER_PROVIDERS` from the router library. + The router is a service implemented by a collection of *Dependency Injection* providers, most of which are identified in the + `ROUTER_PROVIDERS` array. + + We're booting Angular with `AppComponent` as our app's root component and + registering providers, as we often do, in the providers array in the second parameter of the `bootstrap` function. + Providing the router providers at the root makes the Component Router available everywhere in our application. +.l-sub-section + :marked + Learn about providers, the `provide` function, and injected services in the + [Dependency Injection chapter](dependency-injection.html). +:marked + ### The *AppComponent* shell + The root `AppComponent` is the application shell. It has title at the top, a navigation bar with two links, + and a *Router Outlet* at the bottom where the router swaps views on and off the page. Here's what we mean: +figure.image-display + img(src='/resources/images/devguide/router/shell-and-outlet.png' alt="Shell" width="300" ) +:marked + + The corresponding component template looks like this: ++makeExample('router-deprecated/ts/app/app.component.1.ts','template')(format=".") +:marked + ### *RouterOutlet* + `RouterOutlet` is a component from the router library. + The router displays views within the bounds of the `` tags. + +.l-sub-section + :marked + A template may hold exactly one ***unnamed*** ``. + + +:marked + ### *RouterLink* binding + Above the outlet, within the anchor tags, we see [Property Bindings](template-syntax.html#property-binding) to + the `RouterLink` directive that look like `[routerLink]="[...]"`. We imported `RouterLink` from the router library. + + The template expression to the right of the equals (=) returns a *link parameters array*. + + A link parameters array holds the ingredients for router navigation: + * the name of the route that prescribes the destination component and a path for the URL + * the optional route and query parameters that go into the route URL + + The arrays in this example each have a single string parameter, the name of a `Route` that + we'll configure for this application with `@RouteConfig()`. We don't need to set route parameters yet. +.l-sub-section + :marked + Learn more about the link parameters array in the [appendix below](#link-parameters-array). + +:marked + ### *@RouteConfig()* + A router holds a list of route definitions. The list is empty for a new router. We must configure it. + + A router also needs a **Host Component**, a point of origin for its navigations. + + It's natural to combine the creation of a new router, its configuration, and its assignment to a host component + in a single step. That's the purpose of the `@RouteConfig` decorator which we put to good use here: ++makeExample('router-deprecated/ts/app/app.component.1.ts','route-config')(format=".") +:marked + The `@RouteConfig` decorator creates a new router. + We applied the decorator to `AppComponent` which makes that the router's host component. + The argument to `@RouteConfig()` is an array of **Route Definitions**. + + We're supplying two definitions: ++makeExample('router-deprecated/ts/app/app.component.1.ts','route-defs')(format=".") +:marked + Each definition translates to a [Route](../api/router-deprecated/index/Route-class.html) which has a + * `path` - the URL path segment for this route + * `name` - the name of the route + * `component` - the component associated with this route. + + The router draws upon its registry of route definition when + 1. the browser URL changes + 2. we tell the router to go to a named route + + In plain English, we might say of the first route: + 1. *When the browser's location URL changes to **match the path** segment `/crisis-center`, create or retrieve an instance of + the `CrisisCenterComponent` and display its view.* + + 1. *When the application requests navigation to a route **named** `CrisisCenter`, compose a browser URL + with the path segment `/crisis-center`, update the browser's address location and history, create or retrieve an instance of + the `CrisisListComponent`, and display that component's list view.* + + ### "Getting Started" wrap-up + + We've got a very basic, navigating app, one that can switch between two views + when the user clicks a link. + + We've learned how to + * load the router library + * add a nav bar to the shell template with anchor tags and `routerLink` directives + * added a `router-outlet` to the shell template where views will be displayed + * configure the router with `@RouterConfig` + * set the router to compose "HTML 5" browser URLs. + + The rest of the starter app is mundane, with little interest from a router perspective. + Here are the details for readers inclined to build the sample through to this milestone. + + Our starter app's structure looks like this: +.filetree + .file router-sample + .children + .file app + .children + .file app.component.ts + .file crisis-list.component.ts + .file hero-list.component.ts + .file main.ts + .file node_modules ... + .file typings ... + .file index.html + .file package.json + .file styles.css + .file tsconfig.json + .file typings.json +:marked + Here are the files discussed in this milestone ++makeTabs( + `router-deprecated/ts/app/app.component.1.ts, + router-deprecated/ts/app/main.1.ts, + router-deprecated/ts/app/hero-list.component.ts, + router-deprecated/ts/app/crisis-list.component.ts, + router-deprecated/ts/index.html`, + ',all,,', + `app.component.ts, + main.ts, + hero-list.component.ts, + crisis-list.component.ts, + index.html`) +:marked + + +.l-main-section +:marked + ## Milestone #2: The Heroes Feature + + We've seen how to navigate using the `RouterLink` directive. + + Now we'll learn some new tricks such as how to + * organize our app into *feature areas* + * navigate imperatively from one component to another + * pass information along in route parameters (`RouteParams`) + + To demonstrate, we'll build out the *Heroes* feature. + + ### The Heroes "feature area" + + A typical application has multiple *feature areas*, each an island of functionality + with its own workflow(s), dedicated to a particular business purpose. + + We could continue to add files to the `app/` folder. + That's unrealistic and ultimately not maintainable. + We think it's better to put each feature area in its own folder. + + Our first step is to **create a separate `app/heroes/` folder** + and add *Hero Management* feature files there. + + We won't be creative about it. Our example is pretty much a + copy of the code and capabilities in the "[Tutorial: Tour of Heroes](../tutorial/index.html)". + + Here's how the user will experience this version of the app +figure.image-display + img(src='/resources/images/devguide/router/router-2-anim.gif' alt="App in action" ) +:marked + ### Add Heroes functionality + + We delete the placeholder `hero-list.component.ts` that's in + the `app/` folder. + + We create a new `hero-list.component.ts` in the `app/heroes/` + folder and copy over the contents of the final `heroes.component.ts` from the tutorial. + We also copy the `hero-detail.component.ts` and the `hero.service.ts` files + into the `heroes/` folder. + + When we're done organizing, we have three *Hero Management* files: + +.filetree + .file app/heroes + .children + .file hero-detail.component.ts + .file hero-list.component.ts + .file hero.service.ts +:marked + We provide the `HeroService` in the application root `AppComponent` + so that is available everywhere in the app. + + Now it's time for some surgery to bring these files and the rest of the app + into alignment with our application router. + + ### New route definition with route parameter + + The new Heroes feature has two interacting components, the list and the detail. + The list view is self-sufficient; we navigate to it, it gets a list of heroes and displays them. + It doesn't need any outside information. + + The detail view is different. It displays a particular hero. It can't know which hero on its own. + That information must come from outside. + + In our example, when the user selects a hero from the list, we navigate to the detail view to show that hero. + We'll tell the detail view which hero to display by including the selected hero's id in the route URL. + + With that plan in mind, we return to the `app.component.ts` to make changes to the router's configuration + + First, we import the two components from their new locations in the `app/heroes/` folder: ++makeExample('router-deprecated/ts/app/app.component.2.ts','hero-import')(format=".") +:marked + Then we update the `@RouteConfig` route definitions : ++makeExample('router-deprecated/ts/app/app.component.2.ts','route-config')(format=".") +:marked + The `CrisisCenter` and `Heroes` definitions didn't change. + While we moved `hero-list.component.ts` to a new location in the `app/heroes/` folder, that only affects the `import` statement; + it doesn't affect its route definition. + + We added a new route definition for the `HeroDetailComponent` — and this definition has a twist. ++makeExample('router-deprecated/ts/app/app.component.2.ts','hero-detail-route')(format=".") +:marked + Notice the `:id` token in the path. That creates a slot in the path for a **Route Parameter**. + In this case, we're expecting the router to insert the `id` of a hero into that slot. + + If we tell the router to navigate to the detail component and display "Magneta", we expect hero `id` (15) to appear in the + browser URL like this: +code-example(format="." language="bash"). + localhost:3000/hero/15 +:marked + If a user enters that URL into the browser address bar, the router should recognize the + pattern and go to the same "Magneta" detail view. +.l-sub-section + :marked + #### Route parameter or query parameter? + Embedding the route parameter token, `:id`, in the route definition path is a good choice for our scenario + because the `id` is *required* by the `HeroDetailComponent` and because + the value `15` in the path clearly distinguishes the route to "Magneta" from + a route for some other hero. + + A [query parameter](#query-parameter) might be a better choice if we were passing an *optional* value to `HeroDetailComponent`. + + +:marked + ### Navigate to the detail imperatively + + *We don't navigate to the detail component by clicking a link*. + We won't be adding a new anchor tag to the shell navigation bar. + + Instead, we'll *detect* when the user selects a hero from the list and *command* the router + to present the hero detail view of the selected hero. + + We'll adjust the `HeroListComponent` to implement these tasks, beginning with its constructor + which acquires the router service and the `HeroService` by dependency injection: ++makeExample('router-deprecated/ts/app/heroes/hero-list.component.1.ts','ctor')(format=".") +:marked + We make a few changes to the template: ++makeExample('router-deprecated/ts/app/heroes/hero-list.component.1.ts','template')(format=".") +:marked + The template defines an `*ngFor` repeater such as [we've seen before](displaying-data.html#ngFor). + There's a `(click)` [EventBinding](template-syntax.html#event-binding) to the component's `onSelect` method + which we implement as follows: ++makeExample('router-deprecated/ts/app/heroes/hero-list.component.1.ts','select')(format=".") +:marked + It calls the router's **`navigate`** method with a **Link Parameters Array**. + This array is similar to the *link parameters array* we met [earlier](#shell-template) in an anchor tag while + binding to the `RouterLink` directive. This time we see it in code rather than in HTML. + + + ### Setting the route parameters object + + We're navigating to the `HeroDetailComponent` where we expect to see the details of the selected hero. + We'll need *two* pieces of information: the destination and the hero's `id`. + + Accordingly, the *link parameters array* has *two* items: the **name** of the destination route and a **route parameters object** that specifies the + `id` of the selected hero. ++makeExample('router-deprecated/ts/app/heroes/hero-list.component.1.ts','link-parameters-array')(format=".") +:marked + The router composes the appropriate two-part destination URL from this array: +code-example(format="." language="bash"). + localhost:3000/hero/15 +:marked + ### Getting the route parameter + + + How does the target `HeroDetailComponent` learn about that `id`? + Certainly not by analyzing the URL! That's the router's job. + + The router extracts the route parameter (`id:15`) from the URL and supplies it to + the `HeroDetailComponent` via the **RouteParams** service. + + As usual, we write a constructor that asks Angular to inject that service among the other services + that the component require and reference them as private variables. ++makeExample('router-deprecated/ts/app/heroes/hero-detail.component.1.ts','ctor')(format=".") +:marked + Later, in the `ngOnInit` method, + we ask the `RouteParams` service for the `id` parameter by name and + tell the `HeroService` to fetch the hero with that `id`. ++makeExample('router-deprecated/ts/app/heroes/hero-detail.component.1.ts','ngOnInit')(format=".") + +.l-sub-section + :marked + Angular calls the `ngOnInit` method shortly after creating an instance of the `HeroDetailComponent`. + + We put the data access logic in the `ngOnInit` method rather than inside the constructor + to improve the component's testability. + We explore this point in greater detail in the [OnInit appendix](#onInit) below. +:marked + ### Navigating back to the list component + The `HeroDetailComponent` has a "Back" button wired to its `gotoHeroes` method that navigates imperatively + back to the `HeroListComponent`. + + The router `navigate` method takes the same one-item *link parameters array* + that we wrote for the `[routerLink]` directive binding. + It holds the **name of the `HeroListComponent` route**: ++makeExample('router-deprecated/ts/app/heroes/hero-detail.component.1.ts','gotoHeroes')(format=".") +:marked + ### Heroes App Wrap-up + + We've reached the second milestone in our router education. + + We've learned how to + * organize our app into *feature areas* + * navigate imperatively from one component to another + * pass information along in route parameters (`RouteParams`) + + After these changes, the folder structure looks like this: +.filetree + .file router-sample + .children + .file app + .children + .file heroes + .children + .file hero-detail.component.ts + .file hero-list.component.ts + .file hero.service.ts + .file app.component.ts + .file crisis-list.component.ts + .file main.ts + .file node_modules ... + .file typings ... + .file index.html + .file package.json + .file styles.css + .file tsconfig.json + .file typings.json +:marked + + ### The Heroes App code + Here are the relevant files for this version of the sample application. ++makeTabs( + `router-deprecated/ts/app/app.component.2.ts, + router-deprecated/ts/app/heroes/hero-list.component.1.ts, + router-deprecated/ts/app/heroes/hero-detail.component.1.ts, + router-deprecated/ts/app/heroes/hero.service.ts`, + null, + `app.component.ts, + hero-list.component.ts, + hero-detail.component.ts, + hero.service.ts`) +:marked + + +.l-main-section +:marked + ## Milestone #3: The Crisis Center + The *Crisis Center* is a fake view at the moment. Time to make it useful. + + The new *Crisis Center* begins as a virtual copy of the *Heroes* feature. + We create a new `app/crisis-center` folder, copy the Hero files, + and change every mention of "hero" to "crisis". + + A `Crisis` has an `id` and `name`, just like a `Hero` + The new `CrisisListComponent` displays lists of crises. + When the user selects a crisis, the app navigates to the `CrisisDetailComponent` + for display and editing of the crisis name. + + Voilà, instant feature module! + + There's no point to this exercise unless we can learn something. + We do have new ideas and techniques in mind: + + * The application should navigate to the *Crisis Center* by default. + + * The user should be able to cancel unwanted changes. + + * The router should prevent navigation away from the detail view while there are pending changes. + + There are also a few lingering annoyances in the *Heroes* implementation that we can cure in the *Crisis Center*. + + * We currently register every route of every view at the highest level of the application. + If we expand the *Crisis Center* with a 100 new views, we'll make 100 changes to the + `AppComponent` route configuration. If we rename a *Crisis Center* component or change a route definition, + we'll be changing the `AppComponent` too. + + * If we followed *Heroes* lead, we'd be adding the `CrisisService` to the providers in `app.component.ts`. + Then both `HeroService` and `CrisisService` would be available everywhere although + they're only needed in their respective feature modules. That stinks. + + Changes to a sub-module such as *Crisis Center* shouldn't provoke changes to the `AppComponent` or `main.ts`. + We need to [*separate our concerns*](https://blog.8thlight.com/uncle-bob/2014/05/08/SingleReponsibilityPrinciple.html). + + We'll fix all of these problems and add the new routing features to *Crisis Center*. + + The most significant fix is the introduction of a **child *Routing Component*** + and its **child router** + + We'll leave *Heroes* in its less-than-perfect state to + serve as a contrast with what we hope is a superior *Crisis Center*. + + ### A free-standing Crisis Center Feature Module + The *Crisis Center* is one of two application workflows. + Users navigate between them depending on whether they are managing crises or heroes. + + The `CrisisCenter` and `Heroes` components are children of the root `AppComponent`. + + Unfortunately, they and their related files are physically commingled in the same folder with the `AppComponent`. + We'd prefer to separate them in their own *feature areas* so they can operate and evolve independently. + Someday we might re-use one or the other in a different application. + Someday we might load one of them dynamically only when the user chose to enter its workflow. + + Some might call it [yagni](http://martinfowler.com/bliki/Yagni.html) to even think about such things. + But we're right to be nervous about the way *Heroes* and *Crisis Center* artifacts are + bubbling up to the root `AppComponent` and blending with each other. + That's a [code smell](http://martinfowler.com/bliki/CodeSmell.html). + + Isolating feature area modules from each other looks good to us. +.l-sub-section + :marked + It's looking good as a general pattern for Angular applications. + figure.image-display + img(src='/resources/images/devguide/router/component-tree.png' alt="Component Tree" ) + :marked + * each feature area in its own module folder + * each area with its own root component + * each area root component with its own router-outlet and child routes + * area routes rarely (if ever) cross + +:marked + We'll make the *Crisis Center* stand on its own and leave the *Heroes* as it is + so we can compare the effort, results, and consequences. + Then each of us can decide which path to prefer (as if we didn't already know). + + + ### Child Routing Component + We create a new `app/crisis-center` folder and add `crisis-center.component.ts` to it with the following contents: ++makeExample('router-deprecated/ts/app/crisis-center/crisis-center.component.1.ts', 'minus-imports', 'crisis-center/crisis-center.component.ts (minus imports)') +:marked + The `CrisisCenterComponent` parallels the `AppComponent`. + + The `CrisisCenterComponent` is the root of the *Crisis Center* area + just as `AppComponent` is the root of the entire application. + + This `CrisisCenterComponent` is a shell for crisis management + just as the `AppComponent` is a shell to manage the high-level workflow. + + `AppComponent` has a `@RouteConfig` decorator that defines the top-level routes. + `CrisisCenterComponent` has a `@RouteConfig` decorator that defines *Crisis Center* child routes. + + The `CrisisCenterComponent` template is dead simple — simpler even than the `AppComponent` template. + It has no content, no links, just a `` for the *Crisis Center* child views. + + It has no selector either. It doesn't need one. We don't *embed* this component in a parent template. We *navigate* to it + from the outside, via a parent router (more on that soon). + + ### Service isolation + We add the `CrisisService` to the component's providers array + instead of registering it with the `bootstrap` function in `main.ts`. ++makeExample('router-deprecated/ts/app/crisis-center/crisis-center.component.1.ts', 'providers') +:marked + This step limits the scope of that service to the *Crisis Center* component and its sub-component tree. + No component outside of the *Crisis Center* needs access to the `CrisisService`. + By restricting its scope, we feel confident that we can evolve it independently without fear of breaking + unrelated application modules — modules that *shouldn't have access to it anyway*. + + ### Child Route Configuration + The `CrisisCenterComponent` is a *Routing Component* like the `AppComponent`. + + The `@RouteConfig` decorator that adorns the `CrisisCenterComponent` class defines routes in much the same way + that we did earlier. ++makeExample('router-deprecated/ts/app/crisis-center/crisis-center.component.1.ts', 'route-config', 'app/crisis-center/crisis-center.component.ts (routes only)' )(format=".") +:marked + The two routes terminate in the two *Crisis Center* child components, `CrisisListComponent` and `CrisisDetailComponent`. + + There is an *important difference* in the treatment of the root `AppComponent` paths and these paths. + Normally paths that begin with `/` refer to the root of the application. + Here they refer to the **root of the child component!**. + + The Component Router composes the final route by concatenating route paths beginning with the ancestor paths to this child router. + In our example, there is one ancestor path: "crisis-center". + The final route to the `CrisisDetailComponent` displaying the crisis whose `id` is 2 would be something like: +code-example(format=""). + localhost:3000/crisis-center/2 +:marked + We cannot know this simply by looking at the `CrisisCenterComponent` alone. + We can't tell that it is a *child* routing component. + We can't tell that its routes are child routes; they are indistinguiable from top level application routes. + + Such ignorance is intentional. The *Crisis Center* shouldn't know that it is the child of anything. + Today it is a child component one level down. + Tomorrow it might be the top level component of its own application. + Next month it might be re-purposed in a different application. + The *Crisis Center* itself is indifferent to these possibilities. + + *We* make it a child component of our application by reconfiguring the routes of the top level `AppComponent`. +:marked + ### Parent Route Configuration + Here is the revised route configuration for the parent `AppComponent`: ++makeExample('router-deprecated/ts/app/app.component.ts', 'route-config', 'app/app.component.ts (routes only)' ) +:marked + The last two *Hero* routes haven't changed. + + The first *Crisis Center* route has changed — *significantly* — and we've formatted it to draw attention to the differences: ++makeExample('router-deprecated/ts/app/app.component.ts', 'route-config-cc')(format=".") +:marked + Notice that the **path ends with a slash and three trailing periods (`/...`)**. + + That means this is an incomplete route (a ***non-terminal route***). The finished route will be some combination of + the parent `/crisis-center/` route and a route from the **child router** that belongs to the designated component. + + All is well. + The parent route's designated component is the `CrisisCenterComponent` which is a *Routing Component* with its own router and routes. + + + ### Default route + The other important change is the addition of the `useAsDefault` property. + Its value is `true` which makes *this* route the *default* route. + When the application launches, in the absence of any routing information from the browser's URL, the router + will default to the *Crisis Center*. That's our plan. + + ### Routing to the Child + + We've set the top level default route to go to the `CrisisCenterComponent`. + The final route will be a combination of `/crisis-center/` + and one of the child `CrisisCenterComponent` router's two routes. Which one? + + It could be either of them. In the absence of additional information, the router can't decide and must throw an error. + + We've tried the sample application and it didn't fail. We must have done something right. + + Look at the end of the child `CrisisCenterComponent`s first route. ++makeExample('router-deprecated/ts/app/crisis-center/crisis-center.component.1.ts', 'default-route', 'app/crisis-center/crisis-center.component.ts (default route)')(format=".") +:marked + We see `useAsDefault: true` once again. + That tells the router to compose the final URL using the path from the default *child* route. + Concatenate the base URL with the parent path, `/crisis-center/`, and the child path, `/`. + Remove superfluous slashes. We get: +code-example(format=""). + localhost:3000/crisis-center/ + +.l-main-section +:marked + + ## Router Lifecycle Hooks + + Angular components have [lifecycle hooks](lifecycle-hooks.html). For example, Angular calls the hook methods of the + [OnInit](../api/core/OnInit-interface.html) and [OnDestroy](../api/core/OnDestroy-interface.html) + interfaces when it creates and destroys components. + + The router also has hooks for *its* lifecycle such as + [CanActivate](../api/router-deprecated/index/CanActivate-decorator.html), [OnActivate](../api/router-deprecated/index/OnActivate-interface.html), and + [CanDeactivate](../api/router-deprecated/index/CanDeactivate-interface.html). + These three hooks can change the way the router navigates *to* a component or *away* from a component. + + The router lifecycle hooks *supplement* the component lifecycle hooks. + We still need the component hooks but the router hooks do what the component hooks cannot. + For example, the component hooks can't stop component creation or destruction. + They can't pause view navigation to wait for an asynchronous process to finish because they are synchronous. + + A *router* hook can permit or prevent a navigation. + If the hook returns `true`, the navigation proceeds; if it returns `false`, the + router cancels the navigation and stays on the current view. + A hook can also tell the router to navigate to a *different* component. + + Router hook methods can act synchronously by returning a boolean value directly or + act asynchronously by returning a promise that resolves to a boolean. + + Let's look at `CanDeactivate`, one of the most important router hooks. +.l-sub-section + :marked + We'll examine other router hooks in a future update to this chapter. + +:marked + ### *CanDeactivate*: handling unsaved changes + + Back in the "Heroes" workflow, the app accepts every change to a hero immediately without hesitation or validation. + + In the real world, we might have to accumulate the users changes. + We might have to validate across fields. We might have to validate on the server. + We might have to hold changes in a pending state until the user confirms them *as a group* or + cancels and reverts all changes. + + What do we do about unapproved, unsaved changes when the user navigates away? + We can't just leave and risk losing the user's changes; that would be a terrible experience. + + We'd like to pause and let the user decide what to do. + If the user cancels, we'll stay put and allow more changes. + If the user approves, the app can save. + + We still might delay navigation until the save succeeds. + If we let the user move to the next screen immediately and + the save failed (perhaps the data are ruled invalid), we would have lost the context of the error. + + We can't block while waiting for the server — that's not possible in a browser. + We need to stop the navigation while we wait, asynchronously, for the server + to return with its answer. + + We need the `CanDeactivate` hook. + + ### Cancel and Save + + Our sample application doesn't talk to a server. + Fortunately, we have another way to demonstrate an asynchronous router hook. + + Users update crisis information in the `CrisisDetailComponent`. + Unlike the `HeroDetailComponent`, the user changes do not update the + crisis entity immediately. We update the entity when the user presses the *Save* button. + We discard the changes if the user presses he *Cancel* button. + + Both buttons navigate back to the crisis list after save or cancel. ++makeExample('router-deprecated/ts/app/crisis-center/crisis-detail.component.1.ts', 'cancel-save', 'crisis-detail.component.ts (excerpt)')(format=".") +:marked + What if the user tries to navigate away without saving or canceling? + The user could push the browser back button or click the heroes link. + Both actions trigger a navigation. + Should the app save or cancel automatically? + + We'll do neither. Instead we'll ask the user to make that choice explicitly + in a confirmation dialog box that *waits asynchronously for the user's + answer*. +.l-sub-section + :marked + We could wait for the user's answer with synchronous, blocking code. + Our app will be more responsive ... and can do other work ... + by waiting for the user's answer asynchronously. Waiting for the user asynchronously + is like waiting for the server asynchronously. +:marked + The `DialogService` (injected in the `AppComponent` for app-wide use) does the asking. + + It returns a [promise](http://exploringjs.com/es6/ch_promises.html) that + *resolves* when the user eventually decides what to do: either + to discard changes and navigate away (`true`) or to preserve the pending changes and stay in the crisis editor (`false`). + + + +:marked + We execute the dialog inside the router's `routerCanDeactivate` lifecycle hook method. ++makeExample('router-deprecated/ts/app/crisis-center/crisis-detail.component.1.ts', 'routerCanDeactivate', 'crisis-detail.component.ts (excerpt)') +:marked + Notice that the `routerCanDeactivate` method *can* return synchronously; + it returns `true` immediately if there is no crisis or there are no pending changes. + But it can also return a promise and the router will wait for that promise to resolve to truthy (navigate) or falsey (stay put). + + **Two critical points** + 1. The router hook is optional. We don't inherit from a base class. We simply implement the interface method or not. + + 1. We rely on the router to call the hook. We don't worry about all the ways that the user + could navigate away. That's the router's job. + We simply write this method and let the router take it from there. + + The relevant *Crisis Center* code for this milestone is + ++makeTabs( + `router-deprecated/ts/app/crisis-center/crisis-center.component.ts, + router-deprecated/ts/app/crisis-center/crisis-list.component.1.ts, + router-deprecated/ts/app/crisis-center/crisis-detail.component.1.ts, + router-deprecated/ts/app/crisis-center/crisis.service.ts + `, + null, + `crisis-center.component.ts, + crisis-list.component.ts, + crisis-detail.component.ts, + crisis.service.ts, + `) + + + + +.l-main-section +:marked + ## Milestone #4: Query Parameters + + We use [*route parameters*](#route-parameters) to specify a *required* parameterized value *within* the route URL + as we do when navigating to the `HeroDetailComponent` in order to view-and-edit the hero with *id:15*. +code-example(format="." language="bash"). + localhost:3000/hero/15 +:marked + Sometimes we wish to add *optional* information to a route request. + For example, the `HeroListComponent` doesn't need help to display a list of heroes. + But it might be nice if the previously-viewed hero were pre-selected when returning from the `HeroDetailComponent`. +figure.image-display + img(src='/resources/images/devguide/router/selected-hero.png' alt="Selected hero") +:marked + That becomes possible if we can include hero Magneta's `id` in the URL when we + return from the `HeroDetailComponent`, a scenario we'll pursue in a moment. + + Optional information takes other forms. Search criteria are often loosely structured, e.g., `name='wind*'`. + Multiple values are common — `after='12/31/2015' & before='1/1/2017'` — in no particular order — + `before='1/1/2017' & after='12/31/2015'` — in a variety of formats — `during='currentYear'` . + + These kinds of parameters don't fit easily in a URL *path*. Even if we could define a suitable URL token scheme, + doing so greatly complicates the pattern matching required to translate an incoming URL to a named route. + + The **URL query string** is the ideal vehicle for conveying arbitrarily complex information during navigation. + The query string isn't involved in pattern matching and affords enormous flexiblity of expression. + Almost anything serializable can appear in a query string. + + The Component Router supports navigation with query strings as well as route parameters. + We define query string parameters in the *route parameters object* just like we do with route parameters. + + + ### Route Parameters or Query Parameters? + + There is no hard-and-fast rule. In general, + + *prefer a route parameter when* + * the value is required. + * the value is necessary to distinguish one route path from another. + + *prefer a query parameter when* + * the value is optional. + * the value is complex and/or multi-variate. + + + ### Route parameters object + When navigating to the `HeroDetailComponent` we specified the `id` of the hero-to-edit in the + *route parameters object* and made it the second item of the [*link parameters array*](#link-parameters-array). + ++makeExample('router-deprecated/ts/app/heroes/hero-list.component.1.ts','link-parameters-array')(format=".") +:marked + The router embedded the `id` value in the navigation URL because we had defined it + as a route parameter with an `:id` placeholder token in the route `path`: ++makeExample('router-deprecated/ts/app/app.component.2.ts','hero-detail-route')(format=".") +:marked + When the user clicks the back button, the `HeroDetailComponent` constructs another *link parameters array* + which it uses to navigate back to the `HeroListComponent`. ++makeExample('router-deprecated/ts/app/heroes/hero-detail.component.1.ts','gotoHeroes')(format=".") +:marked + This array lacks a route parameters object because we had no reason to send information to the `HeroListComponent`. + + Now we have a reason. We'd like to send the id of the current hero with the navigation request so that the + `HeroListComponent` can highlight that hero in its list. + + We do that with a route parameters object in the same manner as before. + We also defined a junk parameter (`foo`) that the `HeroListComponent` should ignore. + Here's the revised navigation statement: ++makeExample('router-deprecated/ts/app/heroes/hero-detail.component.ts','gotoHeroes-navigate')(format=".") +:marked + The application still works. Clicking "back" returns to the hero list view. + + Look at the browser address bar. +.l-sub-section + img(src='/resources/images/devguide/plunker-separate-window-button.png' alt="pop out the window" align="right" style="margin-right:-20px") + :marked + When running in plunker, pop out the preview window by clicking the blue 'X' button in the upper right corner. +:marked + It should look something like this, depending on where you run it: +code-example(format="." language="bash"). + localhost:3000/heroes?id=15&foo=foo +:marked + The `id` value appears in the query string (`?id=15&foo=foo`), not in the URL path. + The path for the "Heroes" route doesn't have an `:id` token. + +.alert.is-helpful + :marked + The router replaces route path tokens with corresponding values from the route parameters object. + **Every parameter _not_ consumed by a route path goes in the query string.** +:marked + ### Query parameters in the *RouteParams* service + + The list of heroes is unchanged. No hero row is highlighted. + +.l-sub-section + :marked + The [live example](/resources/live-examples/router-deprecated/ts/plnkr.html) *does* highlight the selected + row because it demonstrates the final state of the application which includes the steps we're *about* to cover. + At the moment we're describing the state of affairs *prior* to those steps. +:marked + The `HeroListComponent` isn't expecting any parameters at all and wouldn't know what to do with them. + Let's change that. + + When navigating from the `HeroListComponent` to the `HeroDetailComponent` + the router picked up the route parameter object and made it available to the `HeroDetailComponent` + in the `RouteParams` service. We injected that service in the constructor of the `HeroDetailComponent`. + + This time we'll be navigating in the opposite direction, from the `HeroDetailComponent` to the `HeroListComponent`. + This time we'll inject the `RouteParams` service in the constructor of the `HeroListComponent`. + + First we extend the router import statement to include the `RouteParams` service symbol; ++makeExample('router-deprecated/ts/app/heroes/hero-list.component.ts','import-route-params', 'hero-list.component.ts (import)')(format=".") +:marked + Then we extend the constructor to inject the `RouteParams` service and extract the `id` parameter as the `selectedId`: ++makeExample('router-deprecated/ts/app/heroes/hero-list.component.ts','ctor', 'hero-list.component.ts (constructor)')(format=".") +.l-sub-section + :marked + All route parameters are strings. + The (+) in front of the `routeParameters.get` expression is a JavaScript trick to convert the string to an integer. +:marked + We add an `isSelected` method that returns true when a hero's id matches the selected id. ++makeExample('router-deprecated/ts/app/heroes/hero-list.component.ts','isSelected', 'hero-list.component.ts (constructor)')(format=".") +:marked + Finally, we update our template with a [Class Binding](template-syntax.html#class-binding) to that `isSelected` method. + The binding adds the `selected` CSS class when the method returns `true` and removes it when `false`. + Look for it within the repeated `
  • ` tag as shown here: ++makeExample('router-deprecated/ts/app/heroes/hero-list.component.ts','template', 'hero-list.component.ts (template)')(format=".") +:marked + When the user navigates from the heroes list to the "Magneta" hero and back, "Magneta" appears selected: +figure.image-display + img(src='/resources/images/devguide/router/selected-hero.png' alt="Selected List" ) +:marked + The `foo` query string parameter is harmless and continues to be ignored. + + ### Child Routers and Query Parameters + + We can define query parameters for child routers too. + + The technique is precisely the same. + In fact, we made exactly the same changes to the *Crisis Center* feature. + Confirm the similarities in these *Hero* and *CrisisCenter* components, + arranged side-by-side for easy comparison: ++makeTabs( + `router-deprecated/ts/app/heroes/hero-list.component.ts, + router-deprecated/ts/app/crisis-center/crisis-list.component.ts, + router-deprecated/ts/app/heroes/hero-detail.component.ts, + router-deprecated/ts/app/crisis-center/crisis-detail.component.ts + `, + null, + `hero-list.component.ts, + crisis-list.component.ts, + hero-detail.component.ts, + crisis-detail.component.ts + `) +:marked + When we navigate back from a `CrisisDetailComponent` that is showing the *Asteroid* crisis, + we see that crisis properly selected in the list like this: +figure.image-display + img(src='/resources/images/devguide/router/selected-crisis.png' alt="Selected crisis" ) +:marked + **Look at the browser address bar again**. It's *different*. It looks something like this: +code-example(format="." language="bash"). + localhost:3000/crisis-center/;id=3;foo=foo +:marked + The query string parameters are no longer separated by "?" and "&". + They are **separated by semicolons (;)** + This is *matrix URL* notation — something we may not have seen before. +.l-sub-section + :marked + *Matrix URL* notation is an idea first floated + in a [1996 proposal](http://www.w3.org/DesignIssues/MatrixURIs.html) by the founder of the web, Tim Berners-Lee. + + Although matrix notation never made it into the HTML standard, it is legal and + it became popular among browser routing systems as a way to isolate parameters + belonging to parent and child routes. The Angular Component Router is such a system. + + The syntax may seem strange to us but users are unlikely to notice or care + as long as the URL can be emailed and pasted into a browser address bar + as this one can. + + + +.l-main-section +:marked + ## Wrap Up + As we end our chapter, we take a parting look at + the entire application. + + We can always try the [live example](/resources/live-examples/router-deprecated/ts/plnkr.html) and download the source code from there. + + Our final project folder structure looks like this: +.filetree + .file router-sample + .children + .file app + .children + .file crisis-center/... + .file heroes/... + .file app.component.ts + .file dialog.service.ts + .file main.ts + .file node_modules ... + .file typings ... + .file index.html + .file package.json + .file styles.css + .file tsconfig.json + .file typings.json +:marked + The pertinent top level application files are ++makeTabs( + `router-deprecated/ts/app/app.component.ts, + router-deprecated/ts/app/main.ts, + router-deprecated/ts/app/dialog.service.ts, + router-deprecated/ts/index.html + `, + null, + `app.component.ts, + main.ts, + dialog.service.ts, + index.html + `) +:marked + + ### Crisis Center + The *Crisis Center* feature area within the `crisis-center` folder follows: +.filetree + .file app + .children + .file crisis-center + .children + .file crisis-center.component.ts + .file crisis-detail.component.ts + .file crisis-list.component.ts + .file crisis.service.ts +:marked ++makeTabs( + `router-deprecated/ts/app/crisis-center/crisis-center.component.ts, + router-deprecated/ts/app/crisis-center/crisis-list.component.ts, + router-deprecated/ts/app/crisis-center/crisis-detail.component.ts, + router-deprecated/ts/app/crisis-center/crisis.service.ts + `, + null, + `crisis-center.component.ts, + crisis-list.component.ts, + crisis-detail.component.ts, + crisis.service.ts, + `) +:marked + ### Heroes + The *Heroes* feature area within the `heroes` folder is next: +.filetree + .file app + .children + .file heroes + .children + .file hero-detail.component.ts + .file hero-list.component.ts + .file hero.service.ts +:marked ++makeTabs( + `router-deprecated/ts/app/heroes/hero-list.component.ts, + router-deprecated/ts/app/heroes/hero-detail.component.ts, + router-deprecated/ts/app/heroes/hero.service.ts + `, + null, + `hero-list.component.ts, + hero-detail.component.ts, + hero.service.ts + `) +:marked + + +.l-main-section +:marked + ## Appendices + The balance of this chapter is a set of appendices that + elaborate some of the points we covered quickly above. + + The appendix material isn't essential. Continued reading is for the curious. + + +.l-main-section + +:marked + ## Link Parameters Array + We've mentioned the *Link Parameters Array* several times. We've used it several times. + + We've bound the `RouterLink` directive to such an array like this: ++makeExample('router-deprecated/ts/app/app.component.3.ts', 'h-anchor')(format=".") +:marked + We've written a two element array when specifying a route parameter like this ++makeExample('router-deprecated/ts/app/heroes/hero-list.component.1.ts', 'nav-to-detail')(format=".") +:marked + These two examples cover our needs for an app with one level routing. + The moment we add a child router, such as the *Crisis Center*, we create new link array possibilities. + + Recall that we specified a default child route for *Crisis Center* so this simple `RouterLink` is fine. ++makeExample('router-deprecated/ts/app/app.component.3.ts', 'cc-anchor-w-default')(format=".") +:marked + *If we had not specified a default route*, our single item array would fail + because we didn't tell the router which child route to use. ++makeExample('router-deprecated/ts/app/app.component.3.ts', 'cc-anchor-fail')(format=".") +:marked + We'd need to write our anchor with a link array like this: ++makeExample('router-deprecated/ts/app/app.component.3.ts', 'cc-anchor-no-default')(format=".") +:marked + Let's parse it out. + * The first item in the array identifies the parent route ('CrisisCenter'). + * There are no parameters for this parent route so we're done with it. + * There is no default for the child route so we need to pick one. + * We decide to go to the `CrisisListComponent` whose route name is 'CrisisList' + * So we add that 'CrisisList' as the second item in the array. + * Voila! `['CrisisCenter', 'CrisisList']`. + + Let's take it a step further. + This time we'll build a link parameters array that navigates from the root of the application + down to the "Dragon Crisis". + + * The first item in the array identifies the parent route ('CrisisCenter'). + * There are no parameters for this parent route so we're done with it. + * The second item identifies the child route for details about a particular crisis ('CrisisDetail'). + * The details child route requires an `id` route parameter + * We add `id` of the *Dragon Crisis* as the third item in the array (`{id:1}`) + + It looks like this! ++makeExample('router-deprecated/ts/app/app.component.3.ts', 'Dragon-anchor')(format=".") +:marked + If we wanted to, we could redefine our `AppComponent` template with *Crisis Center* routes exclusively: ++makeExample('router-deprecated/ts/app/app.component.3.ts', 'template')(format=".") +:marked + In sum, we can write applications with one, two or more levels of routing. + The link parameters array affords the flexibility to represent any routing depth and + any legal sequence of route names and (optional) route parameter objects. + + +.l-main-section +:marked + ## Appendix: Why use an *ngOnInit* method + + We implemented an `ngOnInit` method in many of our Component classes. + We did so, for example, in the [HeroDetailComponent](#hero-detail-ctor). + We might have put the `ngOnInit` logic inside the constructor instead. We didn't for a reason. The reason is *testability*. + + A constructor that has major side-effects can be difficult to test because it starts doing things as soon as + we create a test instance. In this case, it might have made a request to a remote server, something it shouldn't + do under test. It may even be impossible to reach the server in the test environment. + + The better practice is to limit what the constructor can do. Mostly it should stash parameters in + local variables and perform simple instance configuration. + + Yet we want an instance of this class to get the hero data from the `HeroService` soon after it is created. + How do we ensure that happens if not in the constructor? + + Angular detects when a component has certain lifecycle methods like + [ngOnInit](../api/core/OnInit-interface.html) and + [ngOnDestroy](../api/core/OnDestroy-interface.html) and calls + them + at the appropriate moment. + + Angular will call `ngOnInit` when we navigate to the `HeroDetailComponent`, we'll get the `id` from the `RouteParams` + and ask the server for the hero with that `id`. + + We too can call that `ngOnInit` method in our tests if we wish ... after taking control of the injected + `HeroService` and (perhaps) mocking it. + + + +.l-main-section +:marked + ## Appendix: *LocationStrategy* and browser URL styles + + When the router navigates to a new component view, it updates the browser's location and history + with a URL for that view. + This is a strictly local URL. The browser shouldn't send this URL to the server + and should not reload the page. + + Modern HTML 5 browsers support + [history.pushState](https://developer.mozilla.org/en-US/docs/Web/API/History_API#Adding_and_modifying_history_entries), + a technique that changes a browser's location and history without triggering a server page request. + The router can compose a "natural" URL that is indistinguishable from + one that would otherwise require a page load. + + Here's the *Crisis Center* URL in this "HTML 5 pushState" style: +code-example(format=".", language="bash"). + localhost:3002/crisis-center/ +:marked + Older browsers send page requests to the server when the location URL changes ... + unless the change occurs after a "#" (called the "hash"). + Routers can take advantage of this exception by composing in-application route + URLs with hashes. Here's a "hash URL" that routes to the *Crisis Center* +code-example(format=".", language="bash"). + localhost:3002/src/#/crisis-center/ +:marked + The Angular Component Router supports both styles with two `LocationStrategy` providers: + 1. `PathLocationStrategy` - the default "HTML 5 pushState" style. + 1. `HashLocationStrategy` - the "hash URL" style. + + The router's `ROUTER_PROVIDERS` array sets the `LocationStrategy` to the `PathLocationStrategy`, + making it the default strategy. + We can switch to the `HashLocationStrategy` with an override during the bootstrapping process if we prefer it. +.l-sub-section + :marked + Learn about "providers" and the bootstrap process in the + [Dependency Injection chapter](dependency-injection#bootstrap) +:marked + ### Which Strategy is Best? + We must choose a strategy and we need to make the right call early in the project. + It won't be easy to change later once the application is in production + and there are lots of application URL references in the wild. + + Almost all Angular 2 projects should use the default HTML 5 style. + It produces URLs that are easier for users to understand. + And it preserves the option to do **server-side rendering** later. + + Rendering critical pages on the server is a technique that can greatly improve + perceived responsiveness when the app first loads. + An app that would otherwise take ten or more seconds to start + could be rendered on the server and delivered to the user's device + in less than a second. + + This option is only available if application URLs look like normal web URLs + without hashes (#) in the middle. + + Stick with the default unless you have a compelling reason to + resort to hash routes. + + ### HTML 5 URLs and the *<base href>* + While the router uses the "[HTML 5 pushState](https://developer.mozilla.org/en-US/docs/Web/API/History_API#Adding_and_modifying_history_entries)" + style by default, we *must* configure that strategy with a **base href** + + The preferred way to configure the strategy is to add a + [<base href> element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base) tag + in the `` of the `index.html`. ++makeExample('router-deprecated/ts/index.1.html','base-href')(format=".") +:marked + Without that tag, the browser may not be able to load resources + (images, css, scripts) when "deep linking" into the app. + Bad things could happen when someone pastes an application link into the + browser's address bar or clicks such a link in an email link. + + Some developers may not be able to add the `` element, perhaps because they don't have + access to `` or the `index.html`. + + Those developers may still use HTML 5 URLs by taking two remedial steps: + + 1. Provide the router with an appropriate `APP_BASE_HREF` value. + 1. Use **absolute URLs** for all web resources: css, images, scripts, and template html files. + +.l-sub-section + :marked + Learn about the [APP_BASE_HREF](../api/router/APP_BASE_HREF-let.html) + in the API Guide. +:marked + ### *HashLocationStrategy* + We can go old-school with the `HashLocationStrategy` by + providing it as the router's `LocationStrategy` during application bootstrapping. + + First, import the `provide` symbol for Dependency Injection and the + `Location` and `HashLocationStrategy` symbols from the router. + + Then *override* the default strategy defined in `ROUTE_PROVIDERS` by + providing the `HashLocationStrategy` later in the `bootstrap` providers array argument: ++makeExample('router-deprecated/ts/app/main.2.ts','', 'main.ts (hash URL strategy)') diff --git a/public/docs/ts/latest/guide/router.jade b/public/docs/ts/latest/guide/router.jade index 29d2c0a12e..babc9a925b 100644 --- a/public/docs/ts/latest/guide/router.jade +++ b/public/docs/ts/latest/guide/router.jade @@ -1,4 +1,10 @@ include ../_util-fns +.alert.is-critical + :marked + This chapter is a *work in progress*. + + It describes the *release candidate* Component Router which + replaces the [*beta* router](router-deprecated.html). :marked The Angular ***Component Router*** enables navigation from one [view](./glossary.html#view) to the next @@ -34,17 +40,17 @@ include ../_util-fns We'll learn many router details in this chapter which covers - * Setting the [base href](#base-href) - * Importing from the [router library](#import) + * setting the [base href](#base-href) + * importing from the [router library](#import) * [configuring a router](#route-config) * the [link parameters array](#link-parameters-array) that propels router navigation * navigating when the user clicks a data-bound [RouterLink](#router-link) * navigating under [program control](#navigate) - * embedding critical information in the URL with [route parameters](#route-parameters) + * embedding critical information in the URL with [positional parameters](#positional-parameters) * creating a [child router](#child-router) with its own routes * setting a [default route](#default) * confirming or canceling navigation with [router lifecycle hooks](#lifecycle-hooks) - * passing optional information in [query parameters](#query-parameters) + * passing optional information in [matrix parameters](#matrix-parameters) * choosing the "HTML5" or "hash" [URL style](#browser-url-styles) We proceed in phases marked by milestones building from a simple two-pager with placeholder views @@ -65,7 +71,7 @@ include ../_util-fns If the `app` folder is the application root, as it is for our sample application, set the `href` value *exactly* as shown here. -+makeExample('router/ts/index.html','base-href', 'index.html (base href)')(format=".") ++makeExample('router/ts/index.1.html','base-href', 'index.html (base href)')(format=".") :marked ### Router imports @@ -299,7 +305,7 @@ figure.image-display If the `app` folder is the application root, as it is for our application, set the `href` value in **`index.html`** *exactly* as shown here. -+makeExample('router/ts/index.html','base-href', 'index.html (base href)')(format=".") ++makeExample('router/ts/index.1.html','base-href', 'index.html (base href)')(format=".") .l-sub-section :marked HTML 5 style navigation is the Component Router default. @@ -598,7 +604,7 @@ code-example(format="." language="bash"). This array is similar to the *link parameters array* we met [earlier](#shell-template) in an anchor tag while binding to the `RouterLink` directive. This time we see it in code rather than in HTML. - + ### Setting the route parameters object We're navigating to the `HeroDetailComponent` where we expect to see the details of the selected hero. @@ -1007,13 +1013,13 @@ code-example(format=""). `) - + .l-main-section :marked ## Milestone #4: Query Parameters - We use [*route parameters*](#route-parameters) to specify a *required* parameterized value *within* the route URL + We use [*route parameters*](#positional-parameters) to specify a *required* parameterized value *within* the route URL as we do when navigating to the `HeroDetailComponent` in order to view-and-edit the hero with *id:15*. code-example(format="." language="bash"). localhost:3000/hero/15 @@ -1054,7 +1060,7 @@ figure.image-display * the value is optional. * the value is complex and/or multi-variate. - + ### Route parameters object When navigating to the `HeroDetailComponent` we specified the `id` of the hero-to-edit in the *route parameters object* and made it the second item of the [*link parameters array*](#link-parameters-array). @@ -1122,7 +1128,7 @@ code-example(format="." language="bash"). First we extend the router import statement to include the `RouteParams` service symbol; +makeExample('router/ts/app/heroes/hero-list.component.ts','import-route-params', 'hero-list.component.ts (import)')(format=".") :marked - Then we extend the constructor to inject the `RouteParams` service and extract the `id` parameter as the `_selectedId`: + Then we extend the constructor to inject the `RouteParams` service and extract the `id` parameter as the `selectedId`: +makeExample('router/ts/app/heroes/hero-list.component.ts','ctor', 'hero-list.component.ts (constructor)')(format=".") .l-sub-section :marked @@ -1443,7 +1449,7 @@ code-example(format=".", language="bash"). The preferred way to configure the strategy is to add a [<base href> element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base) tag in the `` of the `index.html`. -+makeExample('router/ts/index.html','base-href')(format=".") ++makeExample('router/ts/index.1.html','base-href')(format=".") :marked Without that tag, the browser may not be able to load resources (images, css, scripts) when "deep linking" into the app. diff --git a/public/docs/ts/latest/guide/server-communication.jade b/public/docs/ts/latest/guide/server-communication.jade index 81ee12f07a..f630ac1d07 100644 --- a/public/docs/ts/latest/guide/server-communication.jade +++ b/public/docs/ts/latest/guide/server-communication.jade @@ -1,5 +1,5 @@ - -include ../_util-fns +block includes + include ../_util-fns :marked [HTTP](https://tools.ietf.org/html/rfc2616) is the primary protocol for browser/server communication. .l-sub-section @@ -14,34 +14,37 @@ include ../_util-fns The Angular HTTP client library simplifies application programming of the **XHR** and **JSONP** APIs as we'll learn in this chapter covering: - - [Http client sample overview](#http-client)
    - [Fetch data with http.get](#fetch-data)
    - [RxJS Observable of HTTP Responses](#rxjs)
    - [Enabling RxJS Operators](#enable-rxjs-operators)
    - [Extract JSON data with RxJS map](#map)
    - [Error handling](#error-handling)
    - [Send data to the server](#update)
    - [Add headers](#headers)
    - [Promises instead of observables](#promises)
    - [JSONP](#jsonp)
    - [Set query string parameters](#search-parameters)
    - [Debounce search term input](#more-observables)
    - [Appendix: the in-memory web api service](#in-mem-web-api)
    - - We illustrate these topics with code that you can - [run live in a browser](/resources/live-examples/server-communication/ts/plnkr.html). +ul + li #[a(href="#http-client") Http client sample overview] + li #[a(href="#fetch-data") Fetch data with http.get] + +ifDocsFor('ts') + li #[a(href="#rxjs") RxJS Observable of HTTP Responses] + li #[a(href="#enable-rxjs-operators") Enabling RxJS Operators] + li #[a(href="#extract-data") Extract JSON data] + li #[a(href="#error-handling") Error handling] + li #[a(href="#update") Send data to the server] + +ifDocsFor('ts') + li #[a(href="#promises") Promises instead of observables] + li #[a(href="#cross-origin-requests") Cross-origin requests: Wikipedia example] + +ifDocsFor('ts') + ul + li #[a(href="#search-parameters") Set query string parameters] + li #[a(href="#more-observables") Debounce search term input] + li #[a(href="#in-mem-web-api") Appendix: the in-memory web api service] +p. + We illustrate these topics with code that you can + #[+liveExampleLink2('run live in a browser', 'server-communication')]. .l-main-section +a#http-client :marked - ## The *Http* Client Demo We use the Angular `Http` client to communicate via `XMLHttpRequest (XHR)`. We'll demonstrate with a mini-version of the [tutorial](../tutorial)'s "Tour of Heroes" (ToH) application. - This version gets some heroes from the server, displays them in a list, lets us add new heroes, and save them to the server. + This version gets some heroes from the server, displays them in a list, lets us add new heroes, and saves them to the server. It works like this. figure.image-display @@ -56,39 +59,41 @@ figure.image-display We're making a point about application structure that is easier to justify when the app grows. :marked Here is the `TohComponent` shell: -+makeExample('server-communication/ts/app/toh/toh.component.ts', null, 'app/toh.component.ts') -:marked - As usual, we import the symbols we need. The newcomer is `HTTP_PROVIDERS`, - an array of service providers from the Angular HTTP library. - We'll be using that library to access the server. - We also import a `HeroService` that we'll look at shortly. - - The component specifies both the ``HTTP_PROVIDERS` and the `HeroService` in the metadata `providers` array, - making them available to the child components of this "Tour of Heroes" application. ++makeExample('server-communication/ts/app/toh/toh.component.ts', '', 'app/toh/toh.component.ts') -.l-sub-section +block http-providers :marked - Alternatively, we may choose to add the `HTTP_PROVIDERS` while bootstrapping the app: - +makeExample('server-communication/ts/app/main.ts','http-providers','app/main.ts')(format='.') - :marked - Learn about providers in the [Dependency Injection](dependency-injection.html) chapter. + As usual, we import the symbols we need. The newcomer is `HTTP_PROVIDERS`, + an array of service providers from the Angular HTTP library. + We'll be using that library to access the server. + We also import a `HeroService` that we'll look at shortly. + + The component specifies both the ``HTTP_PROVIDERS` and the `HeroService` in the metadata `providers` array, + making them available to the child components of this "Tour of Heroes" application. + + .l-sub-section + :marked + Alternatively, we may choose to add the `HTTP_PROVIDERS` while bootstrapping the app: + +makeExample('server-communication/ts/app/main.ts','http-providers','app/main.ts')(format='.') + :marked + Learn about providers in the [Dependency Injection](dependency-injection.html) chapter. :marked This sample only has one child, the `HeroListComponent`. Here's its template: -+makeExample('server-communication/ts/app/toh/hero-list.component.html', null, 'app/toh/hero-list.component.html (Template)') ++makeExample('server-communication/ts/app/toh/hero-list.component.html', null, 'app/toh/hero-list.component.html (template)') :marked - The component template displays a list of heroes with the `NgFor` repeater directive. + The component template displays a list of heroes with the `ngFor` repeater directive. figure.image-display img(src='/resources/images/devguide/server-communication/hero-list.png' alt="Hero List") :marked Beneath the heroes is an input box and an *Add Hero* button where we can enter the names of new heroes and add them to the database. - We use a [template reference variable](template-syntax.html#ref-vars), `newHero`, to access the + We use a [template reference variable](template-syntax.html#ref-vars), `newHeroName`, to access the value of the input box in the `(click)` event binding. When the user clicks the button, we pass that value to the component's `addHero` method and then clear it to make ready for a new hero name. - Below the button is a (hidden) area for an error message. + Below the button is an area for an error message. a(id="oninit") a(id="HeroListComponent") @@ -115,12 +120,14 @@ a(id="HeroListComponent") This is a "best practice". Components are easier to test and debug when their constructors are simple and all real work (especially calling a remote server) is handled in a separate method. +block getheroes-and-addhero + :marked + The service's `getHeroes()` and `addHero()` methods return an `Observable` of HTTP hero data. + We subscribe to this `Observable`, + specifying the actions to take when the request succeeds or fails. + We'll get to observables and subscription shortly. + :marked - The service `get` and `addHero` methods return an `Observable` of HTTP hero data. - We subscribe to this `Observable`, - specifying the actions to take when the request succeeds or fails. - We'll get to observables and subscription shortly. - With our basic intuitions about the component squared away, we can turn to development of the backend data source and the client-side `HeroService` that talks to it. @@ -130,20 +137,22 @@ a(id="HeroListComponent") returning mock heroes in a service like this one: +makeExample('toh-4/ts/app/hero.service.ts', 'just-get-heroes')(format=".") :marked - In this chapter, we get the heroes from the server using Angular's own HTTP Client service. + In this chapter, we get the heroes from the server using a (browser-based) HTTP client service. Here's the new `HeroService`: - +makeExample('server-communication/ts/app/toh/hero.service.ts', 'v1', 'app/toh/hero.service.ts') -:marked - We begin by importing Angular's `Http` client service and - [inject it](dependency-injection.html) into the `HeroService` constructor. - `Http` is not part of the Angular core. It's an optional service in its own `@angular/http` library. - Moreover, we would need to install this library separately and load it in `system.js`. - All of our Developer Guide samples have this library installed. -+makeExample('server-communication/ts/systemjs.config.1.js', 'package-names', 'systemjs.config.js', { pnk: /('@angular\/http.*)/g})(format=".") +block http-client-service + :marked + The imported `Http` client service gets + [injected](dependency-injection.html) into the `HeroService` constructor. + .l-sub-section + :marked + `Http` is not part of the Angular core. It's an optional service in its own `@angular/http` library + that we installed with npm (see the `package.json`) and + registered for module loading by SystemJS (see `systemjs.config.js`) + :marked - Look closely at how we call `http.get` + Look closely at how we call `#{_priv}http.get` +makeExample('server-communication/ts/app/toh/hero.service.ts', 'http-get', 'app/toh/hero.service.ts (getHeroes)')(format=".") :marked We pass the resource URL to `get` and it calls the server which should return heroes. @@ -151,92 +160,85 @@ a(id="HeroListComponent") :marked It *will* return heroes once we've set up the [in-memory web api](in-mem-web-api) described in the appendix below. - Alternatively, we can (temporarily) target a JSON file by changing the endpoint URL: +makeExample('server-communication/ts/app/toh/hero.service.ts', 'endpoint-json')(format=".") -:marked - - The return value may surprise us. Many of us would expect a - [promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). - We'd expect to chain a call to `then()` and extract the heroes. - Instead we're calling a `map()` method. - Clearly this is not a promise. - In fact, the `http.get` method returns an **Observable** of HTTP Responses (`Observable`) from the RxJS library - and `map` is one of the RxJS *operators*. +block rxjs + :marked + + The return value may surprise us. Many of us would expect a + [promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). + We'd expect to chain a call to `then()` and extract the heroes. + Instead we're calling a `map()` method. + Clearly this is not a promise. + + In fact, the `http.get` method returns an **Observable** of HTTP Responses (`Observable`) from the RxJS library + and `map` is one of the RxJS *operators*. + + .l-main-section + :marked + ### RxJS Library + [RxJS](https://github.com/ReactiveX/RxJS) ("Reactive Extensions") is a 3rd party library, endorsed by Angular, + that implements the [*asynchronous observable*](https://www.youtube.com/watch?v=UHI0AzD_WfY "Rob Wormald on observables") pattern. + + All of our Developer Guide samples have installed the RxJS npm package and loaded via `system.js` + because observables are used widely in Angular applications. + We certainly need it now when working with the HTTP client. + And we must take a critical extra step to make RxJS observables usable. + + ### Enable RxJS Operators + The RxJS library is quite large. + Size matters when we build a production application and deploy it to mobile devices. + We should include only those features that we actually need. + + Accordingly, Angular exposes a stripped down version of `Observable` in the `rxjs/Observable` module, + a version that lacks most of the operators including some we'd like to use here + such as the `map` method we called above in `getHeroes`. + + It's up to us to add the operators we need. -.l-main-section -:marked - ### RxJS Library - [RxJS](https://github.com/ReactiveX/RxJS) ("Reactive Extensions") is a 3rd party library, endorsed by Angular, - that implements the [*asynchronous observable*](https://www.youtube.com/watch?v=UHI0AzD_WfY "Rob Wormald on observables") pattern. - - All of our Developer Guide samples have installed the RxJS npm package and loaded via `system.js` - because observables are used widely in Angular applications. -+makeExample('server-communication/ts/systemjs.config.1.js', 'rxjs', 'systemjs.config.js', {pnk: /('rxjs.*)/g})(format=".") -:marked - We certainly need it now when working with the HTTP client. - And we must take a critical extra step to make RxJS observables usable. - - ### Enable RxJS Operators - The RxJS library is quite large. - Size matters when we build a production application and deploy it to mobile devices. - We should include only those features that we actually need. - - Accordingly, Angular exposes a stripped down version of `Observable` in the `rxjs/Observable` module, - a version that lacks almost all operators including the ones we'd like to use here - such as the `map` method we called above in `getHeroes`. - - It's up to us to add the operators we need. - We could add each operator, one-by-one, until we had a custom *Observable* implementation tuned - precisely to our requirements. - - That would be a distraction today. We're learning HTTP, not counting bytes. - So we'll make it easy on ourselves and enrich *Observable* with the full set of operators. - It only takes one `import` statement. - It's best to add that statement early when we're bootstrapping the application. - : -+makeExample('server-communication/ts/app/main.ts', 'import-rxjs', 'app/main.ts (import rxjs)')(format=".") + We could add _every_ RxJS operators with a single import statement. + While that is the easiest thing to do, we'd pay a penalty in extended launch time and application size + because the full library is so big. We only use a few operators in our app. + + Instead, we'll import each operator, one-by-one, until we have a custom *Observable* implementation tuned + precisely to our requirements. We'll put the `import` statements in one `app/add-rxjs-operators.ts` file. + +makeExample('server-communication/ts/app/add-rxjs-operators.ts', null, 'app/add-rxjs-operators.ts')(format=".") + :marked + If we forget an operator, the compiler will warn that it's missing and we'll update this file. + .l-sub-section + :marked + We don't need _all_ of these particular operators in the `HeroService` — just `map` and `catch`. + We'll need the others later, in a *Wiki* example [below](#more-observables). + :marked + Finally, we import `add-rxjs-operator`_itself_ in our `main.ts`: + +makeExample('server-communication/ts/app/main.ts', 'import-rxjs', 'app/main.ts (import rxjs)')(format=".") -a(id="map") -a(id="extract-data") +a#extract-data :marked ### Process the response object - Remember that our `getHeroes` method mapped the `http.get` response object to heroes with an `extractData` helper method: -+makeExample('server-communication/ts/app/toh/hero.service.ts', 'extract-data', 'app/toh/hero.service.ts (extractData)')(format=".") + Remember that our `getHeroes()` method mapped the `#{_priv}http.get` response object to heroes with an `#{_priv}extractData` helper method: ++makeExample('server-communication/ts/app/toh/hero.service.ts', 'extract-data', 'app/toh/hero.service.ts (excerpt)')(format=".") :marked The `response` object does not hold our data in a form we can use directly. - To make it useful in our application we must - * check for a bad response - * parse the response data into a JSON object -.alert.is-important - :marked - *Beta alert*: error status interception and parsing may be absorbed within `http` when Angular is released. -:marked - #### Bad status codes - A status code outside the 200-300 range is an error from the _application point of view_ - but it is not an error from the _`http` point of view_. - For example, a `404 - Not Found` is a response like any other. - The request went out; a response came back; here it is, thank you very much. - We'd have an observable error only if `http` failed to operate (e.g., it errored internally). - - Because a status code outside the 200-300 range _is an error_ from the application point of view, - we intercept it and throw, moving the observable chain to the error path. - - The `catch` operator that is next in the `getHeroes` observable chain will handle our thrown error. + To make it useful in our application we must parse the response data into a JSON object #### Parse to JSON - The response data are in JSON string form. - We must parse that string into JavaScript objects which we do by calling `response.json()`. +block parse-json + :marked + The response data are in JSON string form. + We must parse that string into JavaScript objects which we do by calling `response.json()`. + + .l-sub-section + :marked + This is not Angular's own design. + The Angular HTTP client follows the ES2015 specification for the + [response object](https://fetch.spec.whatwg.org/#response-class) returned by the `Fetch` function. + That spec defines a `json()` method that parses the response body into a JavaScript object. + .l-sub-section :marked - This is not Angular's own design. - The Angular HTTP client follows the ES2015 specification for the - [response object](https://fetch.spec.whatwg.org/#response-class) returned by the `Fetch` function. - That spec defines a `json()` method that parses the response body into a JavaScript object. -.l-sub-section - :marked - We shouldn't expect `json()` to return the heroes array directly. + We shouldn't expect the decoded JSON to be the heroes #{_array} directly. The server we're calling always wraps JSON results in an object with a `data` property. We have to unwrap it to get the heroes. This is conventional web api behavior, driven by @@ -247,52 +249,52 @@ a(id="extract-data") Not all servers return an object with a `data` property. :marked ### Do not return the response object - Our `getHeroes()` could have returned the `Observable`. - - Bad idea! The point of a data service is to hide the server interaction details from consumers. + Our `getHeroes()` could have returned the HTTP response. Bad idea! + The point of a data service is to hide the server interaction details from consumers. The component that calls the `HeroService` wants heroes. It has no interest in what we do to get them. It doesn't care where they come from. And it certainly doesn't want to deal with a response object. - - -.callout.is-important - header HTTP GET is delayed - :marked - The `http.get` does **not send the request just yet!** This observable is - [*cold*](https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/creating.md#cold-vs-hot-observables) - which means the request won't go out until something *subscribes* to the observable. - That *something* is the [HeroListComponent](#subscribe). -a(id="error-handling") ++ifDocsFor('ts') + .callout.is-important + header HTTP GET is delayed + :marked + The `#{_priv}http.get` does **not send the request just yet!** This observable is + [*cold*](https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/creating.md#cold-vs-hot-observables) + which means the request won't go out until something *subscribes* to the observable. + That *something* is the [HeroListComponent](#subscribe). + +a#error-handling :marked ### Always handle errors - The eagle-eyed reader may have spotted our use of the `catch` operator in conjunction with a `handleError` method. - We haven't discussed so far how that actually works. Whenever we deal with I/O we must be prepared for something to go wrong as it surely will. - We should catch errors in the `HeroService` and do something with them. We may also pass an error message back to the component for presentation to the user but only if we can say something the user can understand and act upon. In this simple app we provide rudimentary error handling in both the service and the component. - - We use the Observable `catch` operator on the service level. - It takes an error handling function with an error object as the argument. - Our service handler, `handleError`, logs the response to the console, - transforms the error into a user-friendly message, and returns the message in a new, failed observable via `Observable.throw`. +block error-handling + :marked + The eagle-eyed reader may have spotted our use of the `catch` operator in conjunction with a `handleError` method. + We haven't discussed so far how that actually works. -+makeExample('server-communication/ts/app/toh/hero.service.ts', 'error-handling', 'app/toh/hero.service.ts')(format=".") + We use the Observable `catch` operator on the service level. + It takes an error handling function with an error object as the argument. + Our service handler, `handleError`, logs the response to the console, + transforms the error into a user-friendly message, and returns the message in a new, failed observable via `Observable.throw`. - - -.l-main-section -:marked - ## Subscribe in the *HeroListComponent* - Back in the `HeroListComponent`, where we called `heroService.get`, - we supply the `subscribe` function with a second function to handle the error message. - It sets an `errorMessage` variable which we've bound conditionally in the template. ++makeExample('server-communication/ts/app/toh/hero.service.ts', 'error-handling', 'app/toh/hero.service.ts (excerpt)')(format=".") + +a#subscribe +a#hero-list-component +h4 #[b HeroListComponent] error handling +block hlc-error-handling + :marked + Back in the `HeroListComponent`, where we called `#{_priv}heroService.getHeroes()`, + we supply the `subscribe` function with a second function to handle the error message. + It sets an `errorMessage` variable which we've bound conditionally in the template. +makeExample('server-communication/ts/app/toh/hero-list.component.ts', 'getHeroes', 'app/toh/hero-list.component.ts (getHeroes)')(format=".") @@ -307,13 +309,14 @@ a(id="error-handling") :marked ## Send data to the server - So far we've seen how to retrieve data from a remote location using Angular's built-in `Http` service. + So far we've seen how to retrieve data from a remote location using an HTTP service. Let's add the ability to create new heroes and save them in the backend. - We'll create an easy method for the `HeroListComponent` to call, an `addHero` method that takes - just the name of a new hero and returns an observable holding the newly-saved hero: -code-example(format="." language="javascript"). - addHero (name: string) : Observable<Hero> + We'll create an easy method for the `HeroListComponent` to call, an `addHero()` method that takes + just the name of a new hero: + ++makeExample('server-communication/ts/app/toh/hero.service.ts', 'addhero-sig')(format=".") + :marked To implement it, we need to know some details about the server's api for creating heroes. @@ -331,90 +334,100 @@ code-example(format="." language="javascript"). of the new hero including its generated id. The hero arrives tucked inside a response object with its own `data` property. - Now that we know how the API works, we implement `addHero`like this: -+makeExample('server-communication/ts/app/toh/hero.service.ts', 'import-request-options', 'app/toh/hero.service.ts (additional imports)')(format=".") + Now that we know how the API works, we implement `addHero()`like this: + ++ifDocsFor('ts') + +makeExample('server-communication/ts/app/toh/hero.service.ts', 'import-request-options', 'app/toh/hero.service.ts (additional imports)')(format=".") +makeExample('server-communication/ts/app/toh/hero.service.ts', 'addhero', 'app/toh/hero.service.ts (addHero)')(format=".") -:marked - The second *body* parameter of the `post` method requires a JSON ***string*** - so we have to `JSON.stringify` the hero content before sending. -.l-sub-section - :marked - We may be able to skip the `stringify` step in the near future. - - + :marked ### Headers - The server requires a `Content-Type` header for the body of the POST. - [Headers](../api/http/Headers-class.html) are one of the [RequestOptions](../api/http/RequestOptions-class.html). - Compose the options object and pass it in as the *third* parameter of the `post` method. -+makeExample('server-communication/ts/app/toh/hero.service.ts', 'headers', 'app/toh/hero.service.ts (headers)')(format=".") + + The `Content-Type` header allows us to inform the server that the body will represent JSON. + ++ifDocsFor('ts') + :marked + [Headers](../api/http/Headers-class.html) are one of the [RequestOptions](../api/http/RequestOptions-class.html). + Compose the options object and pass it in as the *third* parameter of the `post` method, as shown above. + +:marked + ### Body + + Despite the content type being specified as JSON, the POST body must actually be a *string*. + Hence, we explicitly encode the JSON hero content before passing it in as the body argument. + ++ifDocsFor('ts') + .l-sub-section + :marked + We may be able to skip the `JSON.stringify` step in the near future. :marked ### JSON results - As with `getHeroes`, we [extract the data](#extract-data) from the response with `json()` and unwrap the hero via the `data` property. -.alert.is-important - :marked - Know the shape of the data returned by the server. - *This* web api returns the new hero wrapped in an object with a `data` property. - A different api might just return the hero in which case we'd omit the `data` de-reference. -:marked - Back in the `HeroListComponent`, we see that *its* `addHero` method subscribes to the observable returned by the *service's* `addHero` method. - When the data arrive it pushes the new hero object into its `heroes` array for presentation to the user. -+makeExample('server-communication/ts/app/toh/hero-list.component.ts', 'addHero', 'app/toh/hero-list.component.ts (addHero)')(format=".") - -:marked - ## Fall back to Promises - - Although the Angular `http` client API returns an `Observable` we can turn it into a - [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) if we prefer. - It's easy to do and a promise-based version looks much like the observable-based version in simple cases. -.l-sub-section - :marked - While promises may be more familiar, observables have many advantages. - Don't rush to promises until you give observables a chance. -:marked - Let's rewrite the `HeroService` using promises , highlighting just the parts that are different. -+makeTabs( - 'server-communication/ts/app/toh/hero.service.1.ts,server-communication/ts/app/toh/hero.service.ts', - 'methods, methods', - 'app/toh/hero.service.ts (promise-based), app/toh/hero.service.ts (observable-based)') -:marked - Converting from an observable to a promise is as simple as calling `toPromise(success, fail)`. - - We move the observable's `map` callback to the first *success* parameter and its `catch` callback to the second *fail* parameter - and we're done! - Or we can follow the promise `then.catch` pattern as we do in the second `addHero` example. - - Our `errorHandler` forwards an error message as a failed promise instead of a failed Observable. - - The diagnostic *log to console* is just one more `then` in the promise chain. - - We have to adjust the calling component to expect a `Promise` instead of an `Observable`. - -+makeTabs( - 'server-communication/ts/app/toh/hero-list.component.1.ts, server-communication/ts/app/toh/hero-list.component.ts', - 'methods, methods', - 'app/toh/hero-list.component.ts (promise-based), app/toh/hero-list.component.ts (observable-based)') -:marked - The only obvious difference is that we call `then` on the returned promise instead of `subscribe`. - We give both methods the same functional arguments. -.l-sub-section - :marked - The less obvious but critical difference is that these two methods return very different results! - - The promise-based `then` returns another promise. We can keep chaining more `then` and `catch` calls, getting a new promise each time. - - The `subscribe` method returns a `Subscription`. A `Subscription` is not another `Observable`. - It's the end of the line for observables. We can't call `map` on it or call `subscribe` again. - The `Subscription` object has a different purpose, signified by its primary method, `unsubscribe`. - - Learn more about observables to understand the implications and consequences of subscriptions. - -:marked - ## Get data with `JSONP` + As with `getHeroes()`, we [extract the data](#extract-data) from the response using the + `#{_priv}extractData()` helper. - We just learned how to make `XMLHttpRequests` using Angulars built-in `Http` service. +block hero-list-comp-add-hero + :marked + Back in the `HeroListComponent`, we see that *its* `addHero()` method subscribes to the observable returned by the *service's* `addHero()` method. + When the data arrive it pushes the new hero object into its `heroes` array for presentation to the user. + +makeExample('server-communication/ts/app/toh/hero-list.component.ts', 'addHero', 'app/toh/hero-list.component.ts (addHero)')(format=".") + +block promises + a#promises + :marked + ## Fall back to Promises + + Although the Angular `http` client API returns an `Observable` we can turn it into a + [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) if we prefer. + It's easy to do and a promise-based version looks much like the observable-based version in simple cases. + .l-sub-section + :marked + While promises may be more familiar, observables have many advantages. + Don't rush to promises until you give observables a chance. + :marked + Let's rewrite the `HeroService` using promises , highlighting just the parts that are different. + +makeTabs( + 'server-communication/ts/app/toh/hero.service.1.ts,server-communication/ts/app/toh/hero.service.ts', + 'methods, methods', + 'app/toh/hero.service.ts (promise-based), app/toh/hero.service.ts (observable-based)') + :marked + Converting from an observable to a promise is as simple as calling `toPromise(success, fail)`. + + We move the observable's `map` callback to the first *success* parameter and its `catch` callback to the second *fail* parameter + and we're done! + Or we can follow the promise `then.catch` pattern as we do in the second `addHero` example. + + Our `errorHandler` forwards an error message as a failed promise instead of a failed Observable. + + The diagnostic *log to console* is just one more `then` in the promise chain. + + We have to adjust the calling component to expect a `Promise` instead of an `Observable`. + + +makeTabs( + 'server-communication/ts/app/toh/hero-list.component.1.ts, server-communication/ts/app/toh/hero-list.component.ts', + 'methods, methods', + 'app/toh/hero-list.component.ts (promise-based), app/toh/hero-list.component.ts (observable-based)') + :marked + The only obvious difference is that we call `then` on the returned promise instead of `subscribe`. + We give both methods the same functional arguments. + .l-sub-section + :marked + The less obvious but critical difference is that these two methods return very different results! + + The promise-based `then` returns another promise. We can keep chaining more `then` and `catch` calls, getting a new promise each time. + + The `subscribe` method returns a `Subscription`. A `Subscription` is not another `Observable`. + It's the end of the line for observables. We can't call `map` on it or call `subscribe` again. + The `Subscription` object has a different purpose, signified by its primary method, `unsubscribe`. + + Learn more about observables to understand the implications and consequences of subscriptions. + +a#cross-origin-requests +:marked + ## Cross-origin requests: Wikipedia example + + We just learned how to make `XMLHttpRequests` using Angular's built-in `Http` service. This is the most common approach for server communication. It doesn't work in all scenarios. @@ -437,152 +450,159 @@ code-example(format="." language="javascript"). :marked ### Search wikipedia - Wikipedia offers a `JSONP` search api. Let's build a simple search that shows suggestions from wikipedia as we type in a text box. + Let's build a simple search that shows suggestions from wikipedia as we type in a text box. + figure.image-display img(src='/resources/images/devguide/server-communication/wiki-1.gif' alt="Wikipedia search app (v.1)" width="250") -:marked - The Angular `Jsonp` service both extends the `Http` service for JSONP and restricts us to `GET` requests. - All other HTTP methods throw an error because JSONP is a read-only facility. - As always, we wrap our interaction with an Angular data access client service inside a dedicated service, here called `WikipediaService`. - -+makeExample('server-communication/ts/app/wiki/wikipedia.service.ts',null,'app/wiki/wikipedia.service.ts') -:marked - The constructor expects Angular to inject its `jsonp` service. - We register that service with `JSONP_PROVIDERS` in the [component below](#wikicomponent) that calls our `WikipediaService`. - - - -:marked - ### Search parameters - The [Wikipedia 'opensearch' API](https://www.mediawiki.org/wiki/API:Opensearch) - expects four parameters (key/value pairs) to arrive in the request URL's query string. - The keys are `search`, `action`, `format`, and `callback`. - The value of the `search` key is the user-supplied search term to find in Wikipedia. - The other three are the fixed values "opensearch", "json", and "JSONP_CALLBACK" respectively. -.l-sub-section +block wikipedia-jsonp+ :marked - The `JSONP` technique requires that we pass a callback function name to the server in the query string: `callback=JSONP_CALLBACK`. - The server uses that name to build a JavaScript wrapper function in its response which Angular ultimately calls to extract the data. - All of this happens under the hood. -:marked - If we're looking for articles with the word "Angular", we could construct the query string by hand and call `jsonp` like this: -+makeExample('server-communication/ts/app/wiki/wikipedia.service.1.ts','query-string')(format='.') -:marked - In more parameterized examples we might prefer to build the query string with the Angular `URLSearchParams` helper as shown here: -+makeExample('server-communication/ts/app/wiki/wikipedia.service.ts','search-parameters','app/wiki/wikipedia.service.ts (search parameters)')(format=".") -:marked - This time we call `jsonp` with *two* arguments: the `wikiUrl` and an options object whose `search` property is the `params` object. -+makeExample('server-communication/ts/app/wiki/wikipedia.service.ts','call-jsonp','app/wiki/wikipedia.service.ts (call jsonp)')(format=".") -:marked - `Jsonp` flattens the `params` object into the same query string we saw earlier before putting the request on the wire. - - -:marked - ### The WikiComponent - - Now that we have a service that can query the Wikipedia API, - we turn to the component that takes user input and displays search results. - -+makeExample('server-communication/ts/app/wiki/wiki.component.ts', null, 'app/wiki/wiki.component.ts') -:marked - The `providers` array in the component metadata specifies the Angular `JSONP_PROVIDERS` collection that supports the `Jsonp` service. - We register that collection at the component level to make `Jsonp` injectable in the `WikipediaService`. + Wikipedia offers both `CORS` and `JSONP` search APIs, let's use the latter for this example. + The Angular `Jsonp` service both extends the `Http` service for JSONP and restricts us to `GET` requests. + All other HTTP methods throw an error because JSONP is a read-only facility. - The component presents an `` element *search box* to gather search terms from the user. - and calls a `search(term)` method after each `keyup` event. - - The `search(term)` method delegates to our `WikipediaService` which returns an observable array of string results (`Observable + :marked + ### Search parameters + The [Wikipedia 'opensearch' API](https://www.mediawiki.org/wiki/API:Opensearch) + expects four parameters (key/value pairs) to arrive in the request URL's query string. + The keys are `search`, `action`, `format`, and `callback`. + The value of the `search` key is the user-supplied search term to find in Wikipedia. + The other three are the fixed values "opensearch", "json", and "JSONP_CALLBACK" respectively. + .l-sub-section + :marked + The `JSONP` technique requires that we pass a callback function name to the server in the query string: `callback=JSONP_CALLBACK`. + The server uses that name to build a JavaScript wrapper function in its response which Angular ultimately calls to extract the data. + All of this happens under the hood. + :marked + If we're looking for articles with the word "Angular", we could construct the query string by hand and call `jsonp` like this: + +makeExample('server-communication/ts/app/wiki/wikipedia.service.1.ts','query-string')(format='.') + :marked + In more parameterized examples we might prefer to build the query string with the Angular `URLSearchParams` helper as shown here: + +makeExample('server-communication/ts/app/wiki/wikipedia.service.ts','search-parameters','app/wiki/wikipedia.service.ts (search parameters)')(format=".") + :marked + This time we call `jsonp` with *two* arguments: the `wikiUrl` and an options object whose `search` property is the `params` object. + +makeExample('server-communication/ts/app/wiki/wikipedia.service.ts','call-jsonp','app/wiki/wikipedia.service.ts (call jsonp)')(format=".") + :marked + `Jsonp` flattens the `params` object into the same query string we saw earlier before putting the request on the wire. - Our wikipedia search makes too many calls to the server. - It is inefficient and potentially expensive on mobile devices with limited data plans. - - ### 1. Wait for the user to stop typing - At the moment we call the server after every key stroke. - The app should only make requests when the user *stops typing* . - Here's how it *should* work — and *will* work — when we're done refactoring: -figure.image-display - img(src='/resources/images/devguide/server-communication/wiki-2.gif' alt="Wikipedia search app (v.2)" width="250") -:marked - ### 2. Search when the search term changes - - Suppose the user enters the word *angular* in the search box and pauses for a while. - The application issues a search request for *Angular*. - - Then the user backspaces over the last three letters, *lar*, and immediately re-types *lar* before pausing once more. - The search term is still "angular". The app shouldn't make another request. - - ### 3. Cope with out-of-order responses + + :marked + ### The WikiComponent - The user enters *angular*, pauses, clears the search box, and enters *http*. - The application issues two search requests, one for *angular* and one for *http*. - - Which response will arrive first? We can't be sure. - A load balancer could dispatch the requests to two different servers with different response times. - The results from the first *angular* request might arrive after the later *http* results. - The user will be confused if we display the *angular* results to the *http* query. - - When there are multiple requests in-flight, the app should present the responses - in the original request order. That won't happen if *angular* results arrive last. + Now that we have a service that can query the Wikipedia API, + we turn to the component that takes user input and displays search results. - - ## More fun with Observables - We can address these problems and improve our app with the help of some nifty observable operators. - - We could make our changes to the `WikipediaService`. - But we sense that our concerns are driven by the user experience so we update the component class instead. + +makeExample('server-communication/ts/app/wiki/wiki.component.ts', null, 'app/wiki/wiki.component.ts') + :marked + The `providers` array in the component metadata specifies the Angular `JSONP_PROVIDERS` collection that supports the `Jsonp` service. + We register that collection at the component level to make `Jsonp` injectable in the `WikipediaService`. -+makeExample('server-communication/ts/app/wiki/wiki-smart.component.ts', null, 'app/wiki/wiki-smart.component.ts') -:marked - We made no changes to the template or metadata, confining them all to the component class. - Let's review those changes. - - ### Create a stream of search terms - - We're binding to the search box `keyup` event and calling the component's `search` method after each keystroke. - - We turn these events into an observable stream of search terms using a `Subject` - which we import from the RxJS observable library: -+makeExample('server-communication/ts/app/wiki/wiki-smart.component.ts', 'import-subject') -:marked - Each search term is a string, so we create a new `Subject` of type `string` called `_searchTermStream`. - After every keystroke, the `search` method adds the search box value to that stream - via the subject's `next` method. -+makeExample('server-communication/ts/app/wiki/wiki-smart.component.ts', 'subject')(format='.') -:marked - ### Listen for search terms - - Earlier, we passed each search term directly to the service and bound the template to the service results. - Now we listen to the *stream of terms*, manipulating the stream before it reaches the `WikipediaService`. -+makeExample('server-communication/ts/app/wiki/wiki-smart.component.ts', 'observable-operators')(format='.') -:marked - We wait for the user to stop typing for at least 300 milliseconds - ([debounce](https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/debounce.md)). - Only changed search values make it through to the service - ([distinctUntilChanged](https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/distinctuntilchanged.md)). + The component presents an `` element *search box* to gather search terms from the user. + and calls a `search(term)` method after each `keyup` event. - The `WikipediaService` returns a separate observable of string arrays (`Observable`) for each request. - We could have multiple requests *in flight*, all awaiting the server's reply, - which means multiple *observables-of-strings* could arrive at any moment in any order. - - The [switchMap](https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/flatmaplatest.md) - (formerly known as `flatMapLatest`) returns a new observable that combines these `WikipediaService` observables, - re-arranges them in their original request order, - and delivers to subscribers only the most recent search results. + The `search(term)` method delegates to our `WikipediaService` which returns an observable array of string results (`Observable + Our wikipedia search makes too many calls to the server. + It is inefficient and potentially expensive on mobile devices with limited data plans. + + ### 1. Wait for the user to stop typing + At the moment we call the server after every key stroke. + The app should only make requests when the user *stops typing* . + Here's how it *should* work — and *will* work — when we're done refactoring: + figure.image-display + img(src='/resources/images/devguide/server-communication/wiki-2.gif' alt="Wikipedia search app (v.2)" width="250") + :marked + ### 2. Search when the search term changes + + Suppose the user enters the word *angular* in the search box and pauses for a while. + The application issues a search request for *Angular*. + + Then the user backspaces over the last three letters, *lar*, and immediately re-types *lar* before pausing once more. + The search term is still "angular". The app shouldn't make another request. + + ### 3. Cope with out-of-order responses + + The user enters *angular*, pauses, clears the search box, and enters *http*. + The application issues two search requests, one for *angular* and one for *http*. + + Which response will arrive first? We can't be sure. + A load balancer could dispatch the requests to two different servers with different response times. + The results from the first *angular* request might arrive after the later *http* results. + The user will be confused if we display the *angular* results to the *http* query. + + When there are multiple requests in-flight, the app should present the responses + in the original request order. That won't happen if *angular* results arrive last. + + + ## More fun with Observables + We can address these problems and improve our app with the help of some nifty observable operators. + + We could make our changes to the `WikipediaService`. + But we sense that our concerns are driven by the user experience so we update the component class instead. + + +makeExample('server-communication/ts/app/wiki/wiki-smart.component.ts', null, 'app/wiki/wiki-smart.component.ts') + :marked + We made no changes to the template or metadata, confining them all to the component class. + Let's review those changes. + + ### Create a stream of search terms + + We're binding to the search box `keyup` event and calling the component's `search` method after each keystroke. + + We turn these events into an observable stream of search terms using a `Subject` + which we import from the RxJS observable library: + +makeExample('server-communication/ts/app/wiki/wiki-smart.component.ts', 'import-subject') + :marked + Each search term is a string, so we create a new `Subject` of type `string` called `searchTermStream`. + After every keystroke, the `search` method adds the search box value to that stream + via the subject's `next` method. + +makeExample('server-communication/ts/app/wiki/wiki-smart.component.ts', 'subject')(format='.') + :marked + ### Listen for search terms + + Earlier, we passed each search term directly to the service and bound the template to the service results. + Now we listen to the *stream of terms*, manipulating the stream before it reaches the `WikipediaService`. + +makeExample('server-communication/ts/app/wiki/wiki-smart.component.ts', 'observable-operators')(format='.') + :marked + We wait for the user to stop typing for at least 300 milliseconds + ([debounceTime](https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/debounce.md)). + Only changed search values make it through to the service + ([distinctUntilChanged](https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/distinctuntilchanged.md)). + + The `WikipediaService` returns a separate observable of string arrays (`Observable`) for each request. + We could have multiple requests *in flight*, all awaiting the server's reply, + which means multiple *observables-of-strings* could arrive at any moment in any order. + + The [switchMap](https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/flatmaplatest.md) + (formerly known as `flatMapLatest`) returns a new observable that combines these `WikipediaService` observables, + re-arranges them in their original request order, + and delivers to subscribers only the most recent search results. + + The displayed list of search results stays in sync with the user's sequence of search terms. + .l-sub-section + :marked + We added the `debounceTime`, `distinctUntilChanged`, and `switchMap` operators to the RxJS `Observable` class + in `add-rxjs-operators` as [described above](#rxjs) + +a#in-mem-web-api .l-main-section :marked ## Appendix: Tour of Heroes in-memory server @@ -597,46 +617,46 @@ figure.image-display :marked We'd set the endpoint to the JSON file like this: +makeExample('server-communication/ts/app/toh/hero.service.ts', 'endpoint-json')(format=".") + +- var _a_ca_class_with = _docsFor === 'ts' ? 'a custom application class with' : '' :marked The *get heroes* scenario would work. - But we want to *save* data too. We can't save changes to a JSON file. We need a web api server. - + But we want to *save* data too. We can't save changes to a JSON file. We need a web API server. We didn't want the hassle of setting up and maintaining a real server for this chapter. - So we turned to an *in-memory web api simulator* instead. - You too can use it in your own development while waiting for a real server to arrive. - - First, install it with `npm`: -code-example(language="bash"). - npm install a2-in-memory-web-api --save + So we turned to an *in-memory web API simulator* instead. + +.l-sub-section + :marked + The in-memory web api is not part of the Angular core. + It's an optional service in its own `angular2-in-memory-web-api` library + that we installed with npm (see `package.json`) and + registered for module loading by SystemJS (see `systemjs.config.js`) + :marked - Then load the script in the `index.html` below angular: -+makeExample('server-communication/ts/index.html', 'in-mem-web-api', 'index.html')(format=".") -:marked - The *in-memory web api* gets its data from a class with a `createDb()` method that returns - a "database" object whose keys are collection names ("heroes") - and whose values are arrays of objects in those collections. + The in-memory web API gets its data from #{_a_ca_class_with} a `createDb()` + method that returns a map whose keys are collection names and whose values + are #{_array}s of objects in those collections. Here's the class we created for this sample by copy-and-pasting the JSON data: +makeExample('server-communication/ts/app/hero-data.ts', null, 'app/hero-data.ts')(format=".") :marked - We update the `HeroService` endpoint to the location of the web api data. + Ensure that the `HeroService` endpoint refers to the web API: +makeExample('server-communication/ts/app/toh/hero.service.ts', 'endpoint')(format=".") :marked - Finally, we tell Angular itself to direct its http requests to the *in-memory web api* rather - than externally to a remote server. - - This redirection is easy because Angular's `http` delegates the client/server communication tasks - to a helper service called the `XHRBackend`. - - To enable our server simulation, we replace the default `XHRBackend` service with - the *in-memory web api service* using standard Angular provider registration - in the `TohComponent`. We initialize the *in-memory web api* with mock hero data at the same time. - - Here are the pertinent details, excerpted from `TohComponent`, starting with the imports: -+makeExample('server-communication/ts/app/toh/toh.component.ts', 'in-mem-web-api-imports', 'toh.component.ts (web api imports)')(format=".") -:marked - Then we add the following two provider definitions to the `providers` array in component metadata: -+makeExample('server-communication/ts/app/toh/toh.component.ts', 'in-mem-web-api-providers', 'toh.component.ts (web api providers)')(format=".") -:marked - See the full source code in the [live example](/resources/live-examples/server-communication/ts/plnkr.html). - + Finally, we need to redirect client HTTP requests to the in-memory web API. +block redirect-to-web-api + :marked + This redirection is easy to configure because Angular's `http` service delegates the client/server communication tasks + to a helper service called the `XHRBackend`. + + To enable our server simulation, we replace the default `XHRBackend` service with + the in-memory web API service using standard Angular provider registration + in `TohComponent`. We initialize the in-memory web API with mock hero data at the same time. + + Here are the pertinent details, excerpt from `TohComponent`, starting with the imports: + +makeExample('server-communication/ts/app/toh/toh.component.ts', 'in-mem-web-api-imports', 'toh.component.ts (web API imports)')(format=".") + :marked + Then we add the following two provider definitions to the `providers` array in component metadata: + +makeExample('server-communication/ts/app/toh/toh.component.ts', 'in-mem-web-api-providers', 'toh.component.ts (web API providers)')(format=".") + +p See the full source code in the #[+liveExampleLink2('live example', 'server-communication')]. diff --git a/public/docs/ts/latest/guide/structural-directives.jade b/public/docs/ts/latest/guide/structural-directives.jade index ab53753ea8..c69cc870c0 100644 --- a/public/docs/ts/latest/guide/structural-directives.jade +++ b/public/docs/ts/latest/guide/structural-directives.jade @@ -1,4 +1,5 @@ -include ../_util-fns +block includes + include ../_util-fns :marked One of the defining features of a single page application is its manipulation @@ -9,12 +10,12 @@ include ../_util-fns In this chapter we will - [learn what structural directives are](#definition) - - [study *ngIf*](#ng-if) + - [study *ngIf*](#ngIf) - [discover the <template> element](#template) - [understand the asterisk (\*) in **ngFor*](#asterisk) - [write our own structural directive](#unless) - - [Live example](/resources/live-examples/structural-directives/ts/plnkr.html) +p + | Try the #[+liveExampleLink2('live example', 'structural-directives')]. .l-main-section @@ -42,7 +43,7 @@ include ../_util-fns +makeExample('structural-directives/ts/app/structural-directives.component.html', 'structural-directives')(format=".") - + .l-main-section :marked ## NgIf Case Study @@ -122,7 +123,7 @@ figure.image-display `structural-directives/ts/app/structural-directives.component.html, structural-directives/ts/app/heavy-loader.component.ts`, 'message-log,', - 'template excerpt, heavy-loader.component.ts') + 'template (excerpt), heavy-loader.component.ts') :marked We also log when a component is created or destroyed @@ -163,7 +164,7 @@ figure.image-display We can confirm these effects by wrapping the middle "hip" of the phrase "Hip! Hip! Hooray!" within a `