Compare commits
171 Commits
labs/rxjs-
...
6.0.0-rc.1
Author | SHA1 | Date | |
---|---|---|---|
a30728ca5a | |||
aebf04e32c | |||
15278784fc | |||
22cb2c9441 | |||
88a93e730e | |||
dc95e7bc33 | |||
7fdc24db72 | |||
3603a10ea2 | |||
6f7d14064c | |||
a5f0939eae | |||
193737a1ea | |||
be10bf538b | |||
439030fb57 | |||
481b22ecb0 | |||
45e090b614 | |||
0d9140cdce | |||
9fb08e2377 | |||
de0b13d41d | |||
07d33d4e5a | |||
9f7bd8f618 | |||
28058b784b | |||
7de13b60d6 | |||
00497437a6 | |||
4e004f3783 | |||
d9dc46e651 | |||
9e9b8dd494 | |||
12665a749c | |||
e2e80ec61c | |||
5a86f7144f | |||
bd024c02e2 | |||
884bf0ef09 | |||
0b348c8ffe | |||
e1ea7ed019 | |||
ed53c5ccdd | |||
d28ce50067 | |||
ab348ee2be | |||
0ebdb3d12f | |||
de90314304 | |||
f739f756ce | |||
910a16a1ff | |||
2aabbc51fa | |||
2388f24256 | |||
27e14b2fb3 | |||
7a406a32fa | |||
bf6a416bce | |||
7b7757dd3d | |||
4bd3a65764 | |||
6f0191744c | |||
4f0cae0676 | |||
65f296a676 | |||
b9cbe83104 | |||
60d99839de | |||
7966744a44 | |||
d9a0a8ff3e | |||
bcaa07b0ac | |||
d98e9e7c7f | |||
16f021c319 | |||
3a30f5d937 | |||
0f88fc73db | |||
01d2dd2a3a | |||
da76db9601 | |||
91503e538e | |||
53227abe7b | |||
768100516f | |||
328511be8e | |||
56e545735c | |||
07e9969cb7 | |||
5ab9d4d437 | |||
129bb1800b | |||
49396ca2ae | |||
34981063ec | |||
8ca26a9ebb | |||
e44f69c387 | |||
99711b12f9 | |||
204ba9d413 | |||
e5e1b0da33 | |||
d77bb460b0 | |||
bb58664b13 | |||
bfe35dac85 | |||
c84817970e | |||
b524e4b142 | |||
f88fba020b | |||
32105c8012 | |||
4a075e885f | |||
838a610197 | |||
f461f43d72 | |||
64efcf103c | |||
b12ea30a66 | |||
8c2a57878b | |||
4f2c51fe56 | |||
061564394f | |||
7cd8e8dbd1 | |||
73261a8b70 | |||
f285cff10b | |||
8768665587 | |||
623d769858 | |||
17fb9832f4 | |||
3cc5c2e4d0 | |||
fad86a67ca | |||
5f1be9b89b | |||
e6c731f791 | |||
7d095b96cd | |||
67f570caeb | |||
689f351092 | |||
4648597d14 | |||
b43f8bc7d3 | |||
c445314239 | |||
4a7be487da | |||
5caad5fe93 | |||
e5fcf650f8 | |||
2b3de6390f | |||
5c387a7f3c | |||
fc50c77bd3 | |||
bfe077ad64 | |||
1a0cb21538 | |||
0bede54b2d | |||
243c86cd04 | |||
9054e357d6 | |||
0b68a35ff2 | |||
e27cfd6236 | |||
1612985e48 | |||
4f21d373b7 | |||
ce63dc6f95 | |||
d54615d555 | |||
912fe08756 | |||
99408d0445 | |||
f258ec67bf | |||
5d82d8da6d | |||
6ef9f2278f | |||
688096b7a3 | |||
2e450f6fda | |||
fe21437232 | |||
cf3ff7d219 | |||
d72f44556d | |||
0b45dfac29 | |||
167fdf745c | |||
39a12d2c3d | |||
87f60bccfd | |||
46efd4b938 | |||
19368085aa | |||
d2be675acc | |||
44f637a88b | |||
863aff1a77 | |||
400460cc93 | |||
4d506acba0 | |||
7c9b411777 | |||
22b96b9690 | |||
cedc04c320 | |||
bafdad9083 | |||
9220521149 | |||
b149424b11 | |||
269c3a1908 | |||
f9247e4b2e | |||
44de10e2db | |||
0ebd577db4 | |||
4e6ac185e5 | |||
e55bf8fa79 | |||
3b167be069 | |||
02e6ac2117 | |||
04ca77e38e | |||
a011654c71 | |||
88b3198c80 | |||
6e5e819e80 | |||
19e6b8dad5 | |||
f256c02b5e | |||
dd20898bd5 | |||
d509bd6849 | |||
cd2ebd22fd | |||
112431db69 | |||
a0a01f1e1e | |||
ae19d071bb |
@ -74,10 +74,14 @@ jobs:
|
||||
- run: ls /home/circleci/bazel_repository_cache || true
|
||||
- run: bazel info release
|
||||
- run: bazel run @yarn//:yarn
|
||||
# Use bazel query so that we explicitly ask for all buildable targets to be built as well
|
||||
# This avoids waiting for a build command to finish before running the first test
|
||||
# We could use bazel query so that we explicitly ask for all buildable targets to be built as well
|
||||
# This would avoid waiting for a build command to finish before running the first test
|
||||
# See https://github.com/bazelbuild/bazel/issues/4257
|
||||
- run: bazel query --output=label '//modules/... union //packages/... union //tools/...' | xargs bazel test
|
||||
# - run: bazel query --output=label //... | xargs bazel test
|
||||
# However it makes it more confusing for Angular developers who are still novice at Bazel
|
||||
# So keep it simple for now
|
||||
- run: bazel build //...
|
||||
- run: bazel test //...
|
||||
|
||||
# CircleCI will allow us to go back and view/download these artifacts from past builds.
|
||||
# Also we can use a service like https://buildsize.org/ to automatically track binary size of these artifacts.
|
||||
|
6
.github/angular-robot.yml
vendored
6
.github/angular-robot.yml
vendored
@ -19,10 +19,12 @@ merge:
|
||||
disabled: false
|
||||
# the name of the status
|
||||
context: "google3"
|
||||
# text to show when the status is pending
|
||||
pendingDesc: "Googler: test this change in google3 http://go/angular-g3sync"
|
||||
# text to show when the status is pending, {{PRNumber}} will be replaced by the PR number
|
||||
pendingDesc: "Googler: run g3sync presubmit {{PRNumber}}"
|
||||
# text to show when the status is success
|
||||
successDesc: "Does not affect google3"
|
||||
# link to use for the details
|
||||
url: "http://go/angular-g3sync"
|
||||
# list of patterns to check for the files changed by the PR
|
||||
# this list must be manually kept in sync with google3/third_party/javascript/angular2/copy.bara.sky
|
||||
include:
|
||||
|
@ -7,6 +7,7 @@
|
||||
#
|
||||
# alexeagle - Alex Eagle
|
||||
# alxhub - Alex Rickabaugh
|
||||
# andrewseguin - Andrew Seguin
|
||||
# brocco - Mike Brocchi
|
||||
# chuckjaz - Chuck Jazdzewski
|
||||
# filipesilva - Filipe Silva
|
||||
@ -302,6 +303,16 @@ groups:
|
||||
- IgorMinar #fallback
|
||||
- mhevery #fallback
|
||||
|
||||
elements:
|
||||
conditions:
|
||||
files:
|
||||
- "packages/elements/*"
|
||||
users:
|
||||
- andrewseguin #primary
|
||||
- gkalpak
|
||||
- IgorMinar #fallback
|
||||
- mhevery #fallback
|
||||
|
||||
benchpress:
|
||||
conditions:
|
||||
files:
|
||||
|
44
BUILD.bazel
44
BUILD.bazel
@ -1,5 +1,7 @@
|
||||
package(default_visibility = ["//visibility:public"])
|
||||
|
||||
load("@build_bazel_rules_nodejs//:defs.bzl", "node_modules_filegroup")
|
||||
|
||||
exports_files([
|
||||
"tsconfig.json",
|
||||
"LICENSE",
|
||||
@ -12,40 +14,24 @@ alias(
|
||||
actual = "@yarn//:yarn",
|
||||
)
|
||||
|
||||
# This rule belongs in node_modules/BUILD
|
||||
# It's here as a workaround for
|
||||
# https://github.com/bazelbuild/bazel/issues/374#issuecomment-296217940
|
||||
filegroup(
|
||||
node_modules_filegroup(
|
||||
name = "node_modules",
|
||||
# Performance workaround: list individual files
|
||||
# Reduces the number of files as inputs to nodejs_binary:
|
||||
# bazel query "deps(:node_modules)" | wc -l
|
||||
# This won't scale in the general case.
|
||||
# TODO(alexeagle): figure out what to do
|
||||
srcs = glob(["/".join([
|
||||
"node_modules",
|
||||
pkg,
|
||||
"**",
|
||||
ext,
|
||||
]) for pkg in [
|
||||
"jasmine",
|
||||
"typescript",
|
||||
"zone.js",
|
||||
"tsutils",
|
||||
"@types",
|
||||
"tsickle",
|
||||
"hammerjs",
|
||||
"protobufjs",
|
||||
packages = [
|
||||
"bytebuffer",
|
||||
"hammerjs",
|
||||
"jasmine",
|
||||
"minimist",
|
||||
"protobufjs",
|
||||
"reflect-metadata",
|
||||
"source-map-support",
|
||||
"minimist",
|
||||
"tsickle",
|
||||
"tslib",
|
||||
] for ext in [
|
||||
"*.js",
|
||||
"*.json",
|
||||
"*.d.ts",
|
||||
]]),
|
||||
"tsutils",
|
||||
"typescript",
|
||||
"zone.js",
|
||||
"@types",
|
||||
"@webcomponents/custom-elements",
|
||||
],
|
||||
)
|
||||
|
||||
filegroup(
|
||||
|
178
CHANGELOG.md
178
CHANGELOG.md
@ -1,3 +1,167 @@
|
||||
<a name="6.0.0-rc.1"></a>
|
||||
# [6.0.0-rc.1](https://github.com/angular/angular/compare/6.0.0-rc.0...6.0.0-rc.1) (2018-03-30)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **animations:** avoid animation insertions during router back/refresh ([#21977](https://github.com/angular/angular/issues/21977)) ([f88fba0](https://github.com/angular/angular/commit/f88fba0)), closes [#19712](https://github.com/angular/angular/issues/19712)
|
||||
* **animations:** treat numeric state name values as strings ([#22923](https://github.com/angular/angular/issues/22923)) ([e5e1b0d](https://github.com/angular/angular/commit/e5e1b0d))
|
||||
* **bazel:** complete the rollup globals list for all angular entrypoints ([#23080](https://github.com/angular/angular/issues/23080)) ([439030f](https://github.com/angular/angular/commit/439030f))
|
||||
* **bazel:** don't inline tslib into fesms ([#23044](https://github.com/angular/angular/issues/23044)) ([0049743](https://github.com/angular/angular/commit/0049743))
|
||||
* **bazel:** don't try to do flatmoduleindex under Blaze ([#23083](https://github.com/angular/angular/issues/23083)) ([be10bf5](https://github.com/angular/angular/commit/be10bf5))
|
||||
* **bazel:** downlevel decorators in fesm5 files ([#23078](https://github.com/angular/angular/issues/23078)) ([481b22e](https://github.com/angular/angular/commit/481b22e))
|
||||
* **bazel:** ng_package packages attr not forwarded to npm_package ([#22967](https://github.com/angular/angular/issues/22967)) ([2aabbc5](https://github.com/angular/angular/commit/2aabbc5))
|
||||
* **bazel:** ng_package should include private exports in fesms ([#23054](https://github.com/angular/angular/issues/23054)) ([0d9140c](https://github.com/angular/angular/commit/0d9140c))
|
||||
* **bazel:** pass --global option to rollup ([#23073](https://github.com/angular/angular/issues/23073)) ([45e090b](https://github.com/angular/angular/commit/45e090b))
|
||||
* **common:** titlecase pipe ([#22600](https://github.com/angular/angular/issues/22600)) ([7966744](https://github.com/angular/angular/commit/7966744))
|
||||
* **compiler:** don't typecheck all inputs ([#22899](https://github.com/angular/angular/issues/22899)) ([838a610](https://github.com/angular/angular/commit/838a610))
|
||||
* consistently rewrite Injector to INJECTOR ([#23008](https://github.com/angular/angular/issues/23008)) ([884bf0e](https://github.com/angular/angular/commit/884bf0e))
|
||||
* **compiler:** fix support for html-like text in translatable attributes ([#23053](https://github.com/angular/angular/issues/23053)) ([28058b7](https://github.com/angular/angular/commit/28058b7))
|
||||
* **compiler:** take quoting into account when determining if object literals can be shared ([#22942](https://github.com/angular/angular/issues/22942)) ([d98e9e7](https://github.com/angular/angular/commit/d98e9e7))
|
||||
* **compiler-cli:** use numeric comparison for TypeScript version ([#22705](https://github.com/angular/angular/issues/22705)) ([193737a](https://github.com/angular/angular/commit/193737a)), closes [#22593](https://github.com/angular/angular/issues/22593)
|
||||
* **core:** don't override ngInjectableDef in the decorator if present on the type ([#22943](https://github.com/angular/angular/issues/22943)) ([6f01917](https://github.com/angular/angular/commit/6f01917))
|
||||
* **service-worker:** do not enter degraded mode when offline ([#22883](https://github.com/angular/angular/issues/22883)) ([9e9b8dd](https://github.com/angular/angular/commit/9e9b8dd)), closes [#21636](https://github.com/angular/angular/issues/21636)
|
||||
* **service-worker:** fix LruList bugs ([#22769](https://github.com/angular/angular/issues/22769)) ([8c2a578](https://github.com/angular/angular/commit/8c2a578)), closes [#22218](https://github.com/angular/angular/issues/22218) [#22768](https://github.com/angular/angular/issues/22768)
|
||||
* **service-worker:** ignore invalid `only-if-cached` requests ([#22883](https://github.com/angular/angular/issues/22883)) ([d9dc46e](https://github.com/angular/angular/commit/d9dc46e)), closes [#22362](https://github.com/angular/angular/issues/22362)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* **bazel:** prefix private-export (barred-latin-o) symbols ([#23007](https://github.com/angular/angular/issues/23007)) ([27e14b2](https://github.com/angular/angular/commit/27e14b2))
|
||||
* **compiler:** lower @NgModule ids if needed ([#23031](https://github.com/angular/angular/issues/23031)) ([bd024c0](https://github.com/angular/angular/commit/bd024c0))
|
||||
|
||||
|
||||
|
||||
<a name="6.0.0-rc.0"></a>
|
||||
# [6.0.0-rc.0](https://github.com/angular/angular/compare/6.0.0-beta.8...6.0.0-rc.0) (2018-03-21)
|
||||
|
||||
v6 framework is now feature complete, the cli and material/cdk parts of the v6 release and other integrations are still
|
||||
in works and will be completed by the time we cut v6.0.0.
|
||||
|
||||
Please [file new issues](https://github.com/angular/angular/issues/new) at our issue tracker with as many details as
|
||||
possible, and ideally also a include a good reproduction of the problem.
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **bazel:** correct expected outs for external sources in ng_module ([#22755](https://github.com/angular/angular/issues/22755)) ([bfe077a](https://github.com/angular/angular/commit/bfe077a))
|
||||
* **compiler:** do not emit line/char in ngsummary files. ([#22840](https://github.com/angular/angular/issues/22840)) ([5c387a7](https://github.com/angular/angular/commit/5c387a7))
|
||||
* correct several esm2015 entry-points in package.jsons ([#22892](https://github.com/angular/angular/issues/22892)) ([7d095b9](https://github.com/angular/angular/commit/7d095b9))
|
||||
* **router:** don't use spread operator to workaround an issue in closure compiler ([#22884](https://github.com/angular/angular/issues/22884)) ([e6c731f](https://github.com/angular/angular/commit/e6c731f))
|
||||
* **router:** make locationSyncBootstrapListener public due to change in output after TS 2.7 update in [#22669](https://github.com/angular/angular/issues/22669) ([#22896](https://github.com/angular/angular/issues/22896)) ([623d769](https://github.com/angular/angular/commit/623d769))
|
||||
* **upgrade:** two-way binding and listening for event ([#22772](https://github.com/angular/angular/issues/22772)) ([2b3de63](https://github.com/angular/angular/commit/2b3de63)), closes [#22734](https://github.com/angular/angular/issues/22734)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* **core:** update the package output of build.sh to [APF v6](https://goo.gl/jB3GVv) ([#22808](https://github.com/angular/angular/issues/22808)) ([ce63dc6](https://github.com/angular/angular/commit/ce63dc6))
|
||||
* **core:** upgrade rxjs to 6.0.0-beta.0, please see this [RxJS Upgrade Guide](https://goo.gl/osWFzo) for more info ([#22573](https://github.com/angular/angular/issues/22573)) ([b43f8bc](https://github.com/angular/angular/commit/b43f8bc))
|
||||
|
||||
|
||||
|
||||
<a name="6.0.0-beta.8"></a>
|
||||
# [6.0.0-beta.8](https://github.com/angular/angular/compare/6.0.0-beta.7...6.0.0-beta.8) (2018-03-16)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **aio:** constrain error logging to improve reporting ([#22713](https://github.com/angular/angular/issues/22713)) ([049757b](https://github.com/angular/angular/commit/049757b))
|
||||
* **compiler-cli:** annotate Ivy fields as [@nocollapse](https://github.com/nocollapse) in closure mode ([#22691](https://github.com/angular/angular/issues/22691)) ([6e00410](https://github.com/angular/angular/commit/6e00410))
|
||||
* **compiler-cli:** disableTypeScriptVersionCheck should be applied even for older tsc versions ([#22669](https://github.com/angular/angular/issues/22669)) ([3f70aba](https://github.com/angular/angular/commit/3f70aba))
|
||||
* **compiler-cli:** emit correct css string escape sequences ([#22776](https://github.com/angular/angular/issues/22776)) ([6e5e819](https://github.com/angular/angular/commit/6e5e819))
|
||||
* **compiler-cli:** enableResourceInlining handles both styles and styleUrls ([#22688](https://github.com/angular/angular/issues/22688)) ([40315be](https://github.com/angular/angular/commit/40315be))
|
||||
* **compiler-cli:** generate proper exports.* identifiers in cjs output ([#22564](https://github.com/angular/angular/issues/22564)) ([0d8deb0](https://github.com/angular/angular/commit/0d8deb0))
|
||||
* **compiler-cli:** resolve resource URLs before loading them under enableResourceInlining ([#22688](https://github.com/angular/angular/issues/22688)) ([123efba](https://github.com/angular/angular/commit/123efba))
|
||||
* **core:** remove core animation import symbols ([#22692](https://github.com/angular/angular/issues/22692)) ([f5a98f4](https://github.com/angular/angular/commit/f5a98f4))
|
||||
* **elements:** fix elements test bootstrap ([#22839](https://github.com/angular/angular/issues/22839)) ([5d82d8d](https://github.com/angular/angular/commit/5d82d8d))
|
||||
* overloading a function doesn't generate all of the signatures ([#22569](https://github.com/angular/angular/issues/22569)) ([e8326e6](https://github.com/angular/angular/commit/e8326e6))
|
||||
* **platform-server:** add styles to elements correctly ([#22527](https://github.com/angular/angular/issues/22527)) ([cd2ebd2](https://github.com/angular/angular/commit/cd2ebd2))
|
||||
* **router:** correct over-encoding of URL fragment ([#22687](https://github.com/angular/angular/issues/22687)) ([0bf6fa5](https://github.com/angular/angular/commit/0bf6fa5))
|
||||
|
||||
|
||||
### Code Refactoring
|
||||
|
||||
* **compiler:** Drop support for the deprecated `<template>`. Use `<ng-template>` instead ([#22783](https://github.com/angular/angular/issues/22783)) ([0ebd577](https://github.com/angular/angular/commit/0ebd577))
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* **aio:** add hack, remove me ([#22413](https://github.com/angular/angular/issues/22413)) ([4d506ac](https://github.com/angular/angular/commit/4d506ac))
|
||||
* **aio:** migrate embedded comp to elements ([#22413](https://github.com/angular/angular/issues/22413)) ([7c9b411](https://github.com/angular/angular/commit/7c9b411))
|
||||
* **aio:** update payload size ([#22413](https://github.com/angular/angular/issues/22413)) ([400460c](https://github.com/angular/angular/commit/400460c))
|
||||
* **animations:** expose `element` and `params` within transition matchers ([#22693](https://github.com/angular/angular/issues/22693)) ([58b94e6](https://github.com/angular/angular/commit/58b94e6))
|
||||
* **bazel:** change ng_package rule to APF v6 ([#22782](https://github.com/angular/angular/issues/22782)) ([88b3198](https://github.com/angular/angular/commit/88b3198))
|
||||
* **compiler:** support for singleline, multiline & jsdoc comments ([#22715](https://github.com/angular/angular/issues/22715)) ([3b167be](https://github.com/angular/angular/commit/3b167be))
|
||||
* **compiler-cli:** add resource inlining to ngc ([#22615](https://github.com/angular/angular/issues/22615)) ([b5be18f](https://github.com/angular/angular/commit/b5be18f))
|
||||
* **compiler-cli:** require node 8 as runtime engine ([#22669](https://github.com/angular/angular/issues/22669)) ([c602563](https://github.com/angular/angular/commit/c602563))
|
||||
* **core:** add task tracking to Testability ([#16863](https://github.com/angular/angular/issues/16863)) ([37fedd0](https://github.com/angular/angular/commit/37fedd0))
|
||||
* **elements:** add polyfill for elements es5 shim ([#22413](https://github.com/angular/angular/issues/22413)) ([863aff1](https://github.com/angular/angular/commit/863aff1))
|
||||
* **elements:** add support for creating custom elements ([#22413](https://github.com/angular/angular/issues/22413)) ([22b96b9](https://github.com/angular/angular/commit/22b96b9))
|
||||
* **elements:** add tests for component factory strategy ([#22413](https://github.com/angular/angular/issues/22413)) ([d2be675](https://github.com/angular/angular/commit/d2be675))
|
||||
* **elements:** another polyfill solution ([#22413](https://github.com/angular/angular/issues/22413)) ([cf3ff7d](https://github.com/angular/angular/commit/cf3ff7d))
|
||||
* **elements:** fix lint ([#22413](https://github.com/angular/angular/issues/22413)) ([0b45dfa](https://github.com/angular/angular/commit/0b45dfa))
|
||||
* **elements:** fix payload size ([#22413](https://github.com/angular/angular/issues/22413)) ([fe21437](https://github.com/angular/angular/commit/fe21437))
|
||||
* **elements:** fix test ([#22413](https://github.com/angular/angular/issues/22413)) ([44f637a](https://github.com/angular/angular/commit/44f637a))
|
||||
* **elements:** George's comments ([#22413](https://github.com/angular/angular/issues/22413)) ([46efd4b](https://github.com/angular/angular/commit/46efd4b))
|
||||
* **elements:** injector create ([#22413](https://github.com/angular/angular/issues/22413)) ([87f60bc](https://github.com/angular/angular/commit/87f60bc))
|
||||
* **elements:** make bazel happy ([#22413](https://github.com/angular/angular/issues/22413)) ([39a12d2](https://github.com/angular/angular/commit/39a12d2))
|
||||
* **elements:** provide type, not factory; remove config need ([#22413](https://github.com/angular/angular/issues/22413)) ([1936808](https://github.com/angular/angular/commit/1936808))
|
||||
* **elements:** rebase ([#22413](https://github.com/angular/angular/issues/22413)) ([d72f445](https://github.com/angular/angular/commit/d72f445))
|
||||
* **elements:** remove attribute/input from config ([#22413](https://github.com/angular/angular/issues/22413)) ([688096b](https://github.com/angular/angular/commit/688096b))
|
||||
* **elements:** rename API to createCustomElement ([#22413](https://github.com/angular/angular/issues/22413)) ([167fdf7](https://github.com/angular/angular/commit/167fdf7))
|
||||
* **elements:** update package.json with latest ([#22413](https://github.com/angular/angular/issues/22413)) ([2e450f6](https://github.com/angular/angular/commit/2e450f6))
|
||||
* mark angular packages as side-effect free ([#22785](https://github.com/angular/angular/issues/22785)) ([44de10e](https://github.com/angular/angular/commit/44de10e))
|
||||
* tree-shakeable providers API updates ([#22655](https://github.com/angular/angular/issues/22655)) ([db56836](https://github.com/angular/angular/commit/db56836))
|
||||
* update tslib to 1.9.0 ([#22667](https://github.com/angular/angular/issues/22667)) ([489fec1](https://github.com/angular/angular/commit/489fec1))
|
||||
|
||||
|
||||
### BREAKING CHANGES
|
||||
|
||||
* **compiler:** The `<template>` tag was deprecated in Angular v4 to avoid collisions (i.e. when
|
||||
using Web Components).
|
||||
|
||||
This commit removes support for `<template>`. `<ng-template>` should be used
|
||||
instead.
|
||||
|
||||
BEFORE:
|
||||
|
||||
<!-- html template -->
|
||||
<template>some template content</template>
|
||||
|
||||
# tsconfig.json
|
||||
{
|
||||
# ...
|
||||
"angularCompilerOptions": {
|
||||
# ...
|
||||
# This option is no more supported and will have no effect
|
||||
"enableLegacyTemplate": [true|false]
|
||||
}
|
||||
}
|
||||
|
||||
AFTER:
|
||||
|
||||
<!-- html template -->
|
||||
<ng-template>some template content</ng-template>
|
||||
* **core:** it is no longer possible to import
|
||||
animation-related functions from @angular/core. All
|
||||
animation symbols must now be imported from @angular/animations.
|
||||
* after this change, npm and yarn will issue incompatible peerDependencies warning
|
||||
|
||||
We don't expect this to actually break an application, but the application/library package.json
|
||||
will need to be updated to provide tslib 1.9.0 or higher.
|
||||
|
||||
|
||||
|
||||
<a name="5.2.9"></a>
|
||||
## [5.2.9](https://github.com/angular/angular/compare/5.2.8...5.2.9) (2018-03-14)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **platform-server:** add styles to elements correctly ([#22527](https://github.com/angular/angular/issues/22527)) ([fc6dfc2](https://github.com/angular/angular/commit/fc6dfc2))
|
||||
* **router:** correct over-encoding of URL fragment ([#22687](https://github.com/angular/angular/issues/22687)) ([86517f2](https://github.com/angular/angular/commit/86517f2))
|
||||
|
||||
|
||||
|
||||
<a name="6.0.0-beta.7"></a>
|
||||
# [6.0.0-beta.7](https://github.com/angular/angular/compare/6.0.0-beta.6...6.0.0-beta.7) (2018-03-07)
|
||||
|
||||
@ -226,7 +390,7 @@ If that is the case, you should be able to track the old value directly by savin
|
||||
* **common:** don't convert null to a string when flushing a mock request ([#21417](https://github.com/angular/angular/issues/21417)) ([8b14488](https://github.com/angular/angular/commit/8b14488)), closes [#20744](https://github.com/angular/angular/issues/20744)
|
||||
* **core:** fix [#20582](https://github.com/angular/angular/issues/20582), don't need to wrap zone in location change listener ([#20640](https://github.com/angular/angular/issues/20640)) ([f791e9f](https://github.com/angular/angular/commit/f791e9f))
|
||||
* **core:** fix proper propagation of subscriptions in EventEmitter ([#22016](https://github.com/angular/angular/issues/22016)) ([e81606c](https://github.com/angular/angular/commit/e81606c)), closes [#21999](https://github.com/angular/angular/issues/21999)
|
||||
* **core:** should check Zone existance when scheduleMicroTask ([#20656](https://github.com/angular/angular/issues/20656)) ([3a86940](https://github.com/angular/angular/commit/3a86940))
|
||||
* **core:** should check Zone existence when scheduleMicroTask ([#20656](https://github.com/angular/angular/issues/20656)) ([3a86940](https://github.com/angular/angular/commit/3a86940))
|
||||
* **forms:** publish missing types ([#19941](https://github.com/angular/angular/issues/19941)) ([2707012](https://github.com/angular/angular/commit/2707012))
|
||||
* **ivy:** generate correct interpolations ([#21946](https://github.com/angular/angular/issues/21946)) ([3cc1d76](https://github.com/angular/angular/commit/3cc1d76))
|
||||
* **ivy:** generate lifecycle pattern ([#21865](https://github.com/angular/angular/issues/21865)) ([f816666](https://github.com/angular/angular/commit/f816666))
|
||||
@ -257,7 +421,7 @@ If that is the case, you should be able to track the old value directly by savin
|
||||
* **common:** don't convert null to a string when flushing a mock request ([#21417](https://github.com/angular/angular/issues/21417)) ([c4fb696](https://github.com/angular/angular/commit/c4fb696)), closes [#20744](https://github.com/angular/angular/issues/20744)
|
||||
* **core:** fix [#20582](https://github.com/angular/angular/issues/20582), don't need to wrap zone in location change listener ([#22007](https://github.com/angular/angular/issues/22007)) ([ce51ea9](https://github.com/angular/angular/commit/ce51ea9))
|
||||
* **core:** fix proper propagation of subscriptions in EventEmitter ([#22016](https://github.com/angular/angular/issues/22016)) ([c6645e7](https://github.com/angular/angular/commit/c6645e7)), closes [#21999](https://github.com/angular/angular/issues/21999)
|
||||
* **core:** should check Zone existance when scheduleMicroTask ([#20656](https://github.com/angular/angular/issues/20656)) ([aa9ba7f](https://github.com/angular/angular/commit/aa9ba7f))
|
||||
* **core:** should check Zone existence when scheduleMicroTask ([#20656](https://github.com/angular/angular/issues/20656)) ([aa9ba7f](https://github.com/angular/angular/commit/aa9ba7f))
|
||||
|
||||
|
||||
|
||||
@ -1678,7 +1842,7 @@ From 4.0.0 @angular/core uses a [`WeakMap`](https://github.com/angular/angular/c
|
||||
* **compiler:** make sourcemaps work in AOT mode ([492153a](https://github.com/angular/angular/commit/492153a))
|
||||
* **compiler:** only warn for `[@Injectable](https://github.com/Injectable)` classes with invalid args. ([5c34066](https://github.com/angular/angular/commit/5c34066)), closes [#15003](https://github.com/angular/angular/issues/15003)
|
||||
* **compiler:** shouldn't throw when Symbol is used as DI token ([#13701](https://github.com/angular/angular/issues/13701)) ([8b5c6b2](https://github.com/angular/angular/commit/8b5c6b2)), closes [#13314](https://github.com/angular/angular/issues/13314)
|
||||
* **compiler:** support interface types in injectable constuctors ([#14894](https://github.com/angular/angular/issues/14894)) ([b00fe20](https://github.com/angular/angular/commit/b00fe20)), closes [#12631](https://github.com/angular/angular/issues/12631)
|
||||
* **compiler:** support interface types in injectable constructors ([#14894](https://github.com/angular/angular/issues/14894)) ([b00fe20](https://github.com/angular/angular/commit/b00fe20)), closes [#12631](https://github.com/angular/angular/issues/12631)
|
||||
* **compiler:** warning prints "WARNING" instead of "ERROR" ([#15125](https://github.com/angular/angular/issues/15125)) ([3b1956b](https://github.com/angular/angular/commit/3b1956b))
|
||||
* **core:** don’t recreate `TemplateRef` when used as a reference. ([#15066](https://github.com/angular/angular/issues/15066)) ([df914ef](https://github.com/angular/angular/commit/df914ef)), closes [#14873](https://github.com/angular/angular/issues/14873)
|
||||
* **core:** don’t throw if queries change during change detection. ([06fc42b](https://github.com/angular/angular/commit/06fc42b)), closes [#14925](https://github.com/angular/angular/issues/14925)
|
||||
@ -1718,7 +1882,7 @@ From 4.0.0 @angular/core uses a [`WeakMap`](https://github.com/angular/angular/c
|
||||
|
||||
### BREAKING CHANGES
|
||||
|
||||
* Perviously, any provider that had an ngOnDestroy lifecycle hook would be created eagerly.
|
||||
* Previously, any provider that had an ngOnDestroy lifecycle hook would be created eagerly.
|
||||
|
||||
Now, only classes that are annotated with @Component, @Directive, @Pipe, @NgModule are eager. Providers only become eager if they are either directly or transitively injected into one of the above.
|
||||
|
||||
@ -1986,7 +2150,7 @@ Note: the 4.0.0-rc.0 release on npm accidentally omitted one bug fix, so we cut
|
||||
* **compiler:** improve error message for unknown elements ([#14373](https://github.com/angular/angular/issues/14373)) ([2c6dab9](https://github.com/angular/angular/commit/2c6dab9))
|
||||
* **compiler:** improve error messages in aot compiler ([#14333](https://github.com/angular/angular/issues/14333)) ([a696f4a](https://github.com/angular/angular/commit/a696f4a))
|
||||
* **compiler:** improve error msg for unknown properties on ([#14373](https://github.com/angular/angular/issues/14373)) ([e5a144d](https://github.com/angular/angular/commit/e5a144d)), closes [#14070](https://github.com/angular/angular/issues/14070)
|
||||
* **core:** Remove ChangeDetectorRef Paramter from KeyValueDifferFactory and IterableDifferFactory ([#14311](https://github.com/angular/angular/issues/14311)) ([45cc444](https://github.com/angular/angular/commit/45cc444))
|
||||
* **core:** Remove ChangeDetectorRef Parameter from KeyValueDifferFactory and IterableDifferFactory ([#14311](https://github.com/angular/angular/issues/14311)) ([45cc444](https://github.com/angular/angular/commit/45cc444))
|
||||
* **core:** suppress a Closure Compiler warning ([#14484](https://github.com/angular/angular/issues/14484)) ([2f2b65b](https://github.com/angular/angular/commit/2f2b65b))
|
||||
* **forms:** getRawValue should correctly work with nested FormGroups/Arrays ([#12964](https://github.com/angular/angular/issues/12964)) ([1ece736](https://github.com/angular/angular/commit/1ece736)), closes [#12963](https://github.com/angular/angular/issues/12963)
|
||||
* **http:** REVERT: remove dots from jsonp callback name ([#13219](https://github.com/angular/angular/issues/13219)) ([4676df5](https://github.com/angular/angular/commit/4676df5))
|
||||
@ -2171,7 +2335,7 @@ returned value being an array.
|
||||
### Bug Fixes
|
||||
|
||||
* **common:** add PopStateEvent interface ([#13400](https://github.com/angular/angular/issues/13400)) ([71567d1](https://github.com/angular/angular/commit/71567d1)), closes [#13378](https://github.com/angular/angular/issues/13378)
|
||||
* **common:** DatePipe does't throw for NaN ([#14117](https://github.com/angular/angular/issues/14117)) ([32cc675](https://github.com/angular/angular/commit/32cc675)), closes [#14103](https://github.com/angular/angular/issues/14103)
|
||||
* **common:** DatePipe doesn't throw for NaN ([#14117](https://github.com/angular/angular/issues/14117)) ([32cc675](https://github.com/angular/angular/commit/32cc675)), closes [#14103](https://github.com/angular/angular/issues/14103)
|
||||
* **common:** DatePipe parses input string if it's not a valid date in browser ([#13895](https://github.com/angular/angular/issues/13895)) ([e641636](https://github.com/angular/angular/commit/e641636)), closes [#12334](https://github.com/angular/angular/issues/12334) [#13874](https://github.com/angular/angular/issues/13874)
|
||||
* **common:** introduce isObservable method ([#14067](https://github.com/angular/angular/issues/14067)) ([109f0d1](https://github.com/angular/angular/commit/109f0d1)), closes [#8848](https://github.com/angular/angular/issues/8848)
|
||||
* **compiler:** allow empty translations for attributes ([#14085](https://github.com/angular/angular/issues/14085)) ([f3d5506](https://github.com/angular/angular/commit/f3d5506)), closes [#13897](https://github.com/angular/angular/issues/13897)
|
||||
@ -2589,7 +2753,7 @@ We are adding more tests to our test suite to catch these kinds of problems befo
|
||||
* **common:** make sure the plural category exists ([#13169](https://github.com/angular/angular/issues/13169)) ([82c81cd](https://github.com/angular/angular/commit/82c81cd)), closes [#12379](https://github.com/angular/angular/issues/12379)
|
||||
* **compiler:** include the summaries of reexported modules / directives / pipes ([#13196](https://github.com/angular/angular/issues/13196)) ([75d1617](https://github.com/angular/angular/commit/75d1617))
|
||||
* **compiler:** serialize any `StaticSymbol` correctly, not matter in which context ([5614c4f](https://github.com/angular/angular/commit/5614c4f))
|
||||
* **compiler:** short-circut expressions with an index ([#13263](https://github.com/angular/angular/issues/13263)) ([f31c947](https://github.com/angular/angular/commit/f31c947)), closes [#13254](https://github.com/angular/angular/issues/13254)
|
||||
* **compiler:** short-circuit expressions with an index ([#13263](https://github.com/angular/angular/issues/13263)) ([f31c947](https://github.com/angular/angular/commit/f31c947)), closes [#13254](https://github.com/angular/angular/issues/13254)
|
||||
* **core:** display framework version on bootstrapped component ([#13252](https://github.com/angular/angular/issues/13252)) ([16efb13](https://github.com/angular/angular/commit/16efb13))
|
||||
* **facade:** cache original format string ([#12764](https://github.com/angular/angular/issues/12764)) ([a132287](https://github.com/angular/angular/commit/a132287))
|
||||
* **http:** set the default Accept header ([#12989](https://github.com/angular/angular/issues/12989)) ([986abbe](https://github.com/angular/angular/commit/986abbe)), closes [#6354](https://github.com/angular/angular/issues/6354)
|
||||
|
@ -212,6 +212,7 @@ The following is the list of supported scopes:
|
||||
* **compiler**
|
||||
* **compiler-cli**
|
||||
* **core**
|
||||
* **elements**
|
||||
* **forms**
|
||||
* **http**
|
||||
* **language-service**
|
||||
|
26
WORKSPACE
26
WORKSPACE
@ -2,18 +2,21 @@ workspace(name = "angular")
|
||||
|
||||
http_archive(
|
||||
name = "build_bazel_rules_nodejs",
|
||||
url = "https://github.com/bazelbuild/rules_nodejs/archive/f03c8b5df155da2a640b6775afdd4fe4aa6fec72.zip",
|
||||
strip_prefix = "rules_nodejs-f03c8b5df155da2a640b6775afdd4fe4aa6fec72",
|
||||
sha256 = "9d541f49af8cf60c73efb102186bfa5670ee190a088ce52638dcdf90cd9e2de6",
|
||||
url = "https://github.com/bazelbuild/rules_nodejs/archive/0.6.0.zip",
|
||||
strip_prefix = "rules_nodejs-0.6.0",
|
||||
sha256 = "e8a2bb5ca51fbafb244bc507bcebcae33a63d969f47413b319a8dcce032845bf",
|
||||
)
|
||||
|
||||
load("@build_bazel_rules_nodejs//:defs.bzl", "check_bazel_version", "node_repositories")
|
||||
load("@build_bazel_rules_nodejs//:defs.bzl", "check_bazel_version", "node_repositories", "yarn_install")
|
||||
|
||||
check_bazel_version("0.9.0")
|
||||
node_repositories(package_json = [
|
||||
"//:package.json",
|
||||
"//tools/ts-api-guardian:package.json",
|
||||
])
|
||||
node_repositories(package_json = ["//:package.json"])
|
||||
|
||||
yarn_install(
|
||||
name = "ts-api-guardian_runtime_deps",
|
||||
package_json = "//tools/ts-api-guardian:package.json",
|
||||
yarn_lock = "//tools/ts-api-guardian:yarn.lock",
|
||||
)
|
||||
|
||||
http_archive(
|
||||
name = "build_bazel_rules_typescript",
|
||||
@ -31,6 +34,13 @@ local_repository(
|
||||
path = "node_modules/rxjs/src",
|
||||
)
|
||||
|
||||
# Point to the integration test workspace just so that Bazel doesn't descend into it
|
||||
# when expanding the //... pattern
|
||||
local_repository(
|
||||
name = "bazel_integration_test",
|
||||
path = "integration/bazel",
|
||||
)
|
||||
|
||||
# This commit matches the version of buildifier in angular/ngcontainer
|
||||
# If you change this, also check if it matches the version in the angular/ngcontainer
|
||||
# version in /.circleci/config.yml
|
||||
|
@ -13,7 +13,9 @@
|
||||
"app/search/search-worker.js",
|
||||
"favicon.ico",
|
||||
"pwa-manifest.json",
|
||||
"google385281288605d160.html"
|
||||
"google385281288605d160.html",
|
||||
{ "glob": "custom-elements.min.js", "input": "../node_modules/@webcomponents/custom-elements", "output": "./assets/js" },
|
||||
{ "glob": "native-shim.js", "input": "../node_modules/@webcomponents/custom-elements/src", "output": "./assets/js" }
|
||||
],
|
||||
"index": "index.html",
|
||||
"main": "main.ts",
|
||||
|
@ -74,7 +74,7 @@ sudo docker run \
|
||||
## Example
|
||||
The following command would start a docker container based on the previously created `foobar-builds`
|
||||
docker image, alias it as 'foobar-builds-1' and map predefined directories on the host VM to be used
|
||||
by the container for accesing secrets and SSL certificates and keeping the build artifacts and logs.
|
||||
by the container for accessing secrets and SSL certificates and keeping the build artifacts and logs.
|
||||
|
||||
```
|
||||
sudo docker run \
|
||||
|
@ -178,6 +178,11 @@ describe('Dependency Injection Tests', function () {
|
||||
expect(heroes.count()).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('authorized user should have multiple authorized heroes with tree-shakeable HeroesService', function () {
|
||||
let heroes = element.all(by.css('#tspAuthorized app-hero-list div'));
|
||||
expect(heroes.count()).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('authorized user should have secret heroes', function () {
|
||||
let heroes = element.all(by.css('#authorized app-hero-list div'));
|
||||
expect(heroes.count()).toBeGreaterThan(0);
|
||||
|
@ -21,6 +21,7 @@ import { UserService } from './user.service';
|
||||
<p>
|
||||
<app-heroes id="authorized" *ngIf="isAuthorized"></app-heroes>
|
||||
<app-heroes id="unauthorized" *ngIf="!isAuthorized"></app-heroes>
|
||||
<app-heroes-tsp id="tspAuthorized" *ngIf="isAuthorized"></app-heroes-tsp>
|
||||
<app-providers></app-providers>
|
||||
`
|
||||
})
|
||||
|
@ -6,6 +6,7 @@ import { APP_CONFIG, HERO_DI_CONFIG } from './app.config';
|
||||
import { AppComponent } from './app.component';
|
||||
import { CarComponent } from './car/car.component';
|
||||
import { HeroesComponent } from './heroes/heroes.component';
|
||||
import { HeroesTspComponent } from './heroes/heroes-tsp.component';
|
||||
import { HeroListComponent } from './heroes/hero-list.component';
|
||||
import { InjectorComponent } from './injector.component';
|
||||
import { Logger } from './logger.service';
|
||||
@ -25,6 +26,7 @@ import { ProvidersModule } from './providers.module';
|
||||
CarComponent,
|
||||
HeroesComponent,
|
||||
// #enddocregion ngmodule
|
||||
HeroesTspComponent,
|
||||
HeroListComponent,
|
||||
InjectorComponent,
|
||||
TestComponent
|
||||
|
@ -0,0 +1,6 @@
|
||||
// #docregion
|
||||
import { NgModule } from '@angular/core';
|
||||
|
||||
@NgModule({})
|
||||
export class HeroModule {
|
||||
}
|
@ -1,6 +1,8 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
|
||||
@Injectable()
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class HeroService {
|
||||
constructor() { }
|
||||
}
|
||||
|
@ -2,7 +2,9 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { HEROES } from './mock-heroes';
|
||||
|
||||
@Injectable()
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class HeroService {
|
||||
getHeroes() { return HEROES; }
|
||||
}
|
||||
|
@ -3,7 +3,9 @@ import { Injectable } from '@angular/core';
|
||||
import { HEROES } from './mock-heroes';
|
||||
import { Logger } from '../logger.service';
|
||||
|
||||
@Injectable()
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class HeroService {
|
||||
|
||||
// #docregion ctor
|
||||
|
@ -0,0 +1,13 @@
|
||||
// #docregion
|
||||
import { Injectable } from '@angular/core';
|
||||
import { HEROES } from './mock-heroes';
|
||||
|
||||
@Injectable({
|
||||
// we declare that this service should be created
|
||||
// by the root application injector.
|
||||
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class HeroService {
|
||||
getHeroes() { return HEROES; }
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
// #docregion
|
||||
import { Injectable } from '@angular/core';
|
||||
import { HeroModule } from './hero.module';
|
||||
import { HEROES } from './mock-heroes';
|
||||
|
||||
@Injectable({
|
||||
// we declare that this service should be created
|
||||
// by any injector that includes HeroModule.
|
||||
|
||||
providedIn: HeroModule,
|
||||
})
|
||||
export class HeroService {
|
||||
getHeroes() { return HEROES; }
|
||||
}
|
@ -2,8 +2,14 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { HEROES } from './mock-heroes';
|
||||
import { Logger } from '../logger.service';
|
||||
import { UserService } from '../user.service';
|
||||
|
||||
@Injectable()
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
useFactory: (logger: Logger, userService: UserService) =>
|
||||
new HeroService(logger, userService.user.isAuthorized),
|
||||
deps: [Logger, UserService],
|
||||
})
|
||||
export class HeroService {
|
||||
// #docregion internals
|
||||
constructor(
|
||||
|
@ -0,0 +1,16 @@
|
||||
import { Component } from '@angular/core';
|
||||
|
||||
/**
|
||||
* A version of `HeroesComponent` that does not provide the `HeroService` (and thus relies on its
|
||||
* `Injectable`-declared provider) in order to function.
|
||||
*
|
||||
* TSP stands for Tree-Shakeable Provider.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-heroes-tsp',
|
||||
template: `
|
||||
<h2>Heroes</h2>
|
||||
<app-hero-list></app-hero-list>
|
||||
`
|
||||
})
|
||||
export class HeroesTspComponent { }
|
@ -0,0 +1,15 @@
|
||||
import { NgModule } from '@angular/core';
|
||||
import { BrowserModule } from '@angular/platform-browser';
|
||||
import { RouterModule } from '@angular/router';
|
||||
import { ServiceModule } from './service-and-module';
|
||||
|
||||
// #docregion
|
||||
@NgModule({
|
||||
imports: [
|
||||
BrowserModule,
|
||||
RouterModule.forRoot([]),
|
||||
ServiceModule,
|
||||
],
|
||||
})
|
||||
export class AppModule {
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
// #docregion
|
||||
import { Injectable, NgModule } from '@angular/core';
|
||||
|
||||
@Injectable()
|
||||
export class Service {
|
||||
doSomething(): void {
|
||||
}
|
||||
}
|
||||
|
||||
@NgModule({
|
||||
providers: [Service],
|
||||
})
|
||||
export class ServiceModule {
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
|
||||
// #docregion
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
useFactory: () => new Service('dependency'),
|
||||
})
|
||||
export class Service {
|
||||
constructor(private dep: string) {
|
||||
}
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
|
||||
// #docregion
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class Service {
|
||||
}
|
@ -3,7 +3,7 @@
|
||||
"files":[
|
||||
"!**/*.d.ts",
|
||||
"!**/*.js",
|
||||
"!**/*.[0,1,2].*",
|
||||
"!**/*.[0,1,2,3,4].*",
|
||||
"!**/dummy.module.ts"
|
||||
],
|
||||
"tags": ["dependency", "di"]
|
||||
|
@ -6,7 +6,6 @@ import { UserService } from './user.service';
|
||||
|
||||
@NgModule({
|
||||
imports: [ BrowserModule ],
|
||||
providers: [ UserService ],
|
||||
declarations: [ AppComponent ],
|
||||
bootstrap: [ AppComponent ]
|
||||
})
|
||||
|
9
aio/content/examples/providers/src/app/user.module.ts
Normal file
9
aio/content/examples/providers/src/app/user.module.ts
Normal file
@ -0,0 +1,9 @@
|
||||
import { NgModule } from '@angular/core';
|
||||
|
||||
import { UserService } from './user.service';
|
||||
|
||||
@NgModule({
|
||||
providers: [UserService],
|
||||
})
|
||||
export class UserModule {
|
||||
}
|
7
aio/content/examples/providers/src/app/user.service.0.ts
Normal file
7
aio/content/examples/providers/src/app/user.service.0.ts
Normal file
@ -0,0 +1,7 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class UserService {
|
||||
}
|
8
aio/content/examples/providers/src/app/user.service.1.ts
Normal file
8
aio/content/examples/providers/src/app/user.service.1.ts
Normal file
@ -0,0 +1,8 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { UserModule } from './user.module';
|
||||
|
||||
@Injectable({
|
||||
providedIn: UserModule,
|
||||
})
|
||||
export class UserService {
|
||||
}
|
@ -3,9 +3,7 @@ import { UserService } from './user.service';
|
||||
|
||||
describe('UserService', () => {
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [UserService]
|
||||
});
|
||||
TestBed.configureTestingModule({});
|
||||
});
|
||||
|
||||
it('should ...', inject([UserService], (service: UserService) => {
|
||||
|
@ -5,7 +5,9 @@ export class User {
|
||||
name: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class UserService {
|
||||
|
||||
constructor() { }
|
||||
|
@ -3,7 +3,7 @@
|
||||
"files": [
|
||||
"!**/*.d.ts",
|
||||
"!**/*.js",
|
||||
"!**/*.[1,2].*"
|
||||
"!**/*.[0,1,2].*"
|
||||
],
|
||||
"file": "src/app/app.component.ts",
|
||||
"tags": ["providers"]
|
||||
|
@ -6,7 +6,7 @@ import { filter, map } from 'rxjs/operators';
|
||||
|
||||
const squareOdd = of(1, 2, 3, 4, 5)
|
||||
.pipe(
|
||||
filter(n => n % 2),
|
||||
filter(n => n % 2 !== 0),
|
||||
map(n => n * n)
|
||||
);
|
||||
|
||||
|
@ -59,7 +59,8 @@ describe('Style Guide', function () {
|
||||
expect(buttons.get(1).getText()).toBe('Hide toast');
|
||||
});
|
||||
|
||||
it('03-06', function () {
|
||||
// temporarily disabled because of a weird issue when used with rxjs v6 with rxjs-compat
|
||||
xit('03-06', function () {
|
||||
browser.get('#/03-06');
|
||||
|
||||
let div = element(by.tagName('sg-app > div'));
|
||||
@ -158,7 +159,8 @@ describe('Style Guide', function () {
|
||||
expect(input.isPresent()).toBe(true);
|
||||
});
|
||||
|
||||
it('07-01', function () {
|
||||
// temporarily disabled because of a weird issue when used with rxjs v6 with rxjs-compat
|
||||
xit('07-01', function () {
|
||||
browser.get('#/07-01');
|
||||
|
||||
let lis = element.all(by.tagName('sg-app > ul > li'));
|
||||
|
@ -8,6 +8,5 @@ import { HeroService } from './heroes';
|
||||
template: `
|
||||
<toh-heroes></toh-heroes>
|
||||
`,
|
||||
providers: [HeroService]
|
||||
})
|
||||
export class AppComponent {}
|
||||
|
@ -5,7 +5,9 @@ import { Observable, of } from 'rxjs';
|
||||
|
||||
import { Hero } from './hero.model';
|
||||
|
||||
@Injectable()
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class HeroService {
|
||||
getHeroes() {
|
||||
let heroes: Hero[] = [];
|
||||
|
@ -1,7 +1,7 @@
|
||||
// #docregion
|
||||
import { Pipe, PipeTransform } from '@angular/core';
|
||||
|
||||
@Pipe({name: 'titlecase', pure: false})
|
||||
@Pipe({name: 'titlecase', pure: true})
|
||||
/** Transform to Title Case: uppercase the first letter of the words in a string.*/
|
||||
export class TitleCasePipe implements PipeTransform {
|
||||
transform(input: string): string {
|
||||
|
@ -188,7 +188,7 @@ This option should be set to `false` when using factory summaries.
|
||||
|
||||
### *fullTemplateTypeCheck*
|
||||
|
||||
This option tells the compiler to enable the [binding expression validation](#binding-expresion-validation)
|
||||
This option tells the compiler to enable the [binding expression validation](#binding-expression-validation)
|
||||
phase of the template compiler which uses TypeScript to validate binding expressions.
|
||||
|
||||
This option is `false` by default.
|
||||
@ -204,7 +204,7 @@ JavaScript with [JsDoc](http://usejsdoc.org/) comments needed by the
|
||||
### *annotationsAs*
|
||||
|
||||
Use this option to modify how the Angular specific annotations are emitted to improve tree-shaking. Non-Angular
|
||||
annotations and decorators are unnaffected. Default is `static fields`.
|
||||
annotations and decorators are unaffected. Default is `static fields`.
|
||||
|
||||
value | description
|
||||
----------------|-------------------------------------------------------------
|
||||
@ -215,13 +215,6 @@ value | description
|
||||
|
||||
This tells the compiler to print extra information while compiling templates.
|
||||
|
||||
### *enableLegacyTemplate*
|
||||
|
||||
The use of `<template>` element was deprecated starting in Angular 4.0 in favor of using
|
||||
`<ng-template>` to avoid colliding with the DOM's element of the same name. Setting this option to
|
||||
`true` enables the use of the deprecated `<template>` element . This option
|
||||
is `false` by default. This option might be required by some third-party Angular libraries.
|
||||
|
||||
### *disableExpressionLowering*
|
||||
|
||||
The Angular template compiler transforms code that is used, or could be used, in an annotation
|
||||
@ -386,7 +379,7 @@ export function serverFactory() {
|
||||
})
|
||||
```
|
||||
|
||||
Beginning in version 5, the compiler automatically performs this rewritting while emitting the `.js` file.
|
||||
Beginning in version 5, the compiler automatically performs this rewriting while emitting the `.js` file.
|
||||
|
||||
{@a function-calls}
|
||||
### Limited function calls
|
||||
@ -654,7 +647,7 @@ The following are metadata errors you may encounter, with explanations and sugge
|
||||
|
||||
<h3 class="no-toc">Expression form not supported</h3>
|
||||
|
||||
The compiler encountered an expression it didn't understand while evalutating Angular metadata.
|
||||
The compiler encountered an expression it didn't understand while evaluating Angular metadata.
|
||||
|
||||
Language features outside of the compiler's [restricted expression syntax](#expression-syntax)
|
||||
can produce this error, as seen in the following example:
|
||||
@ -1140,12 +1133,12 @@ This error can occur if you use an expression in the `extends` clause of a class
|
||||
Chuck: After reviewing your PR comment I'm still at a loss. See [comment there](https://github.com/angular/angular/pull/17712#discussion_r132025495).
|
||||
|
||||
-->
|
||||
{@a binding-expresion-validation}
|
||||
{@a binding-expression-validation}
|
||||
|
||||
## Phase 3: binding expression validation
|
||||
|
||||
In the validation phase, the Angular template compiler uses the TypeScript compiler to validate the
|
||||
binding expressions in templates. Enable this phase explicity by adding the compiler
|
||||
binding expressions in templates. Enable this phase explicitly by adding the compiler
|
||||
option `"fullTemplateTypeCheck"` in the `"angularCompilerOptions"` of the project's `tsconfig.json` (see
|
||||
[Angular Compiler Options](#compiler-options)).
|
||||
|
||||
@ -1175,7 +1168,7 @@ Chuck: After reviewing your PR comment I'm still at a loss. See [comment there](
|
||||
generated by the template compiler that holds contents of the `MyComponent` class template.
|
||||
Compiler never writes this file to disk. The line and column numbers are relative to the template string
|
||||
in the `@Component` annotation of the class, `MyComponent` in this case. If a component uses
|
||||
`templateUrl` instead of `template`, the errors are reported in the HTML file refereneced by the
|
||||
`templateUrl` instead of `template`, the errors are reported in the HTML file referenced by the
|
||||
`templateUrl` instead of a synthetic file.
|
||||
|
||||
The error location is the beginning of the text node that contains the interpolation expression with
|
||||
|
180
aio/content/guide/architecture-components.md
Normal file
180
aio/content/guide/architecture-components.md
Normal file
@ -0,0 +1,180 @@
|
||||
# Introduction to components
|
||||
|
||||
<img src="generated/images/guide/architecture/hero-component.png" alt="Component" class="left">
|
||||
|
||||
A _component_ controls a patch of screen called a *view*. For example, individual components define and control each of the following views from the [Tutorial](tutorial/index):
|
||||
|
||||
* The app root with the navigation links.
|
||||
* The list of heroes.
|
||||
* The hero editor.
|
||||
|
||||
You define a component's application logic—what it does to support the view—inside a class. The class interacts with the view through an API of properties and methods.
|
||||
|
||||
For example, the `HeroListComponent` has a `heroes` property that returns an array of heroes that it acquires from a service. `HeroListComponent` also has a `selectHero()` method that sets a `selectedHero` property when the user clicks to choose a hero from that list.
|
||||
|
||||
<code-example path="architecture/src/app/hero-list.component.ts" linenums="false" title="src/app/hero-list.component.ts (class)" region="class"></code-example>
|
||||
|
||||
Angular creates, updates, and destroys components as the user moves through the application. Your app can take action at each moment in this lifecycle through optional [lifecycle hooks](guide/lifecycle-hooks), like `ngOnInit()`.
|
||||
|
||||
<hr/>
|
||||
|
||||
## Component metadata
|
||||
|
||||
<img src="generated/images/guide/architecture/metadata.png" alt="Metadata" class="left">
|
||||
|
||||
The `@Component` decorator identifies the class immediately below it as a component class, and specifies its metadata. In the example code below, you can see that `HeroListComponent` is just a class, with no special Angular notation or syntax at all. It's not a component until mark it as one with the `@Component` decorator.
|
||||
|
||||
The metadata for a component tells Angular where to get the major building blocks it needs to create and present the component and its view. In particular, it associates a _template_ with the component, either directly with inline code, or by reference. Together, the component and its template describe a _view_.
|
||||
|
||||
In addition to containing or pointing to the template, the `@Component` metadata configures, for example, how the component can be referenced in HTML and what services it requires.
|
||||
|
||||
Here's an example of basic metadata for `HeroListComponent`:
|
||||
|
||||
<code-example path="architecture/src/app/hero-list.component.ts" linenums="false" title="src/app/hero-list.component.ts (metadata)" region="metadata"></code-example>
|
||||
|
||||
This example shows some of the most useful `@Component` configuration options:
|
||||
|
||||
* `selector`: A CSS selector that tells Angular to create and insert an instance of this component wherever it finds the corresponding tag in template HTML. For example, if an app's HTML contains `<app-hero-list></app-hero-list>`, then
|
||||
Angular inserts an instance of the `HeroListComponent` view between those tags.
|
||||
|
||||
* `templateUrl`: The module-relative address of this component's HTML template. Alternatively, you can provide the HTML template inline, as the value of the `template` property. This template defines the component's _host view_.
|
||||
|
||||
* `providers`: An array of **dependency injection providers** for services that the component requires. In the example, this tells Angular that the component's constructor requires a `HeroService` instance
|
||||
in order to get the list of heroes to display.
|
||||
|
||||
<hr/>
|
||||
|
||||
## Templates and views
|
||||
|
||||
<img src="generated/images/guide/architecture/template.png" alt="Template" class="left">
|
||||
|
||||
You define a component's view with its companion template. A template is a form of HTML that tells Angular how to render the component.
|
||||
|
||||
Views are typically arranged hierarchically, allowing you to modify or show and hide entire UI sections or pages as a unit. The template immediately associated with a component defines that component's _host view_. The component can also define a _view hierarchy_, which contains _embedded views_, hosted by other components.
|
||||
|
||||
<figure>
|
||||
<img src="generated/images/guide/architecture/component-tree.png" alt="Component tree" class="left">
|
||||
</figure>
|
||||
|
||||
A view hierarchy can include views from components in the same NgModule, but it also can (and often does) include views from components that are defined in different NgModules.
|
||||
|
||||
## Template syntax
|
||||
|
||||
A template looks like regular HTML, except that it also contains Angular [template syntax](guide/template-syntax), which alters the HTML based on your app's logic and the state of app and DOM data. Your template can use _data binding_ to coordinate the app and DOM data, _pipes_ to transform data before it is displayed, and _directives_ to apply app logic to what gets displayed.
|
||||
|
||||
For example, here is a template for the Tutorial's `HeroListComponent`:
|
||||
|
||||
<code-example path="architecture/src/app/hero-list.component.html" title="src/app/hero-list.component.html"></code-example>
|
||||
|
||||
This template uses typical HTML elements like `<h2>` and `<p>`, and also includes Angular template-syntax elements, `*ngFor`, `{{hero.name}}`, `(click)`, `[hero]`, and `<app-hero-detail>`. The template-syntax elements tell Angular how to render the HTML to the screen, using program logic and data.
|
||||
|
||||
* The `*ngFor` directive tells Angular to iterate over a list.
|
||||
* The `{{hero.name}}`, `(click)`, and `[hero]` bind program data to and from the DOM, responding to user input. See more about [data binding](#data-binding) below.
|
||||
* The `<app-hero-detail>` tag in the example is an element that represents a new component, `HeroDetailComponent`. The `HeroDetailComponent` (code not shown) is a child component of the `HeroListComponent` that defines the Hero-detail view. Notice how custom components like this mix seamlessly with native HTML in the same layouts.
|
||||
|
||||
### Data binding
|
||||
|
||||
Without a framework, you would be responsible for pushing data values into the HTML controls and turning user responses into actions and value updates. Writing such push/pull logic by hand is tedious, error-prone, and a nightmare to read, as any experienced jQuery programmer can attest.
|
||||
|
||||
Angular supports *two-way data binding*, a mechanism for coordinating parts of a template with parts of a component. Add binding markup to the template HTML to tell Angular how to connect both sides.
|
||||
|
||||
The following diagram shows the four forms of data binding markup. Each form has a direction—to the DOM, from the DOM, or in both directions.
|
||||
|
||||
<figure>
|
||||
<img src="generated/images/guide/architecture/databinding.png" alt="Data Binding" class="left">
|
||||
</figure>
|
||||
|
||||
This example from the `HeroListComponent` template uses three of these forms:
|
||||
|
||||
<code-example path="architecture/src/app/hero-list.component.1.html" linenums="false" title="src/app/hero-list.component.html (binding)" region="binding"></code-example>
|
||||
|
||||
* The `{{hero.name}}` [*interpolation*](guide/displaying-data#interpolation)
|
||||
displays the component's `hero.name` property value within the `<li>` element.
|
||||
|
||||
* The `[hero]` [*property binding*](guide/template-syntax#property-binding) passes the value of `selectedHero` from
|
||||
the parent `HeroListComponent` to the `hero` property of the child `HeroDetailComponent`.
|
||||
|
||||
* The `(click)` [*event binding*](guide/user-input#binding-to-user-input-events) calls the component's `selectHero` method when the user clicks a hero's name.
|
||||
|
||||
**Two-way data binding** is an important fourth form that combines property and event binding in a single notation. Here's an example from the `HeroDetailComponent` template that uses two-way data binding with the `ngModel` directive:
|
||||
|
||||
<code-example path="architecture/src/app/hero-detail.component.html" linenums="false" title="src/app/hero-detail.component.html (ngModel)" region="ngModel"></code-example>
|
||||
|
||||
In two-way binding, a data property value flows to the input box from the component as with property binding.
|
||||
The user's changes also flow back to the component, resetting the property to the latest value,
|
||||
as with event binding.
|
||||
|
||||
Angular processes *all* data bindings once per JavaScript event cycle,
|
||||
from the root of the application component tree through all child components.
|
||||
|
||||
<figure>
|
||||
<img src="generated/images/guide/architecture/component-databinding.png" alt="Data Binding" class="left">
|
||||
</figure>
|
||||
|
||||
Data binding plays an important role in communication between a template and its component, and is also important for communication between parent and child components.
|
||||
|
||||
<figure>
|
||||
<img src="generated/images/guide/architecture/parent-child-binding.png" alt="Parent/Child binding" class="left">
|
||||
</figure>
|
||||
|
||||
### Pipes
|
||||
|
||||
Angular pipes let you declare display-value transformations in your template HTML. A class with the `@Pipe` decorator defines a function that transforms input values to output values for display in a view.
|
||||
|
||||
Angular defines various pipes, such as the [date](https://angular.io/api/common/DatePipe) pipe and [currency](https://angular.io/api/common/CurrencyPipe) pipe; for a complete list, see the [Pipes API list](https://angular.io/api?type=pipe). You can also define new pipes.
|
||||
|
||||
To specify a value transformation in an HTML template, use the [pipe operator (|)](https://angular.io/guide/template-syntax#pipe):
|
||||
|
||||
`{{interpolated_value | pipe_name}}`
|
||||
|
||||
You can chain pipes, sending the output of one pipe function to be transformed by another pipe function. A pipe can also take arguments that control how it performs its transformation. For example, you can pass the desired format to the `date` pipe:
|
||||
|
||||
```
|
||||
<!-- Default format: output 'Jun 15, 2015'-->
|
||||
<p>Today is {{today | date}}</p>
|
||||
|
||||
<!-- fullDate format: output 'Monday, June 15, 2015'-->
|
||||
<p>The date is {{today | date:'fullDate'}}</p>
|
||||
|
||||
<!-- shortTime format: output '9:43 AM'-->
|
||||
<p>The time is {{today | date:'shortTime'}}</p>
|
||||
```
|
||||
|
||||
<hr/>
|
||||
|
||||
### Directives
|
||||
|
||||
<img src="generated/images/guide/architecture/directive.png" alt="Directives" class="left">
|
||||
|
||||
Angular templates are *dynamic*. When Angular renders them, it transforms the DOM according to the instructions given by *directives*. A directive is a class with a `@Directive` decorator.
|
||||
|
||||
A component is technically a directive - but components are so distinctive and central to Angular applications that Angular defines the `@Component` decorator, which extends the `@Directive` decorator with template-oriented features.
|
||||
|
||||
There are two kinds of directives besides components: _structural_ and _attribute_ directives. Just as for components, the metadata for a directive associates the class with a `selector` that you use to insert it into HTML. In templates, directives typically appear within an element tag as attributes, either by name or as the target of an assignment or a binding.
|
||||
|
||||
#### Structural directives
|
||||
|
||||
Structural directives alter layout by adding, removing, and replacing elements in DOM. The example template uses two built-in structural directives to add application logic to how the view is rendered:
|
||||
|
||||
<code-example path="architecture/src/app/hero-list.component.1.html" linenums="false" title="src/app/hero-list.component.html (structural)" region="structural"></code-example>
|
||||
|
||||
* [`*ngFor`](guide/displaying-data#ngFor) is an iterative; it tells Angular to stamp out one `<li>` per hero in the `heroes` list.
|
||||
* [`*ngIf`](guide/displaying-data#ngIf) is a conditional; it includes the `HeroDetail` component only if a selected hero exists.
|
||||
|
||||
#### Attribute directives
|
||||
|
||||
Attribute directives alter the appearance or behavior of an existing element.
|
||||
In templates they look like regular HTML attributes, hence the name.
|
||||
|
||||
The `ngModel` directive, which implements two-way data binding, is an example of an attribute directive. `ngModel` modifies the behavior of an existing element (typically an `<input>`) by setting its display value property and responding to change events.
|
||||
|
||||
<code-example path="architecture/src/app/hero-detail.component.html" linenums="false" title="src/app/hero-detail.component.html (ngModel)" region="ngModel"></code-example>
|
||||
|
||||
Angular has more pre-defined directives that either alter the layout structure
|
||||
(for example, [ngSwitch](guide/template-syntax#ngSwitch))
|
||||
or modify aspects of DOM elements and components
|
||||
(for example, [ngStyle](guide/template-syntax#ngStyle) and [ngClass](guide/template-syntax#ngClass)).
|
||||
|
||||
You can also write your own directives. Components such as `HeroListComponent` are one kind of custom directive. You can also create custom structural and attribute directives.
|
||||
|
||||
<!-- PENDING: link to where to learn more about other kinds! -->
|
107
aio/content/guide/architecture-modules.md
Normal file
107
aio/content/guide/architecture-modules.md
Normal file
@ -0,0 +1,107 @@
|
||||
# Introduction to modules
|
||||
|
||||
<img src="generated/images/guide/architecture/module.png" alt="Module" class="left">
|
||||
|
||||
Angular apps are modular and Angular has its own modularity system called _NgModules_. An NgModule is a container for a cohesive block of code dedicated to an application domain, a workflow, or a closely related set of capabilities. It can contain components, service providers, and other code files whose scope is defined by the containing NgModule. It can import functionality that is exported from other NgModules, and export selected functionality for use by other NgModules.
|
||||
|
||||
Every Angular app has at least one NgModule class, [the _root module_](guide/bootstrapping), which is conventionally named `AppModule` and resides in a file named `app.module.ts`. You launch your app by *bootstrapping* the root NgModule.
|
||||
|
||||
While a small application might have only one NgModule, most apps have many more _feature modules_. The _root_ NgModule for an app is so named because it can include child NgModules in a hierarchy of any depth.
|
||||
|
||||
## NgModule metadata
|
||||
|
||||
An NgModule is defined as a class decorated with `@NgModule`. The `@NgModule` decorator is a function that takes a single metadata object, whose properties describe the module. The most important properties are as follows.
|
||||
|
||||
* `declarations`—The [components](guide/architecture-components), _directives_, and _pipes_ that belong to this NgModule.
|
||||
|
||||
* `exports`—The subset of declarations that should be visible and usable in the _component templates_ of other NgModules.
|
||||
|
||||
* `imports`—Other modules whose exported classes are needed by component templates declared in _this_ NgModule.
|
||||
|
||||
* `providers`—Creators of [services](guide/architecture-services) that this NgModule contributes to the global collection of services; they become accessible in all parts of the app. (You can also specify providers at the component level, which is often preferred.)
|
||||
|
||||
* `bootstrap`—The main application view, called the _root component_, which hosts all other app views. Only the _root NgModule_ should set this `bootstrap` property.
|
||||
|
||||
Here's a simple root NgModule definition:
|
||||
|
||||
<code-example path="architecture/src/app/mini-app.ts" region="module" title="src/app/app.module.ts" linenums="false"></code-example>
|
||||
|
||||
<div class="l-sub-section">
|
||||
|
||||
The `export` of `AppComponent` is just to show how to export; it isn't actually necessary in this example. A root NgModule has no reason to _export_ anything because other modules don't need to _import_ the root NgModule.
|
||||
|
||||
</div>
|
||||
|
||||
## NgModules and components
|
||||
|
||||
NgModules provide a _compilation context_ for their components. A root NgModule always has a root component that is created during bootstrap, but any NgModule can include any number of additional components, which can be loaded through the router or created through the template. The components that belong to an NgModule share a compilation context.
|
||||
|
||||
<figure>
|
||||
|
||||
<img src="generated/images/guide/architecture/compilation-context.png" alt="Component compilation context" class="left">
|
||||
|
||||
</figure>
|
||||
|
||||
<br class="clear">
|
||||
|
||||
A component and its template together define a _view_. A component can contain a _view hierarchy_, which allows you to define arbitrarily complex areas of the screen that can be created, modified, and destroyed as a unit. A view hierarchy can mix views defined in components that belong to different NgModules. This is often the case, especially for UI libraries.
|
||||
|
||||
<figure>
|
||||
|
||||
<img src="generated/images/guide/architecture/view-hierarchy.png" alt="View hierarchy" class="left">
|
||||
|
||||
</figure>
|
||||
|
||||
<br class="clear">
|
||||
|
||||
When you create a component, it is associated directly with a single view, called the _host view_. The host view can be the root of a view hierarchy, which can contain _embedded views_, which are in turn the host views of other components. Those components can be in the same NgModule, or can be imported from other NgModules. Views in the tree can be nested to any depth.
|
||||
|
||||
<div class="l-sub-section">
|
||||
The hierarchical structure of views is a key factor in the way Angular detects and responds to changes in the DOM and app data.
|
||||
</div>
|
||||
|
||||
## NgModules and JavaScript modules
|
||||
|
||||
The NgModule system is different from and unrelated to the JavaScript (ES2015) module system for managing collections of JavaScript objects. These are two different and _complementary_ module systems. You can use them both to write your apps.
|
||||
|
||||
In JavaScript each _file_ is a module and all objects defined in the file belong to that module.
|
||||
The module declares some objects to be public by marking them with the `export` key word.
|
||||
Other JavaScript modules use *import statements* to access public objects from other modules.
|
||||
|
||||
<code-example path="architecture/src/app/app.module.ts" region="imports" linenums="false"></code-example>
|
||||
|
||||
<code-example path="architecture/src/app/app.module.ts" region="export" linenums="false"></code-example>
|
||||
|
||||
<div class="l-sub-section">
|
||||
<a href="http://exploringjs.com/es6/ch_modules.html">Learn more about the JavaScript module system on the web.</a>
|
||||
</div>
|
||||
|
||||
## Angular libraries
|
||||
|
||||
<img src="generated/images/guide/architecture/library-module.png" alt="Component" class="left">
|
||||
|
||||
Angular ships as a collection of JavaScript modules. You can think of them as library modules. Each Angular library name begins with the `@angular` prefix. Install them with the `npm` package manager and import parts of them with JavaScript `import` statements.
|
||||
|
||||
<br class="clear">
|
||||
|
||||
For example, import Angular's `Component` decorator from the `@angular/core` library like this:
|
||||
|
||||
<code-example path="architecture/src/app/app.component.ts" region="import" linenums="false"></code-example>
|
||||
|
||||
You also import NgModules from Angular _libraries_ using JavaScript import statements:
|
||||
|
||||
<code-example path="architecture/src/app/mini-app.ts" region="import-browser-module" linenums="false"></code-example>
|
||||
|
||||
In the example of the simple root module above, the application module needs material from within the `BrowserModule`. To access that material, add it to the `@NgModule` metadata `imports` like this.
|
||||
|
||||
<code-example path="architecture/src/app/mini-app.ts" region="ngmodule-imports" linenums="false"></code-example>
|
||||
|
||||
In this way you're using both the Angular and JavaScript module systems _together_. Although it's easy to confuse the two systems, which share the common vocabulary of "imports" and "exports", you will become familiar with the different contexts in which they are used.
|
||||
|
||||
<div class="l-sub-section">
|
||||
|
||||
Learn more from the [NgModules](guide/ngmodules) page.
|
||||
|
||||
</div>
|
||||
|
||||
<hr/>
|
48
aio/content/guide/architecture-next-steps.md
Normal file
48
aio/content/guide/architecture-next-steps.md
Normal file
@ -0,0 +1,48 @@
|
||||
# Next steps: tools and techniques
|
||||
|
||||
Once you have understood the basic building blocks, you can begin to learn more about the features and tools that are available to help you develop and deliver Angular applications. Angular provides a lot more features and services that are covered in this documentation.
|
||||
|
||||
#### Responsive programming tools
|
||||
|
||||
* [Lifecycle hooks](guide/lifecycle-hooks): Tap into key moments in the lifetime of a component, from its creation to its destruction, by implementing the lifecycle hook interfaces.
|
||||
|
||||
* [Observables and event processing](guide/observables): How to use observables with components and services to publish and subscribe to messages of any type, such as user-interaction events and asynchronous operation results.
|
||||
|
||||
#### Client-server interaction tools
|
||||
|
||||
* [HTTP](guide/http): Communicate with a server to get data, save data, and invoke server-side actions with an HTTP client.
|
||||
|
||||
* [Server-side Rendering](guide/universal): Angular Universal generates static application pages on the server through server-side rendering (SSR). This allows you to run your Angular app on the server in order to improve performance and show the first page quickly on mobile and low-powered devices, and also facilitate web crawlers.
|
||||
|
||||
* [Service Workers](guide/service-worker-intro): A service worker is a script that runs in the web browser and manages caching for an application. Service workers function as a network proxy. They intercept outgoing HTTP requests and can, for example, deliver a cached response if one is available. You can significantly improve the user experience by using a service worker to reduce dependency on the network.
|
||||
|
||||
#### Domain-specific libraries
|
||||
|
||||
* [Animations](guide/animations): Animate component behavior
|
||||
without deep knowledge of animation techniques or CSS with Angular's animation library.
|
||||
|
||||
* [Forms](guide/forms): Support complex data entry scenarios with HTML-based validation and dirty checking.
|
||||
|
||||
#### Support for the development cycle
|
||||
|
||||
* [Testing Platform](guide/testing): Run unit tests on your application parts as they interact with the Angular framework.
|
||||
|
||||
* [Internationalization](guide/i18n): Angular's internationalization (i18n) tools can help you make your app available in multiple languages.
|
||||
|
||||
* [Compilation](guide/aot-compiler): Angular provides just-in-time (JIT) compilation for the development environment, and ahead-of-time (AOT) compilation for the production environment.
|
||||
|
||||
* [Security guidelines](guide/security): Learn about Angular's built-in protections against common web-app vulnerabilities and attacks such as cross-site scripting attacks.
|
||||
|
||||
#### Setup and deployment tools
|
||||
|
||||
* [Setup for local development](guide/setup): Learn how to set up a new project for development with QuickStart.
|
||||
|
||||
* [Installation](guide/npm-packages): The [Angular CLI](https://cli.angular.io/), Angular applications, and Angular itself depend on features and functionality provided by libraries that are available as [npm](https://docs.npmjs.com/) packages.
|
||||
|
||||
* [Typescript Configuration](guide/typescript-configuration): TypeScript is the primary language for Angular application development.
|
||||
|
||||
* [Browser support](guide/browser-support): Learn how to make your apps compatible across a wide range of browsers.
|
||||
|
||||
* [Deployment](guide/deployment): Learn techniques for deploying your Angular application to a remote server.
|
||||
|
||||
<hr/>
|
76
aio/content/guide/architecture-services.md
Normal file
76
aio/content/guide/architecture-services.md
Normal file
@ -0,0 +1,76 @@
|
||||
# Introduction to services and dependency injection
|
||||
|
||||
<img src="generated/images/guide/architecture/service.png" alt="Service" class="left">
|
||||
|
||||
_Service_ is a broad category encompassing any value, function, or feature that an app needs. A service is typically a class with a narrow, well-defined purpose. It should do something specific and do it well.
|
||||
<br class="clear">
|
||||
|
||||
Angular distinguishes components from services in order to increase modularity and reusability.
|
||||
|
||||
* By separating a component's view-related functionality from other kinds of processing, you can make your component classes lean and efficient. Ideally, a component's job is to enable the user experience and nothing more. It should present properties and methods for data binding, in order to mediate between the view (rendered by the template) and the application logic (which often includes some notion of a _model_).
|
||||
|
||||
* A component should not need to define things like how to fetch data from the server, validate user input, or log directly to the console. Instead, it can delegate such tasks to services. By defining that kind of processing task in an injectable service class, you make it available to any component. You can also make your app more adaptable by injecting different providers of the same kind of service, as appropriate in different circumstances.
|
||||
|
||||
Angular doesn't *enforce* these principles. Angular does help you *follow* these principles by making it easy to factor your
|
||||
application logic into services and make those services available to components through *dependency injection*.
|
||||
|
||||
## Service examples
|
||||
|
||||
Here's an example of a service class that logs to the browser console:
|
||||
|
||||
<code-example path="architecture/src/app/logger.service.ts" linenums="false" title="src/app/logger.service.ts (class)" region="class"></code-example>
|
||||
|
||||
Services can depend on other services. For example, here's a `HeroService` that depends on the `Logger` service, and also uses `BackendService` to get heroes. That service in turn might depend on the `HttpClient` service to fetch heroes asynchronously from a server.
|
||||
|
||||
<code-example path="architecture/src/app/hero.service.ts" linenums="false" title="src/app/hero.service.ts (class)" region="class"></code-example>
|
||||
|
||||
<hr/>
|
||||
|
||||
## Dependency injection
|
||||
|
||||
<img src="generated/images/guide/architecture/dependency-injection.png" alt="Service" class="left">
|
||||
|
||||
Components consume services; that is, you can *inject* a service into a component, giving the component access to that service class.
|
||||
|
||||
To define a class as a service in Angular, use the `@Injectable` decorator to provide the metadata that allows Angular to inject it into a component as a *dependency*.
|
||||
|
||||
Similarly, use the `@Injectable` decorator to indicate that a component or other class (such as another service, a pipe, or an NgModule) _has_ a dependency. A dependency doesn't have to be a service—it could be a function, for example, or a value.
|
||||
|
||||
*Dependency injection* (often called DI) is wired into the Angular framework and used everywhere to provide new components with the services or other things they need.
|
||||
|
||||
* The *injector* is the main mechanism. You don't have to create an Angular injector. Angular creates an application-wide injector for you during the bootstrap process.
|
||||
|
||||
* The injector maintains a *container* of dependency instances that it has already created, and reuses them if possible.
|
||||
|
||||
* A *provider* is a recipe for creating a dependency. For a service, this is typically the service class itself. For any dependency you need in your app, you must register a provider with the app's injector, so that the injector can use it to create new instances.
|
||||
|
||||
When Angular creates a new instance of a component class, it determines which services or other dependencies that component needs by looking at the types of its constructor parameters. For example, the constructor of `HeroListComponent` needs a `HeroService`:
|
||||
|
||||
<code-example path="architecture/src/app/hero-list.component.ts" linenums="false" title="src/app/hero-list.component.ts (constructor)" region="ctor"></code-example>
|
||||
|
||||
When Angular discovers that a component depends on a service, it first checks if the injector already has any existing instances of that service. If a requested service instance does not yet exist, the injector makes one using the registered provider, and adds it to the injector before returning the service to Angular.
|
||||
|
||||
When all requested services have been resolved and returned, Angular can call the component's constructor with those services as arguments.
|
||||
|
||||
The process of `HeroService` injection looks something like this:
|
||||
|
||||
<figure>
|
||||
<img src="generated/images/guide/architecture/injector-injects.png" alt="Service" class="left">
|
||||
</figure>
|
||||
|
||||
### Providing services
|
||||
|
||||
You must register at least one *provider* of any service you are going to use. You can register providers in modules or in components.
|
||||
|
||||
* When you add providers to the [root module](guide/architecture-modules), the same instance of a service is available to all components in your app.
|
||||
|
||||
<code-example path="architecture/src/app/app.module.ts" linenums="false" title="src/app/app.module.ts (module providers)" region="providers"></code-example>
|
||||
|
||||
* When you register a provider at the component level, you get a new instance of the
|
||||
service with each new instance of that component. At the component level, register a service provider in the `providers` property of the `@Component` metadata:
|
||||
|
||||
<code-example path="architecture/src/app/hero-list.component.ts" linenums="false" title="src/app/hero-list.component.ts (component providers)" region="providers"></code-example>
|
||||
|
||||
For more detailed information, see the [Dependency Injection](guide/dependency-injection) section.
|
||||
|
||||
<hr/>
|
@ -1,533 +1,137 @@
|
||||
# Architecture Overview
|
||||
# Architecture overview
|
||||
|
||||
Angular is a framework for building client applications in HTML and
|
||||
either JavaScript or a language like TypeScript that compiles to JavaScript.
|
||||
Angular is a platform and framework for building client applications in HTML and TypeScript.
|
||||
Angular is itself written in TypeScript. It implements core and optional functionality as a set of TypeScript libraries that you import into your apps.
|
||||
|
||||
The framework consists of several libraries, some of them core and some optional.
|
||||
The basic building blocks of an Angular application are _NgModules_, which provide a compilation context for _components_. NgModules collect related code into functional sets; an Angular app is defined by a set of NgModules. An app always has at least a _root module_ that enables bootstrapping, and typically has many more _feature modules_.
|
||||
|
||||
You write Angular applications by composing HTML *templates* with Angularized markup,
|
||||
writing *component* classes to manage those templates, adding application logic in *services*,
|
||||
and boxing components and services in *modules*.
|
||||
* Components define *views*, which are sets of screen elements that Angular can choose among and modify according to your program logic and data. Every app has at least a root component.
|
||||
|
||||
Then you launch the app by *bootstrapping* the _root module_.
|
||||
Angular takes over, presenting your application content in a browser and
|
||||
responding to user interactions according to the instructions you've provided.
|
||||
* Components use *services*, which provide specific functionality not directly related to views. Service providers can be *injected* into components as *dependencies*, making your code modular, reusable, and efficient.
|
||||
|
||||
Of course, there is more to it than this.
|
||||
You'll learn the details in the pages that follow. For now, focus on the big picture.
|
||||
Both components and services are simply classes, with *decorators* that mark their type and provide metadata that tells Angular how to use them.
|
||||
|
||||
* The metadata for a component class associates it with a *template* that defines a view. A template combines ordinary HTML with Angular *directives* and *binding markup* that allow Angular to modify the HTML before rendering it for display.
|
||||
|
||||
* The metadata for a service class provides the information Angular needs to make it available to components through *Dependency Injection (DI)*.
|
||||
|
||||
An app's components typically define many views, arranged hierarchically. Angular provides the `Router` service to help you define navigation paths among views. The router provides sophisticated in-browser navigational capabilities.
|
||||
|
||||
## Modules
|
||||
|
||||
Angular defines the `NgModule`, which differs from and complements the JavaScript (ES2015) module. An NgModule declares a compilation context for a set of components that is dedicated to an application domain, a workflow, or a closely related set of capabilities. An NgModule can associate its components with related code, such as services, to form functional units.
|
||||
|
||||
Every Angular app has a _root module_, conventionally named `AppModule`, which provides the bootstrap mechanism that launches the application. An app typically contains many functional modules.
|
||||
|
||||
Like JavaScript modules, NgModules can import functionality from other NgModules, and allow their own functionality to be exported and used by other NgModules. For example, to use the router service in your app, you import the `Router` NgModule.
|
||||
|
||||
Organizing your code into distinct functional modules helps in managing development of complex applications, and in designing for reusability. In addition, this technique lets you take advantage of _lazy-loading_—that is, loading modules on demand—in order to minimize the amount of code that needs to be loaded at startup.
|
||||
|
||||
<div class="l-sub-section">
|
||||
|
||||
For a more detailed discussion, see [Introduction to modules](guide/architecture-modules).
|
||||
|
||||
</div>
|
||||
|
||||
## Components
|
||||
|
||||
Every Angular application has at least one component, the *root component* that connects a component hierarchy with the page DOM. Each component defines a class that contains application data and logic, and is associated with an HTML *template* that defines a view to be displayed in a target environment.
|
||||
|
||||
The `@Component` decorator identifies the class immediately below it as a component, and provides the template and related component-specific metadata.
|
||||
|
||||
<div class="l-sub-section">
|
||||
|
||||
Decorators are functions that modify JavaScript classes. Angular defines a number of such decorators that attach specific kinds of metadata to classes, so that it knows what those classes mean and how they should work.
|
||||
|
||||
<a href="https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841#.x5c2ndtx0">Learn more about decorators on the web.</a>
|
||||
|
||||
</div>
|
||||
|
||||
### Templates, directives, and data binding
|
||||
|
||||
A template combines HTML with Angular markup that can modify the HTML elements before they are displayed.
|
||||
Template *directives* provide program logic, and *binding markup* connects your application data and the document object model (DOM).
|
||||
|
||||
* *Event binding* lets your app respond to user input in the target environment by updating your application data.
|
||||
* *Property binding* lets you interpolate values that are computed from your application data into the HTML.
|
||||
|
||||
Before a view is displayed, Angular evaluates the directives and resolves the binding syntax in the template to modify the HTML elements and the DOM, according to your program data and logic. Angular supports *two-way data binding*, meaning that changes in the DOM, such as user choices, can also be reflected back into your program data.
|
||||
|
||||
Your templates can also use *pipes* to improve the user experience by transforming values for display. Use pipes to display, for example, dates and currency values in a way appropriate to the user's locale. Angular provides predefined pipes for common transformations, and you can also define your own.
|
||||
|
||||
<div class="l-sub-section">
|
||||
|
||||
For a more detailed discussion of these concepts, see [Introduction to components](guide/architecture-components).
|
||||
|
||||
</div>
|
||||
|
||||
{@a dependency-injection}
|
||||
|
||||
|
||||
## Services and dependency injection
|
||||
|
||||
For data or logic that is not associated with a specific view, and that you want to share across components, you create a *service* class. A service class definition is immediately preceded by the `@Injectable` decorator. The decorator provides the metadata that allows your service to be *injected* into client components as a dependency.
|
||||
|
||||
*Dependency injection* (or DI) lets you keep your component classes lean and efficient. They don't fetch data from the server, validate user input, or log directly to the console; they delegate such tasks to services.
|
||||
|
||||
<div class="l-sub-section">
|
||||
|
||||
For a more detailed discusssion, see [Introduction to services and DI](guide/architecture-services).
|
||||
|
||||
</div>
|
||||
|
||||
### Routing
|
||||
|
||||
The Angular `Router` NgModule provides a service that lets you define a navigation path among the different application states and view hierarchies in your app. It is modeled on the familiar browser navigation conventions:
|
||||
|
||||
* Enter a URL in the address bar and the browser navigates to a corresponding page.
|
||||
* Click links on the page and the browser navigates to a new page.
|
||||
* Click the browser's back and forward buttons and the browser navigates backward and forward through the history of pages you've seen.
|
||||
|
||||
The router maps URL-like paths to views instead of pages. When a user performs an action, such as clicking a link, that would load a new page in the browser, the router intercepts the browser's behavior, and shows or hides view hierarchies.
|
||||
|
||||
If the router determines that the current application state requires particular functionality, and the module that defines it has not been loaded, the router can _lazy-load_ the module on demand.
|
||||
|
||||
The router interprets a link URL according to your app's view navigation rules and data state. You can navigate to new views when the user clicks a button, selects from a drop box, or in response to some other stimulus from any source. The Router logs activity in the browser's history journal, so the back and forward buttons work as well.
|
||||
|
||||
To define navigation rules, you associate *navigation paths* with your components. A path uses a URL-like syntax that integrates your program data, in much the same way that template syntax integrates your views with your program data. You can then apply program logic to choose which views to show or to hide, in response to user input and your own access rules.
|
||||
|
||||
<div class="l-sub-section">
|
||||
|
||||
For a more detailed discussion, see [Routing and navigation](guide/router).
|
||||
|
||||
</div>
|
||||
|
||||
<hr/>
|
||||
|
||||
## What's next
|
||||
|
||||
You've learned the basics about the main building blocks of an Angular application. The following diagram shows how these basic pieces are related.
|
||||
|
||||
<figure>
|
||||
<img src="generated/images/guide/architecture/overview2.png" alt="overview">
|
||||
</figure>
|
||||
|
||||
<div class="l-sub-section">
|
||||
* Together, a component and template define an Angular view.
|
||||
* A decorator on a component class adds the metadata, including a pointer to the associated template.
|
||||
* Directives and binding markup in a component's template modify views based on program data and logic.
|
||||
* The dependency injector provides services to a component, such as the router service that lets you define navigation among views.
|
||||
|
||||
The code referenced on this page is available as a <live-example></live-example>.
|
||||
Each of these subjects is introduced in more detail in the following pages.
|
||||
|
||||
</div>
|
||||
|
||||
## Modules
|
||||
|
||||
<img src="generated/images/guide/architecture/module.png" alt="Component" class="left">
|
||||
|
||||
|
||||
Angular apps are modular and Angular has its own modularity system called _NgModules_.
|
||||
|
||||
NgModules are a big deal.
|
||||
This page introduces modules; the [NgModules](guide/ngmodules) pages
|
||||
relating to NgModules covers them in detail.
|
||||
|
||||
<br class="clear">
|
||||
|
||||
Every Angular app has at least one NgModule class, [the _root module_](guide/bootstrapping "Bootstrapping"),
|
||||
conventionally named `AppModule`.
|
||||
|
||||
While the _root module_ may be the only module in a small application, most apps have many more
|
||||
_feature modules_, each a cohesive block of code dedicated to an application domain,
|
||||
a workflow, or a closely related set of capabilities.
|
||||
|
||||
An NgModule, whether a _root_ or _feature_, is a class with an `@NgModule` decorator.
|
||||
* [Modules](guide/architecture-modules)
|
||||
* [Components](guide/architecture-components)
|
||||
* [Templates](guide/architecture-components#templates-and-views)
|
||||
* [Metadata](guide/architecture-components#component-metadata)
|
||||
* [Data binding](guide/architecture-components#data-binding)
|
||||
* [Directives](guide/architecture-components#directives)
|
||||
* [Pipes](guide/architecture-components#pipes)
|
||||
* [Services and dependency injection](guide/architecture-services)
|
||||
|
||||
<div class="l-sub-section">
|
||||
|
||||
Decorators are functions that modify JavaScript classes.
|
||||
Angular has many decorators that attach metadata to classes so that it knows
|
||||
what those classes mean and how they should work.
|
||||
<a href="https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841#.x5c2ndtx0">
|
||||
Learn more</a> about decorators on the web.
|
||||
|
||||
Note that the code referenced on these pages is available as a <live-example></live-example>.
|
||||
</div>
|
||||
|
||||
`NgModule` is a decorator function that takes a single metadata object whose properties describe the module.
|
||||
The most important properties are:
|
||||
* `declarations` - the _view classes_ that belong to this module.
|
||||
Angular has three kinds of view classes: [components](guide/architecture#components), [directives](guide/architecture#directives), and [pipes](guide/pipes).
|
||||
|
||||
* `exports` - the subset of declarations that should be visible and usable in the component [templates](guide/architecture#templates) of other modules.
|
||||
|
||||
* `imports` - other modules whose exported classes are needed by component templates declared in _this_ module.
|
||||
|
||||
* `providers` - creators of [services](guide/architecture#services) that this module contributes to
|
||||
the global collection of services; they become accessible in all parts of the app.
|
||||
|
||||
* `bootstrap` - the main application view, called the _root component_,
|
||||
that hosts all other app views. Only the _root module_ should set this `bootstrap` property.
|
||||
|
||||
Here's a simple root module:
|
||||
|
||||
<code-example path="architecture/src/app/mini-app.ts" region="module" title="src/app/app.module.ts" linenums="false"></code-example>
|
||||
|
||||
<div class="l-sub-section">
|
||||
|
||||
The `export` of `AppComponent` is just to show how to use the `exports` array to export a component; it isn't actually necessary in this example. A root module has no reason to _export_ anything because other components don't need to _import_ the root module.
|
||||
|
||||
When you are familiar with these fundamental building blocks, you can explore them in more detail in the documentation. To learn about more tools and techniques that are available to help you build and deploy Angular applications, see [Next steps](guide/architecture-next-steps).
|
||||
</div>
|
||||
|
||||
Launch an application by _bootstrapping_ its root module.
|
||||
During development you're likely to bootstrap the `AppModule` in a `main.ts` file like this one.
|
||||
|
||||
<code-example path="architecture/src/main.ts" title="src/main.ts" linenums="false"></code-example>
|
||||
|
||||
### NgModules vs. JavaScript modules
|
||||
|
||||
The NgModule — a class decorated with `@NgModule` — is a fundamental feature of Angular.
|
||||
|
||||
JavaScript also has its own module system for managing collections of JavaScript objects.
|
||||
It's completely different and unrelated to the NgModule system.
|
||||
|
||||
In JavaScript each _file_ is a module and all objects defined in the file belong to that module.
|
||||
The module declares some objects to be public by marking them with the `export` key word.
|
||||
Other JavaScript modules use *import statements* to access public objects from other modules.
|
||||
|
||||
<code-example path="architecture/src/app/app.module.ts" region="imports" linenums="false"></code-example>
|
||||
|
||||
<code-example path="architecture/src/app/app.module.ts" region="export" linenums="false"></code-example>
|
||||
|
||||
<div class="l-sub-section">
|
||||
<a href="http://exploringjs.com/es6/ch_modules.html">Learn more about the JavaScript module system on the web.</a>
|
||||
</div>
|
||||
|
||||
These are two different and _complementary_ module systems. Use them both to write your apps.
|
||||
|
||||
### Angular libraries
|
||||
|
||||
<img src="generated/images/guide/architecture/library-module.png" alt="Component" class="left">
|
||||
|
||||
Angular ships as a collection of JavaScript modules. You can think of them as library modules.
|
||||
|
||||
Each Angular library name begins with the `@angular` prefix.
|
||||
|
||||
You install them with the **npm** package manager and import parts of them with JavaScript `import` statements.
|
||||
|
||||
<br class="clear">
|
||||
|
||||
For example, import Angular's `Component` decorator from the `@angular/core` library like this:
|
||||
|
||||
<code-example path="architecture/src/app/app.component.ts" region="import" linenums="false"></code-example>
|
||||
|
||||
You also import NgModules from Angular _libraries_ using JavaScript import statements:
|
||||
|
||||
<code-example path="architecture/src/app/mini-app.ts" region="import-browser-module" linenums="false"></code-example>
|
||||
|
||||
In the example of the simple root module above, the application module needs material from within that `BrowserModule`. To access that material, add it to the `@NgModule` metadata `imports` like this.
|
||||
|
||||
<code-example path="architecture/src/app/mini-app.ts" region="ngmodule-imports" linenums="false"></code-example>
|
||||
|
||||
In this way you're using both the Angular and JavaScript module systems _together_.
|
||||
|
||||
It's easy to confuse the two systems because they share the common vocabulary of "imports" and "exports".
|
||||
Hang in there. The confusion yields to clarity with time and experience.
|
||||
|
||||
<div class="l-sub-section">
|
||||
|
||||
Learn more from the [NgModules](guide/ngmodules) page.
|
||||
|
||||
</div>
|
||||
|
||||
<hr/>
|
||||
|
||||
## Components
|
||||
|
||||
<img src="generated/images/guide/architecture/hero-component.png" alt="Component" class="left">
|
||||
|
||||
A _component_ controls a patch of screen called a *view*.
|
||||
|
||||
For example, the following views are controlled by components:
|
||||
|
||||
* The app root with the navigation links.
|
||||
* The list of heroes.
|
||||
* The hero editor.
|
||||
|
||||
You define a component's application logic—what it does to support the view—inside a class.
|
||||
The class interacts with the view through an API of properties and methods.
|
||||
|
||||
{@a component-code}
|
||||
|
||||
For example, this `HeroListComponent` has a `heroes` property that returns an array of heroes
|
||||
that it acquires from a service.
|
||||
`HeroListComponent` also has a `selectHero()` method that sets a `selectedHero` property when the user clicks to choose a hero from that list.
|
||||
|
||||
<code-example path="architecture/src/app/hero-list.component.ts" linenums="false" title="src/app/hero-list.component.ts (class)" region="class"></code-example>
|
||||
|
||||
Angular creates, updates, and destroys components as the user moves through the application.
|
||||
Your app can take action at each moment in this lifecycle through optional [lifecycle hooks](guide/lifecycle-hooks), like `ngOnInit()` declared above.
|
||||
|
||||
<hr/>
|
||||
|
||||
## Templates
|
||||
|
||||
<img src="generated/images/guide/architecture/template.png" alt="Template" class="left">
|
||||
|
||||
You define a component's view with its companion **template**. A template is a form of HTML
|
||||
that tells Angular how to render the component.
|
||||
|
||||
A template looks like regular HTML, except for a few differences. Here is a
|
||||
template for our `HeroListComponent`:
|
||||
|
||||
<code-example path="architecture/src/app/hero-list.component.html" title="src/app/hero-list.component.html"></code-example>
|
||||
|
||||
Although this template uses typical HTML elements like `<h2>` and `<p>`, it also has some differences. Code like `*ngFor`, `{{hero.name}}`, `(click)`, `[hero]`, and `<app-hero-detail>` uses Angular's [template syntax](guide/template-syntax).
|
||||
|
||||
In the last line of the template, the `<app-hero-detail>` tag is a custom element that represents a new component, `HeroDetailComponent`.
|
||||
|
||||
The `HeroDetailComponent` is a *different* component than the `HeroListComponent` you've been reviewing.
|
||||
The `HeroDetailComponent` (code not shown) presents facts about a particular hero, the
|
||||
hero that the user selects from the list presented by the `HeroListComponent`.
|
||||
The `HeroDetailComponent` is a **child** of the `HeroListComponent`.
|
||||
|
||||
<img src="generated/images/guide/architecture/component-tree.png" alt="Metadata" class="left">
|
||||
|
||||
Notice how `<app-hero-detail>` rests comfortably among native HTML elements. Custom components mix seamlessly with native HTML in the same layouts.
|
||||
|
||||
<hr class="clear"/>
|
||||
|
||||
## Metadata
|
||||
|
||||
<img src="generated/images/guide/architecture/metadata.png" alt="Metadata" class="left">
|
||||
|
||||
Metadata tells Angular how to process a class.
|
||||
|
||||
<br class="clear">
|
||||
|
||||
[Looking back at the code](guide/architecture#component-code) for `HeroListComponent`, you can see that it's just a class.
|
||||
There is no evidence of a framework, no "Angular" in it at all.
|
||||
|
||||
In fact, `HeroListComponent` really is *just a class*. It's not a component until you *tell Angular about it*.
|
||||
|
||||
To tell Angular that `HeroListComponent` is a component, attach **metadata** to the class.
|
||||
|
||||
In TypeScript, you attach metadata by using a **decorator**.
|
||||
Here's some metadata for `HeroListComponent`:
|
||||
|
||||
<code-example path="architecture/src/app/hero-list.component.ts" linenums="false" title="src/app/hero-list.component.ts (metadata)" region="metadata"></code-example>
|
||||
|
||||
Here is the `@Component` decorator, which identifies the class
|
||||
immediately below it as a component class.
|
||||
|
||||
The `@Component` decorator takes a required configuration object with the
|
||||
information Angular needs to create and present the component and its view.
|
||||
|
||||
Here are a few of the most useful `@Component` configuration options:
|
||||
|
||||
* `selector`: CSS selector that tells Angular to create and insert an instance of this component
|
||||
where it finds a `<app-hero-list>` tag in *parent* HTML.
|
||||
For example, if an app's HTML contains `<app-hero-list></app-hero-list>`, then
|
||||
Angular inserts an instance of the `HeroListComponent` view between those tags.
|
||||
|
||||
* `templateUrl`: module-relative address of this component's HTML template, shown [above](guide/architecture#templates).
|
||||
|
||||
* `providers`: array of **dependency injection providers** for services that the component requires.
|
||||
This is one way to tell Angular that the component's constructor requires a `HeroService`
|
||||
so it can get the list of heroes to display.
|
||||
|
||||
<img src="generated/images/guide/architecture/template-metadata-component.png" alt="Metadata" class="left">
|
||||
|
||||
The metadata in the `@Component` tells Angular where to get the major building blocks you specify for the component.
|
||||
|
||||
The template, metadata, and component together describe a view.
|
||||
|
||||
Apply other metadata decorators in a similar fashion to guide Angular behavior.
|
||||
`@Injectable`, `@Input`, and `@Output` are a few of the more popular decorators.
|
||||
|
||||
<br class="clear">
|
||||
|
||||
The architectural takeaway is that you must add metadata to your code
|
||||
so that Angular knows what to do.
|
||||
|
||||
<hr/>
|
||||
|
||||
## Data binding
|
||||
|
||||
Without a framework, you would be responsible for pushing data values into the HTML controls and turning user responses
|
||||
into actions and value updates. Writing such push/pull logic by hand is tedious, error-prone, and a nightmare to
|
||||
read as any experienced jQuery programmer can attest.
|
||||
|
||||
<img src="generated/images/guide/architecture/databinding.png" alt="Data Binding" class="left">
|
||||
|
||||
Angular supports **data binding**,
|
||||
a mechanism for coordinating parts of a template with parts of a component.
|
||||
Add binding markup to the template HTML to tell Angular how to connect both sides.
|
||||
|
||||
As the diagram shows, there are four forms of data binding syntax. Each form has a direction — to the DOM, from the DOM, or in both directions.
|
||||
|
||||
<br class="clear">
|
||||
|
||||
The `HeroListComponent` [example](guide/architecture#templates) template has three forms:
|
||||
|
||||
<code-example path="architecture/src/app/hero-list.component.1.html" linenums="false" title="src/app/hero-list.component.html (binding)" region="binding"></code-example>
|
||||
|
||||
* The `{{hero.name}}` [*interpolation*](guide/displaying-data#interpolation)
|
||||
displays the component's `hero.name` property value within the `<li>` element.
|
||||
|
||||
* The `[hero]` [*property binding*](guide/template-syntax#property-binding) passes the value of `selectedHero` from
|
||||
the parent `HeroListComponent` to the `hero` property of the child `HeroDetailComponent`.
|
||||
|
||||
* The `(click)` [*event binding*](guide/user-input#click) calls the component's `selectHero` method when the user clicks a hero's name.
|
||||
|
||||
**Two-way data binding** is an important fourth form
|
||||
that combines property and event binding in a single notation, using the `ngModel` directive.
|
||||
Here's an example from the `HeroDetailComponent` template:
|
||||
|
||||
<code-example path="architecture/src/app/hero-detail.component.html" linenums="false" title="src/app/hero-detail.component.html (ngModel)" region="ngModel"></code-example>
|
||||
|
||||
In two-way binding, a data property value flows to the input box from the component as with property binding.
|
||||
The user's changes also flow back to the component, resetting the property to the latest value,
|
||||
as with event binding.
|
||||
|
||||
Angular processes *all* data bindings once per JavaScript event cycle,
|
||||
from the root of the application component tree through all child components.
|
||||
|
||||
<figure>
|
||||
<img src="generated/images/guide/architecture/component-databinding.png" alt="Data Binding">
|
||||
</figure>
|
||||
|
||||
Data binding plays an important role in communication between a template and its component.
|
||||
|
||||
<figure>
|
||||
<img src="generated/images/guide/architecture/parent-child-binding.png" alt="Parent/Child binding">
|
||||
</figure>
|
||||
|
||||
Data binding is also important for communication between parent and child components.
|
||||
|
||||
<hr/>
|
||||
|
||||
## Directives
|
||||
|
||||
<img src="generated/images/guide/architecture/directive.png" alt="Parent child" class="left">
|
||||
|
||||
Angular templates are *dynamic*. When Angular renders them, it transforms the DOM
|
||||
according to the instructions given by **directives**.
|
||||
|
||||
A directive is a class with a `@Directive` decorator.
|
||||
A component is a *directive-with-a-template*;
|
||||
a `@Component` decorator is actually a `@Directive` decorator extended with template-oriented features.
|
||||
|
||||
<div class="l-sub-section">
|
||||
|
||||
While **a component is technically a directive**,
|
||||
components are so distinctive and central to Angular applications that this architectural overview separates components from directives.
|
||||
|
||||
</div>
|
||||
|
||||
Two *other* kinds of directives exist: _structural_ and _attribute_ directives.
|
||||
|
||||
They tend to appear within an element tag as attributes do,
|
||||
sometimes by name but more often as the target of an assignment or a binding.
|
||||
|
||||
**Structural** directives alter layout by adding, removing, and replacing elements in DOM.
|
||||
|
||||
The [example template](guide/architecture#templates) uses two built-in structural directives:
|
||||
|
||||
<code-example path="architecture/src/app/hero-list.component.1.html" linenums="false" title="src/app/hero-list.component.html (structural)" region="structural"></code-example>
|
||||
|
||||
* [`*ngFor`](guide/displaying-data#ngFor) tells Angular to stamp out one `<li>` per hero in the `heroes` list.
|
||||
* [`*ngIf`](guide/displaying-data#ngIf) includes the `HeroDetail` component only if a selected hero exists.
|
||||
|
||||
**Attribute** directives alter the appearance or behavior of an existing element.
|
||||
In templates they look like regular HTML attributes, hence the name.
|
||||
|
||||
The `ngModel` directive, which implements two-way data binding, is
|
||||
an example of an attribute directive. `ngModel` modifies the behavior of
|
||||
an existing element (typically an `<input>`)
|
||||
by setting its display value property and responding to change events.
|
||||
|
||||
<code-example path="architecture/src/app/hero-detail.component.html" linenums="false" title="src/app/hero-detail.component.html (ngModel)" region="ngModel"></code-example>
|
||||
|
||||
Angular has a few more directives that either alter the layout structure
|
||||
(for example, [ngSwitch](guide/template-syntax#ngSwitch))
|
||||
or modify aspects of DOM elements and components
|
||||
(for example, [ngStyle](guide/template-syntax#ngStyle) and [ngClass](guide/template-syntax#ngClass)).
|
||||
|
||||
Of course, you can also write your own directives. Components such as
|
||||
`HeroListComponent` are one kind of custom directive.
|
||||
|
||||
<!-- PENDING: link to where to learn more about other kinds! -->
|
||||
|
||||
<hr/>
|
||||
|
||||
## Services
|
||||
|
||||
<img src="generated/images/guide/architecture/service.png" alt="Service" class="left">
|
||||
|
||||
_Service_ is a broad category encompassing any value, function, or feature that your application needs.
|
||||
|
||||
Almost anything can be a service.
|
||||
A service is typically a class with a narrow, well-defined purpose. It should do something specific and do it well.
|
||||
<br class="clear">
|
||||
|
||||
Examples include:
|
||||
|
||||
* logging service
|
||||
* data service
|
||||
* message bus
|
||||
* tax calculator
|
||||
* application configuration
|
||||
|
||||
There is nothing specifically _Angular_ about services. Angular has no definition of a service.
|
||||
There is no service base class, and no place to register a service.
|
||||
|
||||
Yet services are fundamental to any Angular application. Components are big consumers of services.
|
||||
|
||||
Here's an example of a service class that logs to the browser console:
|
||||
|
||||
<code-example path="architecture/src/app/logger.service.ts" linenums="false" title="src/app/logger.service.ts (class)" region="class"></code-example>
|
||||
|
||||
Here's a `HeroService` that uses a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) to fetch heroes.
|
||||
The `HeroService` depends on the `Logger` service and another `BackendService` that handles the server communication grunt work.
|
||||
|
||||
<code-example path="architecture/src/app/hero.service.ts" linenums="false" title="src/app/hero.service.ts (class)" region="class"></code-example>
|
||||
|
||||
Services are everywhere.
|
||||
|
||||
Component classes should be lean. They don't fetch data from the server,
|
||||
validate user input, or log directly to the console.
|
||||
They delegate such tasks to services.
|
||||
|
||||
A component's job is to enable the user experience and nothing more. It mediates between the view (rendered by the template)
|
||||
and the application logic (which often includes some notion of a _model_).
|
||||
A good component presents properties and methods for data binding.
|
||||
It delegates everything nontrivial to services.
|
||||
|
||||
Angular doesn't *enforce* these principles.
|
||||
It won't complain if you write a "kitchen sink" component with 3000 lines.
|
||||
|
||||
Angular does help you *follow* these principles by making it easy to factor your
|
||||
application logic into services and make those services available to components through *dependency injection*.
|
||||
|
||||
<hr/>
|
||||
|
||||
## Dependency injection
|
||||
|
||||
<img src="generated/images/guide/architecture/dependency-injection.png" alt="Service" class="left">
|
||||
|
||||
_Dependency injection_ is a way to supply a new instance of a class
|
||||
with the fully-formed dependencies it requires. Most dependencies are services.
|
||||
Angular uses dependency injection to provide new components with the services they need.
|
||||
|
||||
<br class="clear">
|
||||
|
||||
Angular can tell which services a component needs by looking at the types of its constructor parameters.
|
||||
For example, the constructor of your `HeroListComponent` needs a `HeroService`:
|
||||
|
||||
|
||||
<code-example path="architecture/src/app/hero-list.component.ts" linenums="false" title="src/app/hero-list.component.ts (constructor)" region="ctor"></code-example>
|
||||
|
||||
When Angular creates a component, it first asks an **injector** for
|
||||
the services that the component requires.
|
||||
|
||||
An injector maintains a container of service instances that it has previously created.
|
||||
If a requested service instance is not in the container, the injector makes one and adds it to the container
|
||||
before returning the service to Angular.
|
||||
When all requested services have been resolved and returned,
|
||||
Angular can call the component's constructor with those services as arguments.
|
||||
This is *dependency injection*.
|
||||
|
||||
The process of `HeroService` injection looks a bit like this:
|
||||
|
||||
<figure>
|
||||
<img src="generated/images/guide/architecture/injector-injects.png" alt="Service">
|
||||
</figure>
|
||||
|
||||
If the injector doesn't have a `HeroService`, how does it know how to make one?
|
||||
|
||||
In brief, you must have previously registered a **provider** of the `HeroService` with the injector.
|
||||
A provider is something that can create or return a service, typically the service class itself.
|
||||
|
||||
You can register providers in modules or in components.
|
||||
|
||||
In general, add providers to the [root module](guide/architecture#modules) so that
|
||||
the same instance of a service is available everywhere.
|
||||
|
||||
<code-example path="architecture/src/app/app.module.ts" linenums="false" title="src/app/app.module.ts (module providers)" region="providers"></code-example>
|
||||
|
||||
Alternatively, register at a component level in the `providers` property of the `@Component` metadata:
|
||||
|
||||
<code-example path="architecture/src/app/hero-list.component.ts" linenums="false" title="src/app/hero-list.component.ts (component providers)" region="providers"></code-example>
|
||||
|
||||
Registering at a component level means you get a new instance of the
|
||||
service with each new instance of that component.
|
||||
|
||||
<!-- We've vastly oversimplified dependency injection for this overview.
|
||||
The full story is in the [dependency injection](guide/dependency-injection) page. -->
|
||||
|
||||
Points to remember about dependency injection:
|
||||
|
||||
* Dependency injection is wired into the Angular framework and used everywhere.
|
||||
|
||||
* The *injector* is the main mechanism.
|
||||
* An injector maintains a *container* of service instances that it created.
|
||||
* An injector can create a new service instance from a *provider*.
|
||||
|
||||
* A *provider* is a recipe for creating a service.
|
||||
|
||||
* Register *providers* with injectors.
|
||||
|
||||
<hr/>
|
||||
|
||||
## Wrap up
|
||||
|
||||
You've learned the basics about the eight main building blocks of an Angular application:
|
||||
|
||||
* [Modules](guide/architecture#modules)
|
||||
* [Components](guide/architecture#components)
|
||||
* [Templates](guide/architecture#templates)
|
||||
* [Metadata](guide/architecture#metadata)
|
||||
* [Data binding](guide/architecture#data-binding)
|
||||
* [Directives](guide/architecture#directives)
|
||||
* [Services](guide/architecture#services)
|
||||
* [Dependency injection](guide/architecture#dependency-injection)
|
||||
|
||||
That's a foundation for everything else in an Angular application,
|
||||
and it's more than enough to get going.
|
||||
But it doesn't include everything you need to know.
|
||||
|
||||
Here is a brief, alphabetical list of other important Angular features and services.
|
||||
Most of them are covered in this documentation (or soon will be).
|
||||
|
||||
> [**Animations**](guide/animations): Animate component behavior
|
||||
without deep knowledge of animation techniques or CSS with Angular's animation library.
|
||||
|
||||
> **Change detection**: The change detection documentation will cover how Angular decides that a component property value has changed,
|
||||
when to update the screen, and how it uses **zones** to intercept asynchronous activity and run its change detection strategies.
|
||||
|
||||
> **Events**: The events documentation will cover how to use components and services to raise events with mechanisms for
|
||||
publishing and subscribing to events.
|
||||
|
||||
> [**Forms**](guide/forms): Support complex data entry scenarios with HTML-based validation and dirty checking.
|
||||
|
||||
> [**HTTP**](guide/http): Communicate with a server to get data, save data, and invoke server-side actions with an HTTP client.
|
||||
|
||||
> [**Lifecycle hooks**](guide/lifecycle-hooks): Tap into key moments in the lifetime of a component, from its creation to its destruction,
|
||||
by implementing the lifecycle hook interfaces.
|
||||
|
||||
> [**Pipes**](guide/pipes): Use pipes in your templates to improve the user experience by transforming values for display. Consider this `currency` pipe expression:
|
||||
>
|
||||
> > `price | currency:'USD':true`
|
||||
>
|
||||
> It displays a price of 42.33 as `$42.33`.
|
||||
|
||||
> [**Router**](guide/router): Navigate from page to page within the client
|
||||
application and never leave the browser.
|
||||
|
||||
> [**Testing**](guide/testing): Run unit tests on your application parts as they interact with the Angular framework
|
||||
using the _Angular Testing Platform_.
|
||||
|
65
aio/content/guide/custom-elements.md
Normal file
65
aio/content/guide/custom-elements.md
Normal file
@ -0,0 +1,65 @@
|
||||
# Elements
|
||||
|
||||
## Release Status
|
||||
|
||||
**Angular Labs Project** - experimental and unstable. **Breaking Changes Possible**
|
||||
|
||||
Targeted to land in the [6.x release cycle](https://github.com/angular/angular/blob/master/docs/RELEASE_SCHEDULE.md) of Angular - subject to change
|
||||
|
||||
## Overview
|
||||
|
||||
Elements provides an API that allows developers to register Angular Components as Custom Elements
|
||||
("Web Components"), and bridges the built-in DOM API to Angular's component interface and change
|
||||
detection APIs.
|
||||
|
||||
```ts
|
||||
//hello-world.ts
|
||||
import { Component, Input, NgModule } from '@angular/core';
|
||||
|
||||
@Component({
|
||||
selector: 'hello-world',
|
||||
template: `<h1>Hello {{name}}</h1>`
|
||||
})
|
||||
export class HelloWorld {
|
||||
@Input() name: string = 'World!';
|
||||
}
|
||||
|
||||
@NgModule({
|
||||
declarations: [ HelloWorld ],
|
||||
entryComponents: [ HelloWorld ]
|
||||
})
|
||||
export class HelloWorldModule {}
|
||||
```
|
||||
|
||||
```ts
|
||||
//app.component.ts
|
||||
import { Component, NgModuleRef } from '@angular/core';
|
||||
import { createNgElementConstructor } from '@angular/elements';
|
||||
|
||||
import { HelloWorld } from './hello-world';
|
||||
|
||||
@Component({
|
||||
selector: 'app-root',
|
||||
templateUrl: './app.component.html',
|
||||
styleUrls: ['./app.component.css']
|
||||
})
|
||||
export class AppComponent {
|
||||
constructor(injector: Injector) {
|
||||
const NgElementConstructor = createNgElementConstructor(HelloWorld, {injector});
|
||||
customElements.register('hello-world', NgElementConstructor);
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
Once registered, these components can be used just like built-in HTML elements, because they *are*
|
||||
HTML Elements!
|
||||
|
||||
They can be used in any HTML page:
|
||||
|
||||
```html
|
||||
<hello-world name="Angular"></hello-world>
|
||||
<hello-world name="Typescript"></hello-world>
|
||||
```
|
||||
|
||||
Custom Elements are "self-bootstrapping" - they are automatically started when they are added to the
|
||||
DOM, and automatically destroyed when removed from the DOM.
|
@ -220,7 +220,7 @@ Suppose you configured the root injector (marked as A) with _generic_ providers
|
||||
You create a car component (A) that displays a car constructed from these three generic services.
|
||||
|
||||
Then you create a child component (B) that defines its own, _specialized_ providers for `CarService` and `EngineService`
|
||||
that have special capabilites suitable for whatever is going on in component (B).
|
||||
that have special capabilities suitable for whatever is going on in component (B).
|
||||
|
||||
Component (B) is the parent of another component (C) that defines its own, even _more specialized_ provider for `CarService`.
|
||||
|
||||
|
@ -295,7 +295,7 @@ to every `HttpClient` save method.
|
||||
### Making a POST request
|
||||
|
||||
Apps often POST data to a server. They POST when submitting a form.
|
||||
In the following example, the `HeroService` posts when adding a hero to the database.
|
||||
In the following example, the `HeroesService` posts when adding a hero to the database.
|
||||
|
||||
<code-example
|
||||
path="http/src/app/heroes/heroes.service.ts"
|
||||
@ -313,7 +313,6 @@ It takes two more parameters:
|
||||
1. `httpOptions` - the method options which, in this case, [specify required headers](#adding-headers).
|
||||
|
||||
Of course it catches errors in much the same manner [described above](#error-details).
|
||||
It also _taps_ the returned observable in order to log the successful POST.
|
||||
|
||||
The `HeroesComponent` initiates the actual POST operation by subscribing to
|
||||
the `Observable` returned by this service method.
|
||||
@ -347,18 +346,14 @@ the `Observable` returned by this service method.
|
||||
title="app/heroes/heroes.component.ts (deleteHero)" linenums="false">
|
||||
</code-example>
|
||||
|
||||
The component isn't expecting a result from the delete operation, so it subscribes without a callback. Even though you are not using the result, you still have to subscribe. Calling the `subscribe()` method _executes_ the observable, which is what initiates the DELETE request.
|
||||
|
||||
<div class="alert is-important">
|
||||
|
||||
You must call _subscribe()_ or nothing happens!
|
||||
You must call _subscribe()_ or nothing happens. Just calling `HeroesService.deleteHero()` **does not initiate the DELETE request.**
|
||||
|
||||
</div>
|
||||
|
||||
The component isn't expecting a result from the delete operation and
|
||||
subscribes without a callback.
|
||||
The bare `.subscribe()` _seems_ pointless.
|
||||
|
||||
In fact, it is essential.
|
||||
Merely calling `HeroService.deleteHero()` **does not initiate the DELETE request.**
|
||||
|
||||
<code-example
|
||||
path="http/src/app/heroes/heroes.component.ts"
|
||||
@ -366,7 +361,7 @@ Merely calling `HeroService.deleteHero()` **does not initiate the DELETE request
|
||||
</code-example>
|
||||
|
||||
{@a always-subscribe}
|
||||
### Always _subscribe_!
|
||||
**Always _subscribe_!**
|
||||
|
||||
An `HttpClient` method does not begin its HTTP request until you call `subscribe()` on the observable returned by that method. This is true for _all_ `HttpClient` _methods_.
|
||||
|
||||
@ -378,8 +373,7 @@ The [`AsyncPipe`](api/common/AsyncPipe) subscribes (and unsubscribes) for you au
|
||||
|
||||
All observables returned from `HttpClient` methods are _cold_ by design.
|
||||
Execution of the HTTP request is _deferred_, allowing you to extend the
|
||||
observable with additional operations such as `tap` and `catchError`
|
||||
before anything actually happens.
|
||||
observable with additional operations such as `tap` and `catchError` before anything actually happens.
|
||||
|
||||
Calling `subscribe(...)` triggers execution of the observable and causes
|
||||
`HttpClient` to compose and send the HTTP request to the server.
|
||||
@ -404,7 +398,7 @@ req.subscribe();
|
||||
### Making a PUT request
|
||||
|
||||
An app will send a PUT request to completely replace a resource with updated data.
|
||||
The following `HeroService` example is just like the POST example.
|
||||
The following `HeroesService` example is just like the POST example.
|
||||
|
||||
<code-example
|
||||
path="http/src/app/heroes/heroes.service.ts"
|
||||
@ -417,14 +411,14 @@ in order to initiate the request.
|
||||
|
||||
## Advanced usage
|
||||
|
||||
The above sections detail how to use the basic HTTP functionality in `@angular/common/http`, but sometimes you need to do more than make simple requests and get data back.
|
||||
We have discussed the basic HTTP functionality in `@angular/common/http`, but sometimes you need to do more than make simple requests and get data back.
|
||||
|
||||
### Configuring the request
|
||||
|
||||
Other aspects of an outgoing request can be configured via the options object
|
||||
passed as the last argument to the `HttpClient` method.
|
||||
|
||||
You [saw earlier](#adding-headers) that the `HeroService` sets the default headers by
|
||||
You [saw earlier](#adding-headers) that the `HeroesService` sets the default headers by
|
||||
passing an options object (`httpOptions`) to its save methods.
|
||||
You can do more.
|
||||
|
||||
@ -454,7 +448,7 @@ Here is a `searchHeroes` method that queries for heroes whose names contain the
|
||||
region="searchHeroes" linenums="false">
|
||||
</code-example>
|
||||
|
||||
If there is a search term, the code constructs an options object with an HTML URL encoded search parameter. If the term were "foo", the GET request URL would be `api/heroes/?name=foo`.
|
||||
If there is a search term, the code constructs an options object with an HTML URL-encoded search parameter. If the term were "foo", the GET request URL would be `api/heroes/?name=foo`.
|
||||
|
||||
The `HttpParms` are immutable so you'll have to use the `set()` method to update the options.
|
||||
|
||||
@ -463,7 +457,7 @@ The `HttpParms` are immutable so you'll have to use the `set()` method to update
|
||||
The sample includes an _npm package search_ feature.
|
||||
|
||||
When the user enters a name in a search-box, the `PackageSearchComponent` sends
|
||||
a search request for a package with that name to the NPM web api.
|
||||
a search request for a package with that name to the NPM web API.
|
||||
|
||||
Here's a pertinent excerpt from the template:
|
||||
|
||||
@ -486,7 +480,7 @@ That's easy to implement with RxJS operators, as shown in this excerpt.
|
||||
</code-example>
|
||||
|
||||
The `searchText$` is the sequence of search-box values coming from the user.
|
||||
It's defined as an RxJS `Subject`, which means it is an `Observable`
|
||||
It's defined as an RxJS `Subject`, which means it is a multicasting `Observable`
|
||||
that can also produce values for itself by calling `next(value)`,
|
||||
as happens in the `search()` method.
|
||||
|
||||
@ -820,7 +814,7 @@ Some folks describe it as a "_one and done_" observable.
|
||||
But an interceptor can change this to an _observable_ that emits more than once.
|
||||
|
||||
A revised version of the `CachingInterceptor` optionally returns an _observable_ that
|
||||
immediately emits the cached response, sends the request to the npm web api anyway,
|
||||
immediately emits the cached response, sends the request to the NPM web API anyway,
|
||||
and emits again later with the updated search results.
|
||||
|
||||
<code-example
|
||||
|
@ -56,7 +56,7 @@ Alternatively, the `subscribe()` method can accept callback function definitions
|
||||
|
||||
In either case, a `next` handler is required. The `error` and `complete` handlers are optional.
|
||||
|
||||
Note that a `next()` function could receive, for instance, message strings, or event objects, numeric values, or stuctures, depending on context. As a general term, we refer to data published by an observable as a *stream*. Any type of value can be represented with an observable, and the values are published as a stream.
|
||||
Note that a `next()` function could receive, for instance, message strings, or event objects, numeric values, or structures, depending on context. As a general term, we refer to data published by an observable as a *stream*. Any type of value can be represented with an observable, and the values are published as a stream.
|
||||
|
||||
## Creating observables
|
||||
|
||||
|
@ -507,7 +507,7 @@ These files go in the root folder next to `src/`.
|
||||
</td>
|
||||
<td>
|
||||
|
||||
Git configuration to make sure autogenerated files are not commited to source control.
|
||||
Git configuration to make sure autogenerated files are not committed to source control.
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
|
@ -940,8 +940,7 @@ with that hero's data values.
|
||||
|
||||
A refresh button clears the hero list and the current selected hero before refetching the heroes.
|
||||
|
||||
Notice that `hero-list.component.ts` imports `Observable` and `finally` while `hero.service.ts` imports `Observable`, `of`,
|
||||
and `delay` from `rxjs`.
|
||||
Notice that `hero-list.component.ts` imports `Observable` and the `finalize` operator, while `hero.service.ts` imports `Observable`, `of`, and the `delay` operator from `rxjs`.
|
||||
|
||||
The remaining `HeroListComponent` and `HeroService` implementation details are beyond the scope of this tutorial.
|
||||
However, the techniques involved are covered elsewhere in the documentation, including the _Tour of Heroes_
|
||||
|
@ -340,9 +340,9 @@ It has a great deal of useful information including:
|
||||
|
||||
Two older properties are still available. They are less capable than their replacements, discouraged, and may be deprecated in a future Angular version.
|
||||
|
||||
**`params`** — An `Observable` that contains the required and [optional parameters](#optional-route-parameters) specific to the route. Use `paramMap` instead.
|
||||
**`params`**—An `Observable` that contains the required and [optional parameters](#optional-route-parameters) specific to the route. Use `paramMap` instead.
|
||||
|
||||
**`queryParams`** — An `Observable` that contains the [query parameters](#query-parameters) available to all routes.
|
||||
**`queryParams`**—An `Observable` that contains the [query parameters](#query-parameters) available to all routes.
|
||||
Use `queryParamMap` instead.
|
||||
|
||||
</div>
|
||||
@ -1619,8 +1619,7 @@ They are distributed across two modules, `AppRoutingModule` and `HeroesRoutingMo
|
||||
Each routing module augments the route configuration _in the order of import_.
|
||||
If you list `AppRoutingModule` first, the wildcard route will be registered
|
||||
_before_ the hero routes.
|
||||
The wildcard route — which matches _every_ URL —
|
||||
will intercept the attempt to navigate to a hero route.
|
||||
The wildcard route—which matches _every_ URL—will intercept the attempt to navigate to a hero route.
|
||||
|
||||
|
||||
<div class="l-sub-section">
|
||||
@ -2060,7 +2059,7 @@ The path for the "Heroes" route doesn't have an `:id` token.
|
||||
|
||||
The optional route parameters are not separated by "?" and "&" as they would be in the URL query string.
|
||||
They are **separated by semicolons ";"**
|
||||
This is *matrix URL* notation — something you may not have seen before.
|
||||
This is *matrix URL* notation—something you may not have seen before.
|
||||
|
||||
|
||||
<div class="l-sub-section">
|
||||
@ -3149,7 +3148,7 @@ Here's a demo `AuthService`:
|
||||
Although it doesn't actually log in, it has what you need for this discussion.
|
||||
It has an `isLoggedIn` flag to tell you whether the user is authenticated.
|
||||
Its `login` method simulates an API call to an external service by returning an
|
||||
Observable that resolves successfully after a short pause.
|
||||
observable that resolves successfully after a short pause.
|
||||
The `redirectUrl` property will store the attempted URL so you can navigate to it after authenticating.
|
||||
|
||||
Revise the `AuthGuard` to call it.
|
||||
@ -3459,13 +3458,11 @@ Be explicit. Implement the `Resolve` interface with a type of `Crisis`.
|
||||
Inject the `CrisisService` and `Router` and implement the `resolve()` method.
|
||||
That method could return a `Promise`, an `Observable`, or a synchronous return value.
|
||||
|
||||
The `CrisisService.getCrisis` method returns an Observable.
|
||||
Return that observable to prevent the route from loading until the data is fetched.
|
||||
The `Router` guards require an Observable to `complete`, meaning it has emitted all
|
||||
The `CrisisService.getCrisis` method returns an observable, in order to prevent the route from loading until the data is fetched.
|
||||
The `Router` guards require an observable to `complete`, meaning it has emitted all
|
||||
of its values. You use the `take` operator with an argument of `1` to ensure that the
|
||||
Observable completes after retrieving the first value from the Observable returned by the
|
||||
`getCrisis` method.
|
||||
If it doesn't return a valid `Crisis`, navigate the user back to the `CrisisListComponent`,
|
||||
observable completes after retrieving the first value from the observable returned by the
|
||||
`getCrisis` method. If it doesn't return a valid `Crisis`, navigate the user back to the `CrisisListComponent`,
|
||||
canceling the previous in-flight navigation to the `CrisisDetailComponent`.
|
||||
|
||||
Import this resolver in the `crisis-center-routing.module.ts`
|
||||
@ -3502,8 +3499,8 @@ The router looks for that method and calls it if found.
|
||||
Don't worry about all the ways that the user could navigate away.
|
||||
That's the router's job. Write this class and let the router take it from there.
|
||||
|
||||
1. The Observable provided to the Router _must_ complete.
|
||||
If the Observable does not complete, the navigation will not continue.
|
||||
1. The observable provided to the Router _must_ complete.
|
||||
If the observable does not complete, the navigation will not continue.
|
||||
|
||||
The relevant *Crisis Center* code for this milestone follows.
|
||||
|
||||
@ -3928,7 +3925,7 @@ The router calls the `preload` method with two arguments:
|
||||
1. The route to consider.
|
||||
1. A loader function that can load the routed module asynchronously.
|
||||
|
||||
An implementation of `preload`must return an `Observable`.
|
||||
An implementation of `preload` must return an `Observable`.
|
||||
If the route should preload, it returns the observable returned by calling the loader function.
|
||||
If the route should _not_ preload, it returns an `Observable` of `null`.
|
||||
|
||||
|
@ -97,7 +97,7 @@ using an example application.
|
||||
|
||||
### Serving with `http-server`
|
||||
|
||||
Because `ng serve` does not work with service workers, you must use a seperate HTTP server to test your project locally. You can use any HTTP server. The example below uses the [http-server](https://www.npmjs.com/package/http-server) package from npm. To reduce the possibility of conflicts, test on a dedicated port.
|
||||
Because `ng serve` does not work with service workers, you must use a separate HTTP server to test your project locally. You can use any HTTP server. The example below uses the [http-server](https://www.npmjs.com/package/http-server) package from npm. To reduce the possibility of conflicts, test on a dedicated port.
|
||||
|
||||
To serve with `http-server`, change to the directory containing your web files and start the web server:
|
||||
|
||||
|
@ -262,13 +262,12 @@ test any service with a dependency.
|
||||
|
||||
<div class="alert is-important">
|
||||
|
||||
The `HeroService` methods return _Observables_.
|
||||
_Subscribe_ to the method observable to (a) cause it to execute and (b)
|
||||
The `HeroService` methods return `Observables`. You must
|
||||
_subscribe_ to an observable to (a) cause it to execute and (b)
|
||||
assert that the method succeeds or fails.
|
||||
|
||||
The `subscribe()` method takes a success and fail callback.
|
||||
Make sure you provide _both_ callbacks so that you capture errors.
|
||||
|
||||
The `subscribe()` method takes a success (`next`) and fail (`error`) callback.
|
||||
Make sure you provide _both_ callbacks so that you capture errors.
|
||||
Neglecting to do so produces an asynchronous uncaught observable error that
|
||||
the test runner will likely attribute to a completely different test.
|
||||
|
||||
@ -1024,9 +1023,9 @@ Focus on the spy.
|
||||
region="spy">
|
||||
</code-example>
|
||||
|
||||
The spy is designed such that any call to `getQuote` receives an Observable with a test quote.
|
||||
The spy is designed such that any call to `getQuote` receives an observable with a test quote.
|
||||
Unlike the real `getQuote()` method, this spy bypasses the server
|
||||
and returns a synchronous Observable whose value is available immediately.
|
||||
and returns a synchronous observable whose value is available immediately.
|
||||
|
||||
You can write many useful tests with this spy, even though its `Observable` is synchronous.
|
||||
|
||||
@ -1114,14 +1113,14 @@ Or you can copy this one from the sample code.
|
||||
|
||||
This helper's observable emits the `data` value in the next turn of the JavaScript engine.
|
||||
|
||||
[RxJS `defer()`](http://reactivex.io/documentation/operators/defer.html) returns an observable.
|
||||
The [RxJS `defer()` operator](http://reactivex.io/documentation/operators/defer.html) returns an observable.
|
||||
It takes a factory function that returns either a promise or an observable.
|
||||
When something subscribes to _defer_'s observable,
|
||||
it adds the subscriber to a new observable created with that factory.
|
||||
|
||||
RxJS `defer()` transform the `Promise.resolve()` into a new observable that,
|
||||
The `defer()` operator transforms the `Promise.resolve()` into a new observable that,
|
||||
like `HttpClient`, emits once and completes.
|
||||
Subscribers will be unsubscribed after they receive the data value.
|
||||
Subscribers are unsubscribed after they receive the data value.
|
||||
|
||||
There's a similar helper for producing an async error.
|
||||
|
||||
@ -1688,10 +1687,9 @@ Here's the `HeroDetailComponent` constructor:
|
||||
<code-example path="testing/src/app/hero/hero-detail.component.ts" region="ctor" title="app/hero/hero-detail.component.ts (constructor)" linenums="false"></code-example>
|
||||
|
||||
The `HeroDetail` component needs the `id` parameter so it can fetch
|
||||
the corresponding hero via the `HeroDetailService`.
|
||||
|
||||
the corresponding hero via the `HeroDetailService`.
|
||||
The component has to get the `id` from the `ActivatedRoute.paramMap` property
|
||||
which is an _Observable_.
|
||||
which is an `Observable`.
|
||||
|
||||
It can't just reference the `id` property of the `ActivatedRoute.paramMap`.
|
||||
The component has to _subscribe_ to the `ActivatedRoute.paramMap` observable and be prepared
|
||||
@ -2365,7 +2363,7 @@ Focus on the `overrideComponent` method.
|
||||
<code-example path="testing/src/app/hero/hero-detail.component.spec.ts" region="override-component-method" title="app/hero/hero-detail.component.spec.ts (overrideComponent)" linenums="false"></code-example>
|
||||
|
||||
It takes two arguments: the component type to override (`HeroDetailComponent`) and an override metadata object.
|
||||
The [overide metadata object](#metadata-override-object) is a generic defined as follows:
|
||||
The [override metadata object](#metadata-override-object) is a generic defined as follows:
|
||||
|
||||
<code-example format="." language="javascript">
|
||||
type MetadataOverride<T> = {
|
||||
|
@ -1342,7 +1342,7 @@ and the other loads the details of a specified phone:
|
||||
<code-example path="upgrade-phonecat-2-hybrid/app/core/phone/phone.service.ts" region="fullclass" title="app/core/phone/phone.service.ts">
|
||||
</code-example>
|
||||
|
||||
The methods now return Observables of type `PhoneData` and `PhoneData[]`. This is
|
||||
The methods now return observables of type `PhoneData` and `PhoneData[]`. This is
|
||||
a type you don't have yet. Add a simple interface for it:
|
||||
|
||||
<code-example path="upgrade-phonecat-2-hybrid/app/core/phone/phone.service.ts" region="phonedata-interface" title="app/core/phone/phone.service.ts (interface)" linenums="false">
|
||||
@ -1385,14 +1385,14 @@ it's really an instance of the `Phone` class and you annotate its type according
|
||||
|
||||
Now there are two AngularJS components using an Angular service!
|
||||
The components don't need to be aware of this, though the fact that the
|
||||
service returns Observables and not Promises is a bit of a giveaway.
|
||||
service returns observables and not promises is a bit of a giveaway.
|
||||
In any case, what you've achieved is a migration of a service to Angular
|
||||
without having to yet migrate the components that use it.
|
||||
|
||||
<div class="alert is-helpful">
|
||||
|
||||
You could use the `toPromise` method of `Observable` to turn those
|
||||
Observables into Promises in the service. In many cases that reduce
|
||||
observables into promises in the service. In many cases that reduce
|
||||
the number of changes to the component controllers.
|
||||
|
||||
</div>
|
||||
|
BIN
aio/content/images/guide/architecture/compilation-context.png
Normal file
BIN
aio/content/images/guide/architecture/compilation-context.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 47 KiB |
BIN
aio/content/images/guide/architecture/view-hierarchy.png
Normal file
BIN
aio/content/images/guide/architecture/view-hierarchy.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 76 KiB |
@ -125,13 +125,39 @@
|
||||
"tooltip": "The fundamentals of Angular",
|
||||
"children": [
|
||||
{
|
||||
"url": "guide/architecture",
|
||||
"title": "Architecture",
|
||||
"tooltip": "The basic building blocks of Angular applications."
|
||||
"tooltip": "The basic building blocks of Angular applications.",
|
||||
"children": [
|
||||
{
|
||||
"url": "guide/architecture",
|
||||
"title": "Architecture Overview",
|
||||
"tooltip": "Basic building blocks of Angular applications."
|
||||
},
|
||||
{
|
||||
"url": "guide/architecture-modules",
|
||||
"title": "Intro to Modules",
|
||||
"tooltip": "About NgModules."
|
||||
},
|
||||
{
|
||||
"url": "guide/architecture-components",
|
||||
"title": "Intro to Components",
|
||||
"tooltip": "About Components, Templates, and Views."
|
||||
},
|
||||
{
|
||||
"url": "guide/architecture-services",
|
||||
"title": "Intro to Services and DI",
|
||||
"tooltip": "About services and dependency injection."
|
||||
},
|
||||
{
|
||||
"url": "guide/architecture-next-steps",
|
||||
"title": "Next Steps",
|
||||
"tooltip": "Beyond the basics."
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "Template & Data Binding",
|
||||
"tooltip": "Template & Data Binding",
|
||||
"title": "Components & Templates",
|
||||
"tooltip": "Building dynamic views with data binding",
|
||||
"children": [
|
||||
{
|
||||
"url": "guide/displaying-data",
|
||||
@ -172,7 +198,7 @@
|
||||
"url": "guide/structural-directives",
|
||||
"title": "Structural Directives",
|
||||
"tooltip": "Structural directives manipulate the layout of the page."
|
||||
},
|
||||
},
|
||||
{
|
||||
"url": "guide/pipes",
|
||||
"title": "Pipes",
|
||||
@ -431,6 +457,11 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"url": "guide/custom-elements",
|
||||
"title": "Custom Elements",
|
||||
"tooltip": "Using Angular Components as Custom Elements."
|
||||
},
|
||||
{
|
||||
"title": "Service Workers",
|
||||
"tooltip": "Angular service workers: Controlling caching of application resources.",
|
||||
|
@ -446,7 +446,7 @@ Here are the code files discussed on this page and your app should look like thi
|
||||
* You used [Angular Dependency Injection](guide/dependency-injection) to inject it into a component.
|
||||
* You gave the `HeroService` _get data_ method an asynchronous signature.
|
||||
* You discovered `Observable` and the RxJS _Observable_ library.
|
||||
* You used RxJS `of()` to return an _Observable_ of mock heroes (`Observable<Hero[]>`).
|
||||
* You used RxJS `of()` to return an observable of mock heroes (`Observable<Hero[]>`).
|
||||
* The component's `ngOnInit` lifecycle hook calls the `HeroService` method, not the constructor.
|
||||
* You created a `MessageService` for loosely-coupled communication between classes.
|
||||
* The `HeroService` injected into a component is created with another injected service,
|
||||
|
@ -145,8 +145,8 @@ All `HttpClient` methods return an RxJS `Observable` of something.
|
||||
HTTP is a request/response protocol.
|
||||
You make a request, it returns a single response.
|
||||
|
||||
In general, an `Observable` _can_ return multiple values over time.
|
||||
An `Observable` from `HttpClient` always emits a single value and then completes, never to emit again.
|
||||
In general, an observable _can_ return multiple values over time.
|
||||
An observable from `HttpClient` always emits a single value and then completes, never to emit again.
|
||||
|
||||
This particular `HttpClient.get` call returns an `Observable<Hero[]>`, literally "_an observable of hero arrays_". In practice, it will only return a single hero array.
|
||||
|
||||
@ -513,8 +513,8 @@ The `searchTerms` becomes an `Observable` emitting a steady stream of search ter
|
||||
Passing a new search term directly to the `searchHeroes()` after every user keystroke would create an excessive amount of HTTP requests,
|
||||
taxing server resources and burning through the cellular network data plan.
|
||||
|
||||
Instead, the `ngOnInit()` method pipes the `searchTerms` _observable_ through a sequence of RxJS operators that reduce the number of calls to the `searchHeroes()`,
|
||||
ultimately returning an _observable_ of timely hero search results (each a `Hero[]`).
|
||||
Instead, the `ngOnInit()` method pipes the `searchTerms` observable through a sequence of RxJS operators that reduce the number of calls to the `searchHeroes()`,
|
||||
ultimately returning an observable of timely hero search results (each a `Hero[]`).
|
||||
|
||||
Here's the code.
|
||||
|
||||
@ -529,7 +529,7 @@ Here's the code.
|
||||
before passing along the latest string. You'll never make requests more frequently than 300ms.
|
||||
|
||||
|
||||
* `distinctUntilChanged` ensures that a request is sent only if the filter text changed.
|
||||
* `distinctUntilChanged()` ensures that a request is sent only if the filter text changed.
|
||||
|
||||
|
||||
* `switchMap()` calls the search service for each search term that makes it through `debounce` and `distinctUntilChanged`.
|
||||
@ -648,7 +648,7 @@ You're at the end of your journey, and you've accomplished a lot.
|
||||
* You extended `HeroService` to support `post()`, `put()`, and `delete()` methods.
|
||||
* You updated the components to allow adding, editing, and deleting of heroes.
|
||||
* You configured an in-memory web API.
|
||||
* You learned how to use Observables.
|
||||
* You learned how to use observables.
|
||||
|
||||
This concludes the "Tour of Heroes" tutorial.
|
||||
You're ready to learn more about Angular development in the fundamentals section,
|
||||
|
@ -70,31 +70,34 @@
|
||||
},
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@angular/animations": "^5.2.0",
|
||||
"@angular/animations": "^6.0.0-rc.0",
|
||||
"@angular/cdk": "^5.0.0-rc.1",
|
||||
"@angular/common": "^5.2.0",
|
||||
"@angular/compiler": "^5.2.0",
|
||||
"@angular/core": "^5.2.0",
|
||||
"@angular/forms": "^5.2.0",
|
||||
"@angular/http": "^5.2.0",
|
||||
"@angular/common": "^6.0.0-rc.0",
|
||||
"@angular/compiler": "^6.0.0-rc.0",
|
||||
"@angular/core": "^6.0.0-rc.0",
|
||||
"@angular/elements": "^6.0.0-rc.0",
|
||||
"@angular/forms": "^6.0.0-rc.0",
|
||||
"@angular/http": "^6.0.0-rc.0",
|
||||
"@angular/material": "^5.0.0-rc.1",
|
||||
"@angular/platform-browser": "^5.2.0",
|
||||
"@angular/platform-browser-dynamic": "^5.2.0",
|
||||
"@angular/platform-server": "^5.2.0",
|
||||
"@angular/router": "^5.2.0",
|
||||
"@angular/platform-browser": "^6.0.0-rc.0",
|
||||
"@angular/platform-browser-dynamic": "^6.0.0-rc.0",
|
||||
"@angular/platform-server": "^6.0.0-rc.0",
|
||||
"@angular/router": "^6.0.0-rc.0",
|
||||
"@angular/service-worker": "^1.0.0-beta.16",
|
||||
"@webcomponents/custom-elements": "^1.0.8",
|
||||
"classlist.js": "^1.1.20150312",
|
||||
"core-js": "^2.4.1",
|
||||
"jasmine": "^2.6.0",
|
||||
"ng-pwa-tools": "^0.0.10",
|
||||
"rxjs": "^5.5.2",
|
||||
"tslib": "^1.7.1",
|
||||
"rxjs": "^6.0.0-beta.1",
|
||||
"rxjs-compat": "^6.0.0-beta.1",
|
||||
"tslib": "^1.9.0",
|
||||
"web-animations-js": "^2.2.5",
|
||||
"zone.js": "^0.8.19"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@angular/cli": "^1.6.3",
|
||||
"@angular/compiler-cli": "5.2",
|
||||
"@angular/cli": "^1.7.3",
|
||||
"@angular/compiler-cli": "^6.0.0-rc.0",
|
||||
"@types/jasmine": "^2.5.52",
|
||||
"@types/jasminewd2": "^2.0.3",
|
||||
"@types/node": "~6.0.60",
|
||||
@ -144,7 +147,7 @@
|
||||
"tree-kill": "^1.1.0",
|
||||
"ts-node": "^3.3.0",
|
||||
"tslint": "~4.5.0",
|
||||
"typescript": "^2.5.3",
|
||||
"typescript": "^2.7.2",
|
||||
"uglify-js": "^3.0.15",
|
||||
"unist-util-filter": "^0.2.1",
|
||||
"unist-util-source": "^1.0.1",
|
||||
|
@ -2,10 +2,9 @@
|
||||
"aio": {
|
||||
"master": {
|
||||
"uncompressed": {
|
||||
"inline": 1602,
|
||||
"main": 459119,
|
||||
"polyfills": 40264,
|
||||
"embedded": 71711,
|
||||
"inline": 1971,
|
||||
"main": 584136,
|
||||
"polyfills": 40272,
|
||||
"prettify": 14888
|
||||
}
|
||||
}
|
||||
|
@ -6,17 +6,14 @@ import { HttpClient } from '@angular/common/http';
|
||||
import { MatProgressBar, MatSidenav } from '@angular/material';
|
||||
import { By } from '@angular/platform-browser';
|
||||
|
||||
import { Observable } from 'rxjs/Observable';
|
||||
import { of } from 'rxjs/observable/of';
|
||||
import { timer } from 'rxjs/observable/timer';
|
||||
import 'rxjs/add/operator/mapTo';
|
||||
import { Observable, timer } from 'rxjs';
|
||||
import { mapTo } from 'rxjs/operators';
|
||||
|
||||
import { AppComponent } from './app.component';
|
||||
import { AppModule } from './app.module';
|
||||
import { DocumentService } from 'app/documents/document.service';
|
||||
import { DocViewerComponent } from 'app/layout/doc-viewer/doc-viewer.component';
|
||||
import { Deployment } from 'app/shared/deployment.service';
|
||||
import { EmbedComponentsService } from 'app/embed-components/embed-components.service';
|
||||
import { GaService } from 'app/shared/ga.service';
|
||||
import { LocationService } from 'app/shared/location.service';
|
||||
import { Logger } from 'app/shared/logger.service';
|
||||
@ -1280,7 +1277,6 @@ function createTestingModule(initialUrl: string, mode: string = 'stable') {
|
||||
imports: [ AppModule ],
|
||||
providers: [
|
||||
{ provide: APP_BASE_HREF, useValue: '/' },
|
||||
{ provide: EmbedComponentsService, useClass: TestEmbedComponentsService },
|
||||
{ provide: GaService, useClass: TestGaService },
|
||||
{ provide: HttpClient, useClass: TestHttpClient },
|
||||
{ provide: LocationService, useFactory: () => mockLocationService },
|
||||
@ -1295,10 +1291,6 @@ function createTestingModule(initialUrl: string, mode: string = 'stable') {
|
||||
});
|
||||
}
|
||||
|
||||
class TestEmbedComponentsService {
|
||||
embedInto = jasmine.createSpy('embedInto').and.returnValue(of([]));
|
||||
}
|
||||
|
||||
class TestGaService {
|
||||
locationChanged = jasmine.createSpy('locationChanged');
|
||||
}
|
||||
@ -1379,6 +1371,6 @@ class TestHttpClient {
|
||||
}
|
||||
|
||||
// Preserve async nature of `HttpClient`.
|
||||
return timer(1).mapTo(data);
|
||||
return timer(1).pipe(mapTo(data));
|
||||
}
|
||||
}
|
||||
|
@ -13,10 +13,8 @@ import { SearchResults } from 'app/search/interfaces';
|
||||
import { SearchService } from 'app/search/search.service';
|
||||
import { TocService } from 'app/shared/toc.service';
|
||||
|
||||
import { Observable } from 'rxjs/Observable';
|
||||
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
|
||||
import { combineLatest } from 'rxjs/observable/combineLatest';
|
||||
import 'rxjs/add/operator/first';
|
||||
import { BehaviorSubject, combineLatest, Observable } from 'rxjs';
|
||||
import { first, map } from 'rxjs/operators';
|
||||
|
||||
const sideNavView = 'SideNav';
|
||||
|
||||
@ -145,7 +143,7 @@ export class AppComponent implements OnInit {
|
||||
// Compute the version picker list from the current version and the versions in the navigation map
|
||||
combineLatest(
|
||||
this.navigationService.versionInfo,
|
||||
this.navigationService.navigationViews.map(views => views['docVersions']))
|
||||
this.navigationService.navigationViews.pipe(map(views => views['docVersions'])))
|
||||
.subscribe(([versionInfo, versions]) => {
|
||||
// TODO(pbd): consider whether we can lookup the stable and next versions from the internet
|
||||
const computedVersions: NavigationNode[] = [
|
||||
@ -173,7 +171,7 @@ export class AppComponent implements OnInit {
|
||||
|
||||
this.navigationService.versionInfo.subscribe(vi => this.versionInfo = vi);
|
||||
|
||||
const hasNonEmptyToc = this.tocService.tocList.map(tocList => tocList.length > 0);
|
||||
const hasNonEmptyToc = this.tocService.tocList.pipe(map(tocList => tocList.length > 0));
|
||||
combineLatest(hasNonEmptyToc, this.showFloatingToc)
|
||||
.subscribe(([hasToc, showFloatingToc]) => this.hasFloatingToc = hasToc && showFloatingToc);
|
||||
|
||||
@ -185,7 +183,7 @@ export class AppComponent implements OnInit {
|
||||
combineLatest(
|
||||
this.documentService.currentDocument, // ...needed to determine host classes
|
||||
this.navigationService.currentNodes) // ...needed to determine `sidenav` state
|
||||
.first()
|
||||
.pipe(first())
|
||||
.subscribe(() => this.updateShell());
|
||||
}
|
||||
|
||||
|
@ -1,50 +0,0 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { AppModule } from 'app/app.module';
|
||||
import { ComponentsOrModulePath, EMBEDDED_COMPONENTS } from 'app/embed-components/embed-components.service';
|
||||
import { embeddedComponents } from 'app/embedded/embedded.module';
|
||||
|
||||
describe('AppModule', () => {
|
||||
let componentsMap: {[multiSelectorstring: string]: ComponentsOrModulePath};
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({imports: [AppModule]});
|
||||
componentsMap = TestBed.get(EMBEDDED_COMPONENTS);
|
||||
});
|
||||
|
||||
it('should provide a map of selectors to embedded components (or module)', () => {
|
||||
const allSelectors = Object.keys(componentsMap);
|
||||
|
||||
expect(allSelectors.length).toBeGreaterThan(1);
|
||||
allSelectors.forEach(selector => {
|
||||
const value = componentsMap[selector];
|
||||
const isArrayOrString = Array.isArray(value) || (typeof value === 'string');
|
||||
expect(isArrayOrString).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it('should provide a list of eagerly-loaded embedded components', () => {
|
||||
|
||||
const eagerConfig = Object.keys(componentsMap).filter(selector => Array.isArray(componentsMap[selector]));
|
||||
expect(eagerConfig.length).toBeGreaterThan(0);
|
||||
|
||||
const eagerSelectors = eagerConfig.reduce<string[]>((selectors, config) => selectors.concat(config.split(',')), []);
|
||||
expect(eagerSelectors.length).toBeGreaterThan(0);
|
||||
|
||||
// For example...
|
||||
expect(eagerSelectors).toContain('aio-toc');
|
||||
expect(eagerSelectors).toContain('aio-announcement-bar');
|
||||
});
|
||||
|
||||
it('should provide a list of lazy-loaded embedded components', () => {
|
||||
const lazySelector = Object.keys(componentsMap).find(selector => selector.includes('code-example'))!;
|
||||
const selectorCount = lazySelector.split(',').length;
|
||||
|
||||
expect(lazySelector).not.toBeNull();
|
||||
expect(selectorCount).toBe(embeddedComponents.length);
|
||||
|
||||
// For example...
|
||||
expect(lazySelector).toContain('code-example');
|
||||
expect(lazySelector).toContain('code-tabs');
|
||||
expect(lazySelector).toContain('live-example');
|
||||
});
|
||||
});
|
@ -11,12 +11,7 @@ import { MatProgressBarModule } from '@angular/material/progress-bar';
|
||||
import { MatSidenavModule } from '@angular/material/sidenav';
|
||||
import { MatToolbarModule } from '@angular/material/toolbar';
|
||||
|
||||
import { ROUTES } from '@angular/router';
|
||||
|
||||
|
||||
import { AnnouncementBarComponent } from 'app/embedded/announcement-bar/announcement-bar.component';
|
||||
import { AppComponent } from 'app/app.component';
|
||||
import { EMBEDDED_COMPONENTS, EmbeddedComponentsMap } from 'app/embed-components/embed-components.service';
|
||||
import { CustomIconRegistry, SVG_ICONS } from 'app/shared/custom-icon-registry';
|
||||
import { Deployment } from 'app/shared/deployment.service';
|
||||
import { DocViewerComponent } from 'app/layout/doc-viewer/doc-viewer.component';
|
||||
@ -42,14 +37,10 @@ import { TocService } from 'app/shared/toc.service';
|
||||
import { CurrentDateToken, currentDateProvider } from 'app/shared/current-date';
|
||||
import { WindowToken, windowProvider } from 'app/shared/window';
|
||||
|
||||
import { EmbedComponentsModule } from 'app/embed-components/embed-components.module';
|
||||
import { CustomElementsModule } from 'app/custom-elements/custom-elements.module';
|
||||
import { SharedModule } from 'app/shared/shared.module';
|
||||
import { SwUpdatesModule } from 'app/sw-updates/sw-updates.module';
|
||||
|
||||
|
||||
// The path to the `EmbeddedModule`.
|
||||
const embeddedModulePath = 'app/embedded/embedded.module#EmbeddedModule';
|
||||
|
||||
// These are the hardcoded inline svg sources to be used by the `<mat-icon>` component
|
||||
export const svgIconProviders = [
|
||||
{
|
||||
@ -100,7 +91,7 @@ export const svgIconProviders = [
|
||||
imports: [
|
||||
BrowserModule,
|
||||
BrowserAnimationsModule,
|
||||
EmbedComponentsModule,
|
||||
CustomElementsModule,
|
||||
HttpClientModule,
|
||||
MatButtonModule,
|
||||
MatIconModule,
|
||||
@ -108,10 +99,9 @@ export const svgIconProviders = [
|
||||
MatSidenavModule,
|
||||
MatToolbarModule,
|
||||
SwUpdatesModule,
|
||||
SharedModule
|
||||
SharedModule,
|
||||
],
|
||||
declarations: [
|
||||
AnnouncementBarComponent,
|
||||
AppComponent,
|
||||
DocViewerComponent,
|
||||
DtComponent,
|
||||
@ -142,27 +132,8 @@ export const svgIconProviders = [
|
||||
TocService,
|
||||
{ provide: CurrentDateToken, useFactory: currentDateProvider },
|
||||
{ provide: WindowToken, useFactory: windowProvider },
|
||||
|
||||
{
|
||||
provide: EMBEDDED_COMPONENTS,
|
||||
useValue: {
|
||||
/* tslint:disable: max-line-length */
|
||||
'aio-announcement-bar': [AnnouncementBarComponent],
|
||||
'aio-toc': [TocComponent],
|
||||
'aio-api-list, aio-contributor-list, aio-file-not-found-search, aio-resource-list, code-example, code-tabs, current-location, live-example': embeddedModulePath,
|
||||
/* tslint:enable: max-line-length */
|
||||
} as EmbeddedComponentsMap,
|
||||
},
|
||||
{
|
||||
// This is currently the only way to get `@angular/cli`
|
||||
// to split `EmbeddedModule` into a separate chunk :(
|
||||
provide: ROUTES,
|
||||
useValue: [{ path: '/embedded', loadChildren: embeddedModulePath }],
|
||||
multi: true,
|
||||
},
|
||||
],
|
||||
entryComponents: [ AnnouncementBarComponent, TocComponent ],
|
||||
entryComponents: [ TocComponent ],
|
||||
bootstrap: [ AppComponent ]
|
||||
})
|
||||
export class AppModule {
|
||||
}
|
||||
export class AppModule { }
|
||||
|
@ -1,5 +1,6 @@
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { catchError, map } from 'rxjs/operators';
|
||||
import { Logger } from 'app/shared/logger.service';
|
||||
import { CONTENT_URL_PREFIX } from 'app/documents/document.service';
|
||||
const announcementsPath = CONTENT_URL_PREFIX + 'announcements.json';
|
||||
@ -58,15 +59,17 @@ export class AnnouncementBarComponent implements OnInit {
|
||||
|
||||
ngOnInit() {
|
||||
this.http.get<Announcement[]>(announcementsPath)
|
||||
.catch(error => {
|
||||
this.logger.error(new Error(`${announcementsPath} request failed: ${error.message}`));
|
||||
return [];
|
||||
})
|
||||
.map(announcements => this.findCurrentAnnouncement(announcements))
|
||||
.catch(error => {
|
||||
this.logger.error(new Error(`${announcementsPath} contains invalid data: ${error.message}`));
|
||||
return [];
|
||||
})
|
||||
.pipe(
|
||||
catchError(error => {
|
||||
this.logger.error(new Error(`${announcementsPath} request failed: ${error.message}`));
|
||||
return [];
|
||||
}),
|
||||
map(announcements => this.findCurrentAnnouncement(announcements)),
|
||||
catchError(error => {
|
||||
this.logger.error(new Error(`${announcementsPath} contains invalid data: ${error.message}`));
|
||||
return [];
|
||||
}),
|
||||
)
|
||||
.subscribe(announcement => this.announcement = announcement);
|
||||
}
|
||||
|
@ -0,0 +1,15 @@
|
||||
import { NgModule, Type } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { HttpClientModule } from '@angular/common/http';
|
||||
import { SharedModule } from '../../shared/shared.module';
|
||||
import { AnnouncementBarComponent } from './announcement-bar.component';
|
||||
import { WithCustomElementComponent } from '../element-registry';
|
||||
|
||||
@NgModule({
|
||||
imports: [ CommonModule, SharedModule, HttpClientModule ],
|
||||
declarations: [ AnnouncementBarComponent ],
|
||||
entryComponents: [ AnnouncementBarComponent ],
|
||||
})
|
||||
export class AnnouncementBarModule implements WithCustomElementComponent {
|
||||
customElementComponent: Type<any> = AnnouncementBarComponent;
|
||||
}
|
@ -1,10 +1,12 @@
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
|
||||
import { BehaviorSubject } from 'rxjs';
|
||||
|
||||
import { ApiListComponent } from './api-list.component';
|
||||
import { ApiItem, ApiSection, ApiService } from './api.service';
|
||||
import { LocationService } from 'app/shared/location.service';
|
||||
import { SharedModule } from 'app/shared/shared.module';
|
||||
import { Logger } from 'app/shared/logger.service';
|
||||
import { MockLogger } from 'testing/logger.service';
|
||||
import { ApiListModule } from './api-list.module';
|
||||
|
||||
describe('ApiListComponent', () => {
|
||||
let component: ApiListComponent;
|
||||
@ -13,10 +15,10 @@ describe('ApiListComponent', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
imports: [ SharedModule ],
|
||||
declarations: [ ApiListComponent ],
|
||||
imports: [ ApiListModule ],
|
||||
providers: [
|
||||
{ provide: ApiService, useClass: TestApiService },
|
||||
{ provide: Logger, useClass: MockLogger },
|
||||
{ provide: LocationService, useClass: TestLocationService }
|
||||
]
|
||||
});
|
||||
@ -37,11 +39,11 @@ describe('ApiListComponent', () => {
|
||||
let badItem: ApiItem|undefined;
|
||||
expect(filtered.length).toBeGreaterThan(0, 'expected something');
|
||||
expect(filtered.every(section => section.items.every(
|
||||
item => {
|
||||
const ok = item.show === itemTest(item);
|
||||
if (!ok) { badItem = item; }
|
||||
return ok;
|
||||
}
|
||||
item => {
|
||||
const ok = item.show === itemTest(item);
|
||||
if (!ok) { badItem = item; }
|
||||
return ok;
|
||||
}
|
||||
))).toBe(true, `${label} fail: ${JSON.stringify(badItem, null, 2)}`);
|
||||
});
|
||||
}
|
@ -8,9 +8,7 @@
|
||||
|
||||
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
|
||||
|
||||
import { Observable } from 'rxjs/Observable';
|
||||
import { ReplaySubject } from 'rxjs/ReplaySubject';
|
||||
import { combineLatest } from 'rxjs/observable/combineLatest';
|
||||
import { combineLatest, Observable, ReplaySubject } from 'rxjs';
|
||||
|
||||
import { LocationService } from 'app/shared/location.service';
|
||||
import { ApiSection, ApiService } from './api.service';
|
||||
@ -25,7 +23,7 @@ class SearchCriteria {
|
||||
|
||||
@Component({
|
||||
selector: 'aio-api-list',
|
||||
templateUrl: './api-list.component.html'
|
||||
templateUrl: './api-list.component.html',
|
||||
})
|
||||
export class ApiListComponent implements OnInit {
|
||||
|
||||
@ -69,7 +67,6 @@ export class ApiListComponent implements OnInit {
|
||||
private locationService: LocationService) { }
|
||||
|
||||
ngOnInit() {
|
||||
|
||||
this.filteredSections = combineLatest(
|
||||
this.apiService.sections,
|
||||
this.criteriaSubject,
|
17
aio/src/app/custom-elements/api/api-list.module.ts
Normal file
17
aio/src/app/custom-elements/api/api-list.module.ts
Normal file
@ -0,0 +1,17 @@
|
||||
import { NgModule, Type } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { HttpClientModule } from '@angular/common/http';
|
||||
import { SharedModule } from '../../shared/shared.module';
|
||||
import { ApiListComponent } from './api-list.component';
|
||||
import { ApiService } from './api.service';
|
||||
import { WithCustomElementComponent } from '../element-registry';
|
||||
|
||||
@NgModule({
|
||||
imports: [ CommonModule, SharedModule, HttpClientModule ],
|
||||
declarations: [ ApiListComponent ],
|
||||
entryComponents: [ ApiListComponent ],
|
||||
providers: [ ApiService ]
|
||||
})
|
||||
export class ApiListModule implements WithCustomElementComponent {
|
||||
customElementComponent: Type<any> = ApiListComponent;
|
||||
}
|
@ -49,17 +49,18 @@ describe('ApiService', () => {
|
||||
|
||||
describe('#sections', () => {
|
||||
|
||||
it('first subscriber should fetch sections', () => {
|
||||
it('first subscriber should fetch sections', done => {
|
||||
const data = [{name: 'a', title: 'A', items: []}, {name: 'b', title: 'B', items: []}];
|
||||
|
||||
service.sections.subscribe(sections => {
|
||||
expect(sections).toEqual(data);
|
||||
done();
|
||||
});
|
||||
|
||||
httpMock.expectOne({}).flush(data);
|
||||
});
|
||||
|
||||
it('second subscriber should get previous sections and NOT trigger refetch', () => {
|
||||
it('second subscriber should get previous sections and NOT trigger refetch', done => {
|
||||
const data = [{name: 'a', title: 'A', items: []}, {name: 'b', title: 'B', items: []}];
|
||||
let subscriptions = 0;
|
||||
|
||||
@ -71,6 +72,8 @@ describe('ApiService', () => {
|
||||
service.sections.subscribe(sections => {
|
||||
subscriptions++;
|
||||
expect(sections).toEqual(data);
|
||||
expect(subscriptions).toBe(2);
|
||||
done();
|
||||
});
|
||||
|
||||
httpMock.expectOne({}).flush(data);
|
@ -1,11 +1,8 @@
|
||||
import { Injectable, OnDestroy } from '@angular/core';
|
||||
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
|
||||
|
||||
import { ReplaySubject } from 'rxjs/ReplaySubject';
|
||||
import { Subject } from 'rxjs/Subject';
|
||||
import 'rxjs/add/operator/do';
|
||||
import 'rxjs/add/operator/map';
|
||||
import 'rxjs/add/operator/takeUntil';
|
||||
import { ReplaySubject, Subject } from 'rxjs';
|
||||
import { takeUntil, tap } from 'rxjs/operators';
|
||||
|
||||
import { Logger } from 'app/shared/logger.service';
|
||||
import { DOC_CONTENT_URL_PREFIX } from 'app/documents/document.service';
|
||||
@ -35,7 +32,7 @@ export class ApiService implements OnDestroy {
|
||||
private firstTime = true;
|
||||
private onDestroy = new Subject();
|
||||
private sectionsSubject = new ReplaySubject<ApiSection[]>(1);
|
||||
private _sections = this.sectionsSubject.takeUntil(this.onDestroy);
|
||||
private _sections = this.sectionsSubject.pipe(takeUntil(this.onDestroy));
|
||||
|
||||
/**
|
||||
* Return a cached observable of API sections from a JSON file.
|
||||
@ -71,8 +68,10 @@ export class ApiService implements OnDestroy {
|
||||
// TODO: get URL by configuration?
|
||||
const url = this.apiBase + (src || this.apiListJsonDefault);
|
||||
this.http.get<ApiSection[]>(url)
|
||||
.takeUntil(this.onDestroy)
|
||||
.do(() => this.logger.log(`Got API sections from ${url}`))
|
||||
.pipe(
|
||||
takeUntil(this.onDestroy),
|
||||
tap(() => this.logger.log(`Got API sections from ${url}`)),
|
||||
)
|
||||
.subscribe(
|
||||
sections => this.sectionsSubject.next(sections),
|
||||
(err: HttpErrorResponse) => {
|
100
aio/src/app/custom-elements/code/code-example.component.spec.ts
Normal file
100
aio/src/app/custom-elements/code/code-example.component.spec.ts
Normal file
@ -0,0 +1,100 @@
|
||||
import { Component, ViewChild } from '@angular/core';
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
|
||||
import { CodeExampleComponent } from './code-example.component';
|
||||
import { CodeExampleModule } from './code-example.module';
|
||||
import { Logger } from 'app/shared/logger.service';
|
||||
import { MockLogger } from 'testing/logger.service';
|
||||
|
||||
describe('CodeExampleComponent', () => {
|
||||
let hostComponent: HostComponent;
|
||||
let codeExampleComponent: CodeExampleComponent;
|
||||
let fixture: ComponentFixture<HostComponent>;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
imports: [ CodeExampleModule ],
|
||||
declarations: [
|
||||
HostComponent,
|
||||
],
|
||||
providers: [
|
||||
{ provide: Logger, useClass: MockLogger },
|
||||
]
|
||||
});
|
||||
|
||||
fixture = TestBed.createComponent(HostComponent);
|
||||
hostComponent = fixture.componentInstance;
|
||||
codeExampleComponent = hostComponent.codeExampleComponent;
|
||||
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('should be able to capture the code snippet provided in content', () => {
|
||||
expect(codeExampleComponent.aioCode.code.trim()).toBe(`const foo = "bar";`);
|
||||
});
|
||||
|
||||
it('should change aio-code classes based on title presence', () => {
|
||||
expect(codeExampleComponent.title).toBe('Great Example');
|
||||
expect(fixture.nativeElement.querySelector('header')).toBeTruthy();
|
||||
expect(codeExampleComponent.classes).toEqual({
|
||||
'headed-code': true,
|
||||
'simple-code': false
|
||||
});
|
||||
|
||||
codeExampleComponent.title = '';
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(codeExampleComponent.title).toBe('');
|
||||
expect(fixture.nativeElement.querySelector('header')).toBeFalsy();
|
||||
expect(codeExampleComponent.classes).toEqual({
|
||||
'headed-code': false,
|
||||
'simple-code': true
|
||||
});
|
||||
});
|
||||
|
||||
it('should set avoidFile class if path has .avoid.', () => {
|
||||
const codeExampleComponentElement: HTMLElement =
|
||||
fixture.nativeElement.querySelector('code-example');
|
||||
|
||||
expect(codeExampleComponent.path).toBe('code-path');
|
||||
expect(codeExampleComponentElement.className.indexOf('avoidFile') === -1).toBe(true);
|
||||
|
||||
codeExampleComponent.path = 'code-path.avoid.';
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(codeExampleComponentElement.className.indexOf('avoidFile') === -1).toBe(false);
|
||||
});
|
||||
|
||||
it('should coerce hidecopy', () => {
|
||||
expect(codeExampleComponent.hidecopy).toBe(false);
|
||||
|
||||
hostComponent.hidecopy = true;
|
||||
fixture.detectChanges();
|
||||
expect(codeExampleComponent.hidecopy).toBe(true);
|
||||
|
||||
hostComponent.hidecopy = 'false';
|
||||
fixture.detectChanges();
|
||||
expect(codeExampleComponent.hidecopy).toBe(false);
|
||||
|
||||
hostComponent.hidecopy = 'true';
|
||||
fixture.detectChanges();
|
||||
expect(codeExampleComponent.hidecopy).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@Component({
|
||||
selector: 'aio-host-comp',
|
||||
template: `
|
||||
<code-example [title]="title" [path]="path" [hidecopy]="hidecopy">
|
||||
{{code}}
|
||||
</code-example>
|
||||
`
|
||||
})
|
||||
class HostComponent {
|
||||
code = `const foo = "bar";`;
|
||||
title = 'Great Example';
|
||||
path = 'code-path';
|
||||
hidecopy: boolean | string = false;
|
||||
|
||||
@ViewChild(CodeExampleComponent) codeExampleComponent: CodeExampleComponent;
|
||||
}
|
89
aio/src/app/custom-elements/code/code-example.component.ts
Normal file
89
aio/src/app/custom-elements/code/code-example.component.ts
Normal file
@ -0,0 +1,89 @@
|
||||
/* tslint:disable component-selector */
|
||||
import { Component, HostBinding, ElementRef, ViewChild, Input, AfterViewInit } from '@angular/core';
|
||||
import { CodeComponent } from './code.component';
|
||||
|
||||
/**
|
||||
* An embeddable code block that displays nicely formatted code.
|
||||
* Example usage:
|
||||
*
|
||||
* ```
|
||||
* <code-example language="ts" linenums="2" class="special" title="Do Stuff">
|
||||
* // a code block
|
||||
* console.log('do stuff');
|
||||
* </code-example>
|
||||
* ```
|
||||
*/
|
||||
@Component({
|
||||
selector: 'code-example',
|
||||
template: `
|
||||
<!-- Content projection is used to get the content HTML provided to this component -->
|
||||
<div #content style="display: none"><ng-content></ng-content></div>
|
||||
|
||||
<header *ngIf="title">{{title}}</header>
|
||||
|
||||
<aio-code [ngClass]="classes"
|
||||
[language]="language"
|
||||
[linenums]="linenums"
|
||||
[path]="path"
|
||||
[region]="region"
|
||||
[hideCopy]="hidecopy"
|
||||
[title]="title">
|
||||
</aio-code>
|
||||
`,
|
||||
})
|
||||
export class CodeExampleComponent implements AfterViewInit {
|
||||
classes: {};
|
||||
|
||||
@Input() language: string;
|
||||
|
||||
@Input() linenums: string;
|
||||
|
||||
@Input() region: string;
|
||||
|
||||
@Input()
|
||||
set title(title: string) {
|
||||
this._title = title;
|
||||
this.classes = {
|
||||
'headed-code': !!this.title,
|
||||
'simple-code': !this.title,
|
||||
};
|
||||
}
|
||||
get title(): string { return this._title; }
|
||||
private _title: string;
|
||||
|
||||
@Input()
|
||||
set path(path: string) {
|
||||
this._path = path;
|
||||
this.isAvoid = this.path.indexOf('.avoid.') !== -1;
|
||||
}
|
||||
get path(): string { return this._path; }
|
||||
private _path = '';
|
||||
|
||||
@Input()
|
||||
set hidecopy(hidecopy: boolean) {
|
||||
// Coerce the boolean value.
|
||||
this._hidecopy = hidecopy != null && `${hidecopy}` !== 'false';
|
||||
}
|
||||
get hidecopy(): boolean { return this._hidecopy; }
|
||||
private _hidecopy: boolean;
|
||||
|
||||
@Input('hide-copy')
|
||||
set hyphenatedHideCopy(hidecopy: boolean) {
|
||||
this.hidecopy = hidecopy;
|
||||
}
|
||||
|
||||
@Input('hideCopy')
|
||||
set capitalizedHideCopy(hidecopy: boolean) {
|
||||
this.hidecopy = hidecopy;
|
||||
}
|
||||
|
||||
@HostBinding('class.avoidFile') isAvoid = false;
|
||||
|
||||
@ViewChild('content') content: ElementRef;
|
||||
|
||||
@ViewChild(CodeComponent) aioCode: CodeComponent;
|
||||
|
||||
ngAfterViewInit() {
|
||||
this.aioCode.code = this.content.nativeElement.innerHTML;
|
||||
}
|
||||
}
|
15
aio/src/app/custom-elements/code/code-example.module.ts
Normal file
15
aio/src/app/custom-elements/code/code-example.module.ts
Normal file
@ -0,0 +1,15 @@
|
||||
import { NgModule, Type } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { CodeExampleComponent } from './code-example.component';
|
||||
import { CodeModule } from './code.module';
|
||||
import { WithCustomElementComponent } from '../element-registry';
|
||||
|
||||
@NgModule({
|
||||
imports: [ CommonModule, CodeModule ],
|
||||
declarations: [ CodeExampleComponent ],
|
||||
exports: [ CodeExampleComponent ],
|
||||
entryComponents: [ CodeExampleComponent ]
|
||||
})
|
||||
export class CodeExampleModule implements WithCustomElementComponent {
|
||||
customElementComponent: Type<any> = CodeExampleComponent;
|
||||
}
|
96
aio/src/app/custom-elements/code/code-tabs.component.spec.ts
Normal file
96
aio/src/app/custom-elements/code/code-tabs.component.spec.ts
Normal file
@ -0,0 +1,96 @@
|
||||
import { Component, ViewChild, NO_ERRORS_SCHEMA } from '@angular/core';
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
import { Logger } from 'app/shared/logger.service';
|
||||
import { MockLogger } from 'testing/logger.service';
|
||||
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
|
||||
|
||||
import { CodeTabsComponent } from './code-tabs.component';
|
||||
import { CodeTabsModule } from './code-tabs.module';
|
||||
|
||||
describe('CodeTabsComponent', () => {
|
||||
let fixture: ComponentFixture<HostComponent>;
|
||||
let hostComponent: HostComponent;
|
||||
let codeTabsComponent: CodeTabsComponent;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
declarations: [ HostComponent ],
|
||||
imports: [ CodeTabsModule, NoopAnimationsModule ],
|
||||
schemas: [ NO_ERRORS_SCHEMA ],
|
||||
providers: [
|
||||
{ provide: Logger, useClass: MockLogger },
|
||||
]
|
||||
});
|
||||
|
||||
fixture = TestBed.createComponent(HostComponent);
|
||||
hostComponent = fixture.componentInstance;
|
||||
codeTabsComponent = hostComponent.codeTabsComponent;
|
||||
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('should get correct tab info', () => {
|
||||
const tabs = codeTabsComponent.tabs;
|
||||
expect(tabs.length).toBe(2);
|
||||
|
||||
// First code pane expectations
|
||||
expect(tabs[0].class).toBe('class-A');
|
||||
expect(tabs[0].language).toBe('language-A');
|
||||
expect(tabs[0].linenums).toBe('linenums-A');
|
||||
expect(tabs[0].path).toBe('path-A');
|
||||
expect(tabs[0].region).toBe('region-A');
|
||||
expect(tabs[0].title).toBe('title-A');
|
||||
expect(tabs[0].code.trim()).toBe('Code example 1');
|
||||
|
||||
// Second code pane expectations
|
||||
expect(tabs[1].class).toBe('class-B');
|
||||
expect(tabs[1].language).toBe('language-B');
|
||||
expect(tabs[1].linenums).toBe('default-linenums', 'Default linenums should have been used');
|
||||
expect(tabs[1].path).toBe('path-B');
|
||||
expect(tabs[1].region).toBe('region-B');
|
||||
expect(tabs[1].title).toBe('title-B');
|
||||
expect(tabs[1].code.trim()).toBe('Code example 2');
|
||||
});
|
||||
|
||||
it('should create the right number of tabs with the right labels and classes', () => {
|
||||
const matTabs = fixture.nativeElement.querySelectorAll('.mat-tab-label');
|
||||
expect(matTabs.length).toBe(2);
|
||||
|
||||
expect(matTabs[0].textContent.trim()).toBe('title-A');
|
||||
expect(matTabs[0].querySelector('.class-A')).toBeTruthy();
|
||||
|
||||
expect(matTabs[1].textContent.trim()).toBe('title-B');
|
||||
expect(matTabs[1].querySelector('.class-B')).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should show the first tab with the right code', () => {
|
||||
const codeContent = fixture.nativeElement.querySelector('aio-code').textContent;
|
||||
expect(codeContent.indexOf('Code example 1') !== -1).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
@Component({
|
||||
selector: 'aio-host-comp',
|
||||
template: `
|
||||
<code-tabs linenums="default-linenums">
|
||||
<code-pane class="class-A"
|
||||
language="language-A"
|
||||
linenums="linenums-A"
|
||||
path="path-A"
|
||||
region="region-A"
|
||||
title="title-A">
|
||||
Code example 1
|
||||
</code-pane>
|
||||
<code-pane class="class-B"
|
||||
language="language-B"
|
||||
path="path-B"
|
||||
region="region-B"
|
||||
title="title-B">
|
||||
Code example 2
|
||||
</code-pane>
|
||||
</code-tabs>
|
||||
`
|
||||
})
|
||||
class HostComponent {
|
||||
@ViewChild(CodeTabsComponent) codeTabsComponent: CodeTabsComponent;
|
||||
}
|
81
aio/src/app/custom-elements/code/code-tabs.component.ts
Normal file
81
aio/src/app/custom-elements/code/code-tabs.component.ts
Normal file
@ -0,0 +1,81 @@
|
||||
/* tslint:disable component-selector */
|
||||
import { Component, AfterViewInit, ViewChild, Input, ViewChildren, QueryList, OnInit } from '@angular/core';
|
||||
import { CodeComponent } from './code.component';
|
||||
|
||||
export interface TabInfo {
|
||||
class: string|null;
|
||||
code: string;
|
||||
language: string|null;
|
||||
linenums: any;
|
||||
path: string;
|
||||
region: string;
|
||||
title: string|null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a set of tab group of code snippets.
|
||||
*
|
||||
* The innerHTML of the `<code-tabs>` component should contain `<code-pane>` elements.
|
||||
* Each `<code-pane>` has the same interface as the embedded `<code-example>` component.
|
||||
* The optional `linenums` attribute is the default `linenums` for each code pane.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'code-tabs',
|
||||
template: `
|
||||
<!-- Use content projection so that the provided HTML's code-panes can be split into tabs -->
|
||||
<div #content style="display: none"><ng-content></ng-content></div>
|
||||
|
||||
<mat-tab-group class="code-tab-group" disableRipple>
|
||||
<mat-tab style="overflow-y: hidden;" *ngFor="let tab of tabs">
|
||||
<ng-template mat-tab-label>
|
||||
<span class="{{ tab.class }}">{{ tab.title }}</span>
|
||||
</ng-template>
|
||||
<aio-code class="{{ tab.class }}"
|
||||
[language]="tab.language"
|
||||
[linenums]="tab.linenums"
|
||||
[path]="tab.path"
|
||||
[region]="tab.region"
|
||||
[title]="tab.title">
|
||||
</aio-code>
|
||||
</mat-tab>
|
||||
</mat-tab-group>
|
||||
`,
|
||||
})
|
||||
export class CodeTabsComponent implements OnInit, AfterViewInit {
|
||||
tabs: TabInfo[];
|
||||
|
||||
@Input('linenums') linenums: string;
|
||||
|
||||
@ViewChild('content') content;
|
||||
|
||||
@ViewChildren(CodeComponent) codeComponents: QueryList<CodeComponent>;
|
||||
|
||||
ngOnInit() {
|
||||
this.tabs = [];
|
||||
const codeExamples = this.content.nativeElement.querySelectorAll('code-pane');
|
||||
|
||||
for (let i = 0; i < codeExamples.length; i++) {
|
||||
const tabContent = codeExamples[i];
|
||||
this.tabs.push(this.getTabInfo(tabContent));
|
||||
}
|
||||
}
|
||||
|
||||
ngAfterViewInit() {
|
||||
this.codeComponents.toArray().forEach((codeComponent, i) => {
|
||||
codeComponent.code = this.tabs[i].code;
|
||||
});
|
||||
}
|
||||
|
||||
/** Gets the extracted TabInfo data from the provided code-pane element. */
|
||||
private getTabInfo(tabContent: HTMLElement): TabInfo {
|
||||
return {
|
||||
class: tabContent.getAttribute('class'),
|
||||
code: tabContent.innerHTML,
|
||||
language: tabContent.getAttribute('language'),
|
||||
linenums: tabContent.getAttribute('linenums') || this.linenums,
|
||||
path: tabContent.getAttribute('path') || '',
|
||||
region: tabContent.getAttribute('region') || '',
|
||||
title: tabContent.getAttribute('title')
|
||||
};
|
||||
}
|
||||
}
|
16
aio/src/app/custom-elements/code/code-tabs.module.ts
Normal file
16
aio/src/app/custom-elements/code/code-tabs.module.ts
Normal file
@ -0,0 +1,16 @@
|
||||
import { NgModule, Type } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { CodeTabsComponent } from './code-tabs.component';
|
||||
import { MatTabsModule } from '@angular/material';
|
||||
import { CodeModule } from './code.module';
|
||||
import { WithCustomElementComponent } from '../element-registry';
|
||||
|
||||
@NgModule({
|
||||
imports: [ CommonModule, MatTabsModule, CodeModule ],
|
||||
declarations: [ CodeTabsComponent ],
|
||||
exports: [ CodeTabsComponent ],
|
||||
entryComponents: [ CodeTabsComponent ]
|
||||
})
|
||||
export class CodeTabsModule implements WithCustomElementComponent {
|
||||
customElementComponent: Type<any> = CodeTabsComponent;
|
||||
}
|
@ -1,10 +1,12 @@
|
||||
import { Component, DebugElement } from '@angular/core';
|
||||
import { Component, ViewChild, AfterViewInit } from '@angular/core';
|
||||
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
import { MatSnackBarModule, MatSnackBar } from '@angular/material';
|
||||
import { MatSnackBar } from '@angular/material';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
|
||||
import { first } from 'rxjs/operators';
|
||||
|
||||
import { CodeComponent } from './code.component';
|
||||
import { CodeModule } from './code.module';
|
||||
import { CopierService } from 'app/shared//copier.service';
|
||||
import { Logger } from 'app/shared/logger.service';
|
||||
import { PrettyPrinter } from './pretty-printer.service';
|
||||
@ -22,12 +24,9 @@ const smallMultiLineCode = `
|
||||
const bigMultiLineCode = smallMultiLineCode + smallMultiLineCode + smallMultiLineCode;
|
||||
|
||||
describe('CodeComponent', () => {
|
||||
let codeComponentDe: DebugElement;
|
||||
let codeComponent: CodeComponent;
|
||||
let hostComponent: HostComponent;
|
||||
let fixture: ComponentFixture<HostComponent>;
|
||||
|
||||
|
||||
// WARNING: Chance of cross-test pollution
|
||||
// CodeComponent injects PrettyPrintService
|
||||
// Once PrettyPrintService runs once _anywhere_, its ctor loads `prettify.js`
|
||||
@ -42,14 +41,14 @@ describe('CodeComponent', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
imports: [ MatSnackBarModule, NoopAnimationsModule ],
|
||||
declarations: [ CodeComponent, HostComponent ],
|
||||
imports: [ NoopAnimationsModule, CodeModule ],
|
||||
declarations: [ HostComponent ],
|
||||
providers: [
|
||||
PrettyPrinter,
|
||||
CopierService,
|
||||
{provide: Logger, useClass: TestLogger }
|
||||
]
|
||||
});
|
||||
}).compileComponents();
|
||||
});
|
||||
|
||||
// Must be async because
|
||||
@ -58,80 +57,85 @@ describe('CodeComponent', () => {
|
||||
beforeEach(async(() => {
|
||||
fixture = TestBed.createComponent(HostComponent);
|
||||
hostComponent = fixture.componentInstance;
|
||||
codeComponentDe = fixture.debugElement.children[0];
|
||||
codeComponent = codeComponentDe.componentInstance;
|
||||
|
||||
fixture.detectChanges();
|
||||
}));
|
||||
|
||||
it('should create CodeComponent', () => {
|
||||
expect(codeComponentDe.name).toBe('aio-code', 'selector');
|
||||
expect(codeComponent).toBeTruthy('CodeComponent');
|
||||
});
|
||||
|
||||
describe('pretty printing', () => {
|
||||
it('should format a one-line code sample', () => {
|
||||
// 'pln' spans are a tell-tale for syntax highlighing
|
||||
const spans = codeComponentDe.nativeElement.querySelectorAll('span.pln');
|
||||
const untilCodeFormatted = () => {
|
||||
const emitter = hostComponent.codeComponent.codeFormatted;
|
||||
return emitter.pipe(first()).toPromise();
|
||||
};
|
||||
const hasLineNumbers = async () => {
|
||||
// presence of `<li>`s are a tell-tale for line numbers
|
||||
await untilCodeFormatted();
|
||||
return 0 < fixture.nativeElement.querySelectorAll('li').length;
|
||||
};
|
||||
|
||||
it('should format a one-line code sample', async () => {
|
||||
hostComponent.setCode(oneLineCode);
|
||||
await untilCodeFormatted();
|
||||
|
||||
// 'pln' spans are a tell-tale for syntax highlighting
|
||||
const spans = fixture.nativeElement.querySelectorAll('span.pln');
|
||||
expect(spans.length).toBeGreaterThan(0, 'formatted spans');
|
||||
});
|
||||
|
||||
function hasLineNumbers() {
|
||||
// presence of `<li>`s are a tell-tale for line numbers
|
||||
return 0 < codeComponentDe.nativeElement.querySelectorAll('li').length;
|
||||
}
|
||||
|
||||
it('should format a one-line code sample without linenums by default', () => {
|
||||
expect(hasLineNumbers()).toBe(false);
|
||||
it('should format a one-line code sample without linenums by default', async () => {
|
||||
hostComponent.setCode(oneLineCode);
|
||||
expect(await hasLineNumbers()).toBe(false);
|
||||
});
|
||||
|
||||
it('should add line numbers to one-line code sample when linenums set true', () => {
|
||||
it('should add line numbers to one-line code sample when linenums set true', async () => {
|
||||
hostComponent.linenums = 'true';
|
||||
fixture.detectChanges();
|
||||
expect(hasLineNumbers()).toBe(true);
|
||||
|
||||
expect(await hasLineNumbers()).toBe(true);
|
||||
});
|
||||
|
||||
it('should format a small multi-line code without linenums by default', () => {
|
||||
hostComponent.code = smallMultiLineCode;
|
||||
fixture.detectChanges();
|
||||
expect(hasLineNumbers()).toBe(false);
|
||||
it('should format a small multi-line code without linenums by default', async () => {
|
||||
hostComponent.setCode(smallMultiLineCode);
|
||||
expect(await hasLineNumbers()).toBe(false);
|
||||
});
|
||||
|
||||
it('should add line numbers to a big multi-line code by default', () => {
|
||||
hostComponent.code = bigMultiLineCode;
|
||||
fixture.detectChanges();
|
||||
expect(hasLineNumbers()).toBe(true);
|
||||
it('should add line numbers to a big multi-line code by default', async () => {
|
||||
hostComponent.setCode(bigMultiLineCode);
|
||||
expect(await hasLineNumbers()).toBe(true);
|
||||
});
|
||||
|
||||
it('should format big multi-line code without linenums when linenums set false', () => {
|
||||
it('should format big multi-line code without linenums when linenums set false', async () => {
|
||||
hostComponent.linenums = false;
|
||||
hostComponent.code = bigMultiLineCode;
|
||||
fixture.detectChanges();
|
||||
expect(hasLineNumbers()).toBe(false);
|
||||
|
||||
hostComponent.setCode(bigMultiLineCode);
|
||||
expect(await hasLineNumbers()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('whitespace handling', () => {
|
||||
it('should remove common indentation from the code before rendering', () => {
|
||||
hostComponent.linenums = false;
|
||||
hostComponent.code = ' abc\n let x = text.split(\'\\n\');\n ghi\n\n jkl\n';
|
||||
fixture.detectChanges();
|
||||
const codeContent = codeComponentDe.nativeElement.querySelector('code').textContent;
|
||||
|
||||
hostComponent.setCode(' abc\n let x = text.split(\'\\n\');\n ghi\n\n jkl\n');
|
||||
const codeContent = fixture.nativeElement.querySelector('code').textContent;
|
||||
expect(codeContent).toEqual('abc\n let x = text.split(\'\\n\');\nghi\n\njkl');
|
||||
});
|
||||
|
||||
it('should trim whitespace from the code before rendering', () => {
|
||||
hostComponent.linenums = false;
|
||||
hostComponent.code = '\n\n\n' + smallMultiLineCode + '\n\n\n';
|
||||
fixture.detectChanges();
|
||||
const codeContent = codeComponentDe.nativeElement.querySelector('code').textContent;
|
||||
|
||||
hostComponent.setCode('\n\n\n' + smallMultiLineCode + '\n\n\n');
|
||||
const codeContent = fixture.nativeElement.querySelector('code').textContent;
|
||||
expect(codeContent).toEqual(codeContent.trim());
|
||||
});
|
||||
|
||||
it('should trim whitespace from code before computing whether to format linenums', () => {
|
||||
hostComponent.code = '\n\n\n' + hostComponent.code + '\n\n\n';
|
||||
fixture.detectChanges();
|
||||
hostComponent.setCode('\n\n\n' + oneLineCode + '\n\n\n');
|
||||
|
||||
// `<li>`s are a tell-tale for line numbers
|
||||
const lis = codeComponentDe.nativeElement.querySelectorAll('li');
|
||||
const lis = fixture.nativeElement.querySelectorAll('li');
|
||||
expect(lis.length).toBe(0, 'should be no linenums');
|
||||
});
|
||||
});
|
||||
@ -139,39 +143,38 @@ describe('CodeComponent', () => {
|
||||
describe('error message', () => {
|
||||
|
||||
function getErrorMessage() {
|
||||
const missing: HTMLElement = codeComponentDe.nativeElement.querySelector('.code-missing');
|
||||
const missing: HTMLElement = fixture.nativeElement.querySelector('.code-missing');
|
||||
return missing ? missing.textContent : null;
|
||||
}
|
||||
|
||||
it('should not display "code-missing" class when there is some code', () => {
|
||||
fixture.detectChanges();
|
||||
expect(getErrorMessage()).toBeNull('should not have element with "code-missing" class');
|
||||
});
|
||||
|
||||
it('should display error message when there is no code (after trimming)', () => {
|
||||
hostComponent.code = ' \n ';
|
||||
fixture.detectChanges();
|
||||
hostComponent.setCode(' \n ');
|
||||
expect(getErrorMessage()).toContain('missing');
|
||||
});
|
||||
|
||||
it('should show path and region in missing-code error message', () => {
|
||||
hostComponent.code = ' \n ';
|
||||
hostComponent.path = 'fizz/buzz/foo.html';
|
||||
hostComponent.region = 'something';
|
||||
fixture.detectChanges();
|
||||
|
||||
hostComponent.setCode(' \n ');
|
||||
expect(getErrorMessage()).toMatch(/for[\s\S]fizz\/buzz\/foo\.html#something$/);
|
||||
});
|
||||
|
||||
it('should show path only in missing-code error message when no region', () => {
|
||||
hostComponent.code = ' \n ';
|
||||
hostComponent.path = 'fizz/buzz/foo.html';
|
||||
fixture.detectChanges();
|
||||
|
||||
hostComponent.setCode(' \n ');
|
||||
expect(getErrorMessage()).toMatch(/for[\s\S]fizz\/buzz\/foo\.html$/);
|
||||
});
|
||||
|
||||
it('should show simple missing-code error message when no path/region', () => {
|
||||
hostComponent.code = ' \n ';
|
||||
fixture.detectChanges();
|
||||
hostComponent.setCode(' \n ');
|
||||
expect(getErrorMessage()).toMatch(/missing.$/);
|
||||
});
|
||||
});
|
||||
@ -190,12 +193,10 @@ describe('CodeComponent', () => {
|
||||
});
|
||||
|
||||
it('should have title', () => {
|
||||
fixture.detectChanges();
|
||||
expect(getButton().title).toBe('Copy code snippet');
|
||||
});
|
||||
|
||||
it('should have no aria-label by default', () => {
|
||||
fixture.detectChanges();
|
||||
expect(getButton().getAttribute('aria-label')).toBe('');
|
||||
});
|
||||
|
||||
@ -226,12 +227,11 @@ describe('CodeComponent', () => {
|
||||
const expectedCode = smallMultiLineCode.trim().replace(/</g, '<').replace(/>/g, '>');
|
||||
let actualCode;
|
||||
|
||||
hostComponent.code = smallMultiLineCode;
|
||||
hostComponent.setCode(smallMultiLineCode);
|
||||
|
||||
[false, true, 42].forEach(linenums => {
|
||||
hostComponent.linenums = linenums;
|
||||
fixture.detectChanges();
|
||||
codeComponent.ngOnChanges();
|
||||
getButton().click();
|
||||
actualCode = spy.calls.mostRecent().args[0];
|
||||
|
||||
@ -271,19 +271,29 @@ describe('CodeComponent', () => {
|
||||
@Component({
|
||||
selector: 'aio-host-comp',
|
||||
template: `
|
||||
<aio-code [code]="code" [language]="language"
|
||||
<aio-code [language]="language"
|
||||
[linenums]="linenums" [path]="path" [region]="region"
|
||||
[hideCopy]="hideCopy" [title]="title"></aio-code>
|
||||
`
|
||||
})
|
||||
class HostComponent {
|
||||
code = oneLineCode;
|
||||
class HostComponent implements AfterViewInit {
|
||||
hideCopy: boolean;
|
||||
language: string;
|
||||
linenums: boolean | number | string;
|
||||
path: string;
|
||||
region: string;
|
||||
title: string;
|
||||
|
||||
@ViewChild(CodeComponent) codeComponent: CodeComponent;
|
||||
|
||||
ngAfterViewInit() {
|
||||
this.setCode(oneLineCode);
|
||||
}
|
||||
|
||||
/** Changes the displayed code on the code component. */
|
||||
setCode(code: string) {
|
||||
this.codeComponent.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
class TestLogger {
|
191
aio/src/app/custom-elements/code/code.component.ts
Normal file
191
aio/src/app/custom-elements/code/code.component.ts
Normal file
@ -0,0 +1,191 @@
|
||||
import { Component, ElementRef, EventEmitter, Input, OnChanges, Output, ViewChild } from '@angular/core';
|
||||
import { Logger } from 'app/shared/logger.service';
|
||||
import { PrettyPrinter } from './pretty-printer.service';
|
||||
import { CopierService } from 'app/shared/copier.service';
|
||||
import { MatSnackBar } from '@angular/material/snack-bar';
|
||||
import { tap } from 'rxjs/operators';
|
||||
|
||||
/**
|
||||
* If linenums is not set, this is the default maximum number of lines that
|
||||
* an example can display without line numbers.
|
||||
*/
|
||||
const DEFAULT_LINE_NUMS_COUNT = 10;
|
||||
|
||||
/**
|
||||
* Formatted Code Block
|
||||
*
|
||||
* Pretty renders a code block, used in the docs and API reference by the code-example and
|
||||
* code-tabs embedded components.
|
||||
* It includes a "copy" button that will send the content to the clipboard when clicked
|
||||
*
|
||||
* Example usage:
|
||||
*
|
||||
* ```
|
||||
* <aio-code
|
||||
* [language]="ts"
|
||||
* [linenums]="true"
|
||||
* [path]="router/src/app/app.module.ts"
|
||||
* [region]="animations-module">
|
||||
* </aio-code>
|
||||
* ```
|
||||
*
|
||||
*
|
||||
* Renders code provided through the `updateCode` method.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'aio-code',
|
||||
template: `
|
||||
<pre class="prettyprint lang-{{language}}">
|
||||
<button *ngIf="!hideCopy" class="material-icons copy-button no-print"
|
||||
title="Copy code snippet"
|
||||
[attr.aria-label]="ariaLabel"
|
||||
(click)="doCopy()">
|
||||
<span aria-hidden="true">content_copy</span>
|
||||
</button>
|
||||
<code class="animated fadeIn" #codeContainer></code>
|
||||
</pre>
|
||||
`
|
||||
})
|
||||
export class CodeComponent implements OnChanges {
|
||||
ariaLabel = '';
|
||||
|
||||
/** The code to be copied when clicking the copy button, this should not be HTML encoded */
|
||||
private codeText: string;
|
||||
|
||||
/** Code that should be formatted with current inputs and displayed in the view. */
|
||||
set code(code: string) {
|
||||
this._code = code;
|
||||
|
||||
if (!this._code || !this._code.trim()) {
|
||||
this.showMissingCodeMessage();
|
||||
} else {
|
||||
this.formatDisplayedCode();
|
||||
}
|
||||
}
|
||||
get code(): string { return this._code; }
|
||||
_code: string;
|
||||
|
||||
/** Whether the copy button should be shown. */
|
||||
@Input() hideCopy: boolean;
|
||||
|
||||
/** Language to render the code (e.g. javascript, dart, typescript). */
|
||||
@Input() language: string;
|
||||
|
||||
/**
|
||||
* Whether to display line numbers:
|
||||
* - If false: hide
|
||||
* - If true: show
|
||||
* - If number: show but start at that number
|
||||
*/
|
||||
@Input() linenums: boolean | number | string;
|
||||
|
||||
/** Path to the source of the code. */
|
||||
@Input() path: string;
|
||||
|
||||
/** Region of the source of the code being displayed. */
|
||||
@Input() region: string;
|
||||
|
||||
/** Optional title to be displayed above the code. */
|
||||
@Input()
|
||||
set title(title: string) {
|
||||
this._title = title;
|
||||
this.ariaLabel = this.title ? `Copy code snippet from ${this.title}` : '';
|
||||
}
|
||||
get title(): string { return this._title; }
|
||||
private _title: string;
|
||||
|
||||
@Output() codeFormatted = new EventEmitter<void>();
|
||||
|
||||
/** The element in the template that will display the formatted code. */
|
||||
@ViewChild('codeContainer') codeContainer: ElementRef;
|
||||
|
||||
constructor(
|
||||
private snackbar: MatSnackBar,
|
||||
private pretty: PrettyPrinter,
|
||||
private copier: CopierService,
|
||||
private logger: Logger) {}
|
||||
|
||||
ngOnChanges() {
|
||||
// If some inputs have changed and there is code displayed, update the view with the latest
|
||||
// formatted code.
|
||||
if (this.code) {
|
||||
this.formatDisplayedCode();
|
||||
}
|
||||
}
|
||||
|
||||
private formatDisplayedCode() {
|
||||
const leftAlignedCode = leftAlign(this.code);
|
||||
this.setCodeHtml(leftAlignedCode); // start with unformatted code
|
||||
this.codeText = this.getCodeText(); // store the unformatted code as text (for copying)
|
||||
|
||||
this.pretty
|
||||
.formatCode(leftAlignedCode, this.language, this.getLinenums(leftAlignedCode))
|
||||
.pipe(tap(() => this.codeFormatted.emit()))
|
||||
.subscribe(c => this.setCodeHtml(c), err => { /* ignore failure to format */ }
|
||||
);
|
||||
}
|
||||
|
||||
/** Sets the message showing that the code could not be found. */
|
||||
private showMissingCodeMessage() {
|
||||
const src = this.path ? this.path + (this.region ? '#' + this.region : '') : '';
|
||||
const srcMsg = src ? ` for\n${src}` : '.';
|
||||
this.setCodeHtml(`<p class="code-missing">The code sample is missing${srcMsg}</p>`);
|
||||
}
|
||||
|
||||
/** Sets the innerHTML of the code container to the provided code string. */
|
||||
private setCodeHtml(formattedCode: string) {
|
||||
// **Security:** Code example content is provided by docs authors and as such its considered to
|
||||
// be safe for innerHTML purposes.
|
||||
this.codeContainer.nativeElement.innerHTML = formattedCode;
|
||||
}
|
||||
|
||||
/** Gets the textContent of the displayed code element. */
|
||||
private getCodeText() {
|
||||
// `prettify` may remove newlines, e.g. when `linenums` are on. Retrieve the content of the
|
||||
// container as text, before prettifying it.
|
||||
// We take the textContent because we don't want it to be HTML encoded.
|
||||
return this.codeContainer.nativeElement.textContent;
|
||||
}
|
||||
|
||||
/** Copies the code snippet to the user's clipboard. */
|
||||
doCopy() {
|
||||
const code = this.codeText;
|
||||
const successfullyCopied = this.copier.copyText(code);
|
||||
|
||||
if (successfullyCopied) {
|
||||
this.logger.log('Copied code to clipboard:', code);
|
||||
this.snackbar.open('Code Copied', '', { duration: 800 });
|
||||
} else {
|
||||
this.logger.error(new Error(`ERROR copying code to clipboard: "${code}"`));
|
||||
this.snackbar.open('Copy failed. Please try again!', '', { duration: 800 });
|
||||
}
|
||||
}
|
||||
|
||||
/** Gets the calculated value of linenums (boolean/number). */
|
||||
getLinenums(code: string) {
|
||||
const linenums =
|
||||
typeof this.linenums === 'boolean' ? this.linenums :
|
||||
this.linenums === 'true' ? true :
|
||||
this.linenums === 'false' ? false :
|
||||
typeof this.linenums === 'string' ? parseInt(this.linenums, 10) :
|
||||
this.linenums;
|
||||
|
||||
// if no linenums, enable line numbers if more than one line
|
||||
return linenums == null || isNaN(linenums as number) ?
|
||||
(code.match(/\n/g) || []).length > DEFAULT_LINE_NUMS_COUNT : linenums;
|
||||
}
|
||||
}
|
||||
|
||||
function leftAlign(text: string): string {
|
||||
let indent = Number.MAX_VALUE;
|
||||
|
||||
const lines = text.split('\n');
|
||||
lines.forEach(line => {
|
||||
const lineIndent = line.search(/\S/);
|
||||
if (lineIndent !== -1) {
|
||||
indent = Math.min(lineIndent, indent);
|
||||
}
|
||||
});
|
||||
|
||||
return lines.map(line => line.substr(indent)).join('\n').trim();
|
||||
}
|
15
aio/src/app/custom-elements/code/code.module.ts
Normal file
15
aio/src/app/custom-elements/code/code.module.ts
Normal file
@ -0,0 +1,15 @@
|
||||
import { NgModule } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { CodeComponent } from './code.component';
|
||||
import { MatSnackBarModule } from '@angular/material';
|
||||
import { PrettyPrinter } from './pretty-printer.service';
|
||||
import { CopierService } from 'app/shared/copier.service';
|
||||
|
||||
@NgModule({
|
||||
imports: [ CommonModule, MatSnackBarModule ],
|
||||
declarations: [ CodeComponent ],
|
||||
entryComponents: [ CodeComponent ],
|
||||
exports: [ CodeComponent ],
|
||||
providers: [ PrettyPrinter, CopierService ]
|
||||
})
|
||||
export class CodeModule { }
|
@ -1,9 +1,7 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
|
||||
import { Observable } from 'rxjs/Observable';
|
||||
import { fromPromise } from 'rxjs/observable/fromPromise';
|
||||
import 'rxjs/add/operator/map';
|
||||
import 'rxjs/add/operator/first';
|
||||
import { from as fromPromise, Observable } from 'rxjs';
|
||||
import { first, map, share } from 'rxjs/operators';
|
||||
|
||||
import { Logger } from 'app/shared/logger.service';
|
||||
|
||||
@ -22,7 +20,7 @@ export class PrettyPrinter {
|
||||
private prettyPrintOne: Observable<PrettyPrintOne>;
|
||||
|
||||
constructor(private logger: Logger) {
|
||||
this.prettyPrintOne = fromPromise(this.getPrettyPrintOne()).share();
|
||||
this.prettyPrintOne = fromPromise(this.getPrettyPrintOne()).pipe(share());
|
||||
}
|
||||
|
||||
private getPrettyPrintOne(): Promise<PrettyPrintOne> {
|
||||
@ -51,15 +49,17 @@ export class PrettyPrinter {
|
||||
* @returns Observable<string> - Observable of formatted code
|
||||
*/
|
||||
formatCode(code: string, language?: string, linenums?: number | boolean) {
|
||||
return this.prettyPrintOne.map(ppo => {
|
||||
try {
|
||||
return ppo(code, language, linenums);
|
||||
} catch (err) {
|
||||
const msg = `Could not format code that begins '${code.substr(0, 50)}...'.`;
|
||||
console.error(msg, err);
|
||||
throw new Error(msg);
|
||||
}
|
||||
})
|
||||
.first(); // complete immediately
|
||||
return this.prettyPrintOne.pipe(
|
||||
map(ppo => {
|
||||
try {
|
||||
return ppo(code, language, linenums);
|
||||
} catch (err) {
|
||||
const msg = `Could not format code that begins '${code.substr(0, 50)}...'.`;
|
||||
console.error(msg, err);
|
||||
throw new Error(msg);
|
||||
}
|
||||
}),
|
||||
first(), // complete immediately
|
||||
);
|
||||
}
|
||||
}
|
@ -1,6 +1,6 @@
|
||||
import { ReflectiveInjector } from '@angular/core';
|
||||
|
||||
import { of } from 'rxjs/observable/of';
|
||||
import { of } from 'rxjs';
|
||||
|
||||
import { ContributorGroup } from './contributors.model';
|
||||
import { ContributorListComponent } from './contributor-list.component';
|
@ -0,0 +1,16 @@
|
||||
import { NgModule, Type } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { ContributorListComponent } from './contributor-list.component';
|
||||
import { ContributorService } from './contributor.service';
|
||||
import { ContributorComponent } from './contributor.component';
|
||||
import { WithCustomElementComponent } from '../element-registry';
|
||||
|
||||
@NgModule({
|
||||
imports: [ CommonModule ],
|
||||
declarations: [ ContributorListComponent, ContributorComponent ],
|
||||
entryComponents: [ ContributorListComponent ],
|
||||
providers: [ ContributorService ]
|
||||
})
|
||||
export class ContributorListModule implements WithCustomElementComponent {
|
||||
customElementComponent: Type<any> = ContributorListComponent;
|
||||
}
|
@ -1,11 +1,12 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
|
||||
import { Observable } from 'rxjs/Observable';
|
||||
import 'rxjs/add/operator/map';
|
||||
import 'rxjs/add/operator/publishLast';
|
||||
import { ConnectableObservable, Observable } from 'rxjs';
|
||||
import { map, publishLast } from 'rxjs/operators';
|
||||
|
||||
import { Contributor, ContributorGroup } from './contributors.model';
|
||||
|
||||
// TODO(andrewjs): Look into changing this so that we don't import the service just to get the const
|
||||
import { CONTENT_URL_PREFIX } from 'app/documents/document.service';
|
||||
|
||||
const contributorsPath = CONTENT_URL_PREFIX + 'contributors.json';
|
||||
@ -20,9 +21,9 @@ export class ContributorService {
|
||||
}
|
||||
|
||||
private getContributors() {
|
||||
const contributors = this.http.get<{[key: string]: Contributor}>(contributorsPath)
|
||||
const contributors = this.http.get<{[key: string]: Contributor}>(contributorsPath).pipe(
|
||||
// Create group map
|
||||
.map(contribs => {
|
||||
map(contribs => {
|
||||
const contribMap: { [name: string]: Contributor[]} = {};
|
||||
Object.keys(contribs).forEach(key => {
|
||||
const contributor = contribs[key];
|
||||
@ -36,10 +37,10 @@ export class ContributorService {
|
||||
});
|
||||
|
||||
return contribMap;
|
||||
})
|
||||
}),
|
||||
|
||||
// Flatten group map into sorted group array of sorted contributors
|
||||
.map(cmap => {
|
||||
map(cmap => {
|
||||
return Object.keys(cmap).map(key => {
|
||||
const order = knownGroups.indexOf(key);
|
||||
return {
|
||||
@ -49,10 +50,12 @@ export class ContributorService {
|
||||
} as ContributorGroup;
|
||||
})
|
||||
.sort(compareGroups);
|
||||
})
|
||||
.publishLast();
|
||||
}),
|
||||
|
||||
contributors.connect();
|
||||
publishLast(),
|
||||
);
|
||||
|
||||
(contributors as ConnectableObservable<ContributorGroup[]>).connect();
|
||||
return contributors;
|
||||
}
|
||||
}
|
@ -2,14 +2,11 @@
|
||||
import { Component } from '@angular/core';
|
||||
import { LocationService } from 'app/shared/location.service';
|
||||
|
||||
/**
|
||||
* A simple embedded component that displays the current location path
|
||||
*/
|
||||
/** Renders the current location path. */
|
||||
@Component({
|
||||
selector: 'current-location',
|
||||
template: '{{ location.currentPath | async }}'
|
||||
})
|
||||
export class CurrentLocationComponent {
|
||||
constructor(public location: LocationService) {
|
||||
}
|
||||
constructor(public location: LocationService) { }
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
import { NgModule, Type } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { CurrentLocationComponent } from './current-location.component';
|
||||
import { WithCustomElementComponent } from '../element-registry';
|
||||
|
||||
@NgModule({
|
||||
imports: [ CommonModule ],
|
||||
declarations: [ CurrentLocationComponent ],
|
||||
entryComponents: [ CurrentLocationComponent ]
|
||||
})
|
||||
export class CurrentLocationModule implements WithCustomElementComponent {
|
||||
customElementComponent: Type<any> = CurrentLocationComponent;
|
||||
}
|
22
aio/src/app/custom-elements/custom-elements.module.ts
Normal file
22
aio/src/app/custom-elements/custom-elements.module.ts
Normal file
@ -0,0 +1,22 @@
|
||||
import { NgModule, NgModuleFactoryLoader, SystemJsNgModuleLoader } from '@angular/core';
|
||||
import { ROUTES} from '@angular/router';
|
||||
import { ElementsLoader } from './elements-loader';
|
||||
import {
|
||||
ELEMENT_MODULE_PATHS,
|
||||
ELEMENT_MODULE_PATHS_AS_ROUTES,
|
||||
ELEMENT_MODULE_PATHS_TOKEN
|
||||
} from './element-registry';
|
||||
|
||||
@NgModule({
|
||||
providers: [
|
||||
ElementsLoader,
|
||||
{ provide: NgModuleFactoryLoader, useClass: SystemJsNgModuleLoader },
|
||||
{ provide: ELEMENT_MODULE_PATHS_TOKEN, useValue: ELEMENT_MODULE_PATHS },
|
||||
|
||||
// Providing these routes as a signal to the build system that these modules should be
|
||||
// registered as lazy-loadable.
|
||||
// TODO(andrewjs): Provide first-class support for providing this.
|
||||
{ provide: ROUTES, useValue: ELEMENT_MODULE_PATHS_AS_ROUTES, multi: true },
|
||||
],
|
||||
})
|
||||
export class CustomElementsModule { }
|
64
aio/src/app/custom-elements/element-registry.ts
Normal file
64
aio/src/app/custom-elements/element-registry.ts
Normal file
@ -0,0 +1,64 @@
|
||||
import { InjectionToken, Type } from '@angular/core';
|
||||
|
||||
// Modules containing custom elements must be set up as lazy-loaded routes (loadChildren)
|
||||
// TODO(andrewjs): This is a hack, Angular should have first-class support for preparing a module
|
||||
// that contains custom elements.
|
||||
export const ELEMENT_MODULE_PATHS_AS_ROUTES = [
|
||||
{
|
||||
selector: 'aio-announcement-bar',
|
||||
loadChildren: './announcement-bar/announcement-bar.module#AnnouncementBarModule'
|
||||
},
|
||||
{
|
||||
selector: 'aio-api-list',
|
||||
loadChildren: './api/api-list.module#ApiListModule'
|
||||
},
|
||||
{
|
||||
selector: 'live-example',
|
||||
loadChildren: './live-example/live-example.module#LiveExampleModule'
|
||||
},
|
||||
{
|
||||
selector: 'aio-file-not-found-search',
|
||||
loadChildren: './search/file-not-found-search.module#FileNotFoundSearchModule'
|
||||
},
|
||||
{
|
||||
selector: 'aio-resource-list',
|
||||
loadChildren: './resource/resource-list.module#ResourceListModule'
|
||||
},
|
||||
{
|
||||
selector: 'current-location',
|
||||
loadChildren: './current-location/current-location.module#CurrentLocationModule'
|
||||
},
|
||||
{
|
||||
selector: 'aio-contributor-list',
|
||||
loadChildren: './contributor/contributor-list.module#ContributorListModule'
|
||||
},
|
||||
{
|
||||
selector: 'code-tabs',
|
||||
loadChildren: './code/code-tabs.module#CodeTabsModule'
|
||||
},
|
||||
{
|
||||
selector: 'code-example',
|
||||
loadChildren: './code/code-example.module#CodeExampleModule'
|
||||
},
|
||||
{
|
||||
selector: 'expandable-section',
|
||||
loadChildren: './expandable-section/expandable-section.module#ExpandableSectionModule'
|
||||
}
|
||||
];
|
||||
|
||||
/**
|
||||
* Interface expected to be implemented by all modules that declare a component that can be used as
|
||||
* a custom element.
|
||||
*/
|
||||
export interface WithCustomElementComponent {
|
||||
customElementComponent: Type<any>;
|
||||
}
|
||||
|
||||
/** Injection token to provide the element path modules. */
|
||||
export const ELEMENT_MODULE_PATHS_TOKEN = new InjectionToken('aio/elements-map');
|
||||
|
||||
/** Map of possible custom element selectors to their lazy-loadable module paths. */
|
||||
export const ELEMENT_MODULE_PATHS = new Map<string, string>();
|
||||
ELEMENT_MODULE_PATHS_AS_ROUTES.forEach(route => {
|
||||
ELEMENT_MODULE_PATHS.set(route.selector, route.loadChildren);
|
||||
});
|
170
aio/src/app/custom-elements/elements-loader.spec.ts
Normal file
170
aio/src/app/custom-elements/elements-loader.spec.ts
Normal file
@ -0,0 +1,170 @@
|
||||
import {
|
||||
ComponentFactory,
|
||||
ComponentFactoryResolver, ComponentRef, Injector, NgModuleFactory, NgModuleFactoryLoader,
|
||||
NgModuleRef,
|
||||
Type
|
||||
} from '@angular/core';
|
||||
import {TestBed, fakeAsync, tick} from '@angular/core/testing';
|
||||
|
||||
import { ElementsLoader } from './elements-loader';
|
||||
import { ELEMENT_MODULE_PATHS_TOKEN, WithCustomElementComponent } from './element-registry';
|
||||
|
||||
class FakeComponentFactory extends ComponentFactory<any> {
|
||||
selector: string;
|
||||
componentType: Type<any>;
|
||||
ngContentSelectors: string[];
|
||||
inputs = [{propName: this.identifyingInput, templateName: this.identifyingInput}];
|
||||
outputs = [];
|
||||
|
||||
constructor(private identifyingInput: string) { super(); }
|
||||
|
||||
create(injector: Injector,
|
||||
projectableNodes?: any[][],
|
||||
rootSelectorOrNode?: string | any,
|
||||
ngModule?: NgModuleRef<any>): ComponentRef<any> {
|
||||
return (jasmine.createSpy('ComponentRef') as any) as ComponentRef<any>;
|
||||
};
|
||||
}
|
||||
|
||||
const FAKE_COMPONENT_FACTORIES = new Map([
|
||||
['element-a-module-path', new FakeComponentFactory('element-a-input')],
|
||||
['element-b-module-path', new FakeComponentFactory('element-b-input')],
|
||||
]);
|
||||
|
||||
describe('ElementsLoader', () => {
|
||||
let elementsLoader: ElementsLoader;
|
||||
let actualCustomElementsDefine;
|
||||
let fakeCustomElementsDefine;
|
||||
|
||||
// ElementsLoader uses the window's customElements API. Provide a fake for this test.
|
||||
beforeEach(() => {
|
||||
actualCustomElementsDefine = window.customElements.define;
|
||||
|
||||
fakeCustomElementsDefine = jasmine.createSpy('define');
|
||||
|
||||
window.customElements.define = fakeCustomElementsDefine;
|
||||
});
|
||||
afterEach(() => {
|
||||
window.customElements.define = actualCustomElementsDefine;
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
const injector = TestBed.configureTestingModule({
|
||||
providers: [
|
||||
ElementsLoader,
|
||||
{ provide: NgModuleFactoryLoader, useClass: FakeModuleFactoryLoader },
|
||||
{ provide: ELEMENT_MODULE_PATHS_TOKEN, useValue: new Map([
|
||||
['element-a-selector', 'element-a-module-path'],
|
||||
['element-b-selector', 'element-b-module-path']
|
||||
])},
|
||||
]
|
||||
});
|
||||
|
||||
elementsLoader = injector.get(ElementsLoader);
|
||||
});
|
||||
|
||||
it('should be able to register an element', fakeAsync(() => {
|
||||
// Verify that the elements loader considered `element-a-selector` to be unregistered.
|
||||
expect(elementsLoader.elementsToLoad.has('element-a-selector')).toBeTruthy();
|
||||
|
||||
const hostEl = document.createElement('div');
|
||||
hostEl.innerHTML = `<element-a-selector></element-a-selector>`;
|
||||
|
||||
elementsLoader.loadContainingCustomElements(hostEl);
|
||||
tick();
|
||||
|
||||
const defineArgs = fakeCustomElementsDefine.calls.argsFor(0);
|
||||
expect(defineArgs[0]).toBe('element-a-selector');
|
||||
|
||||
// Verify the right component was loaded/created
|
||||
expect(defineArgs[1].observedAttributes[0]).toBe('element-a-input');
|
||||
|
||||
expect(elementsLoader.elementsToLoad.has('element-a-selector')).toBeFalsy();
|
||||
}));
|
||||
|
||||
it('should be able to register multiple elements', fakeAsync(() => {
|
||||
// Verify that the elements loader considered `element-a-selector` to be unregistered.
|
||||
expect(elementsLoader.elementsToLoad.has('element-a-selector')).toBeTruthy();
|
||||
|
||||
const hostEl = document.createElement('div');
|
||||
hostEl.innerHTML = `
|
||||
<element-a-selector></element-a-selector>
|
||||
<element-b-selector></element-b-selector>
|
||||
`;
|
||||
|
||||
elementsLoader.loadContainingCustomElements(hostEl);
|
||||
tick();
|
||||
|
||||
const defineElementA = fakeCustomElementsDefine.calls.argsFor(0);
|
||||
expect(defineElementA[0]).toBe('element-a-selector');
|
||||
expect(defineElementA[1].observedAttributes[0]).toBe('element-a-input');
|
||||
expect(elementsLoader.elementsToLoad.has('element-a-selector')).toBeFalsy();
|
||||
|
||||
const defineElementB = fakeCustomElementsDefine.calls.argsFor(1);
|
||||
expect(defineElementB[0]).toBe('element-b-selector');
|
||||
expect(defineElementB[1].observedAttributes[0]).toBe('element-b-input');
|
||||
expect(elementsLoader.elementsToLoad.has('element-b-selector')).toBeFalsy();
|
||||
}));
|
||||
|
||||
it('should only register an element one time', fakeAsync(() => {
|
||||
const hostEl = document.createElement('div');
|
||||
hostEl.innerHTML = `<element-a-selector></element-a-selector>`;
|
||||
|
||||
elementsLoader.loadContainingCustomElements(hostEl);
|
||||
tick(); // Tick for the module factory loader's async `load` function
|
||||
|
||||
// Call again to to check how many times customElements.define was called.
|
||||
elementsLoader.loadContainingCustomElements(hostEl);
|
||||
tick(); // Tick for the module factory loader's async `load` function
|
||||
|
||||
// Should have only been called once, since the second load would not query for element-a
|
||||
expect(window.customElements.define).toHaveBeenCalledTimes(1);
|
||||
}));
|
||||
});
|
||||
|
||||
// TEST CLASSES/HELPERS
|
||||
|
||||
class FakeCustomElementModule implements WithCustomElementComponent {
|
||||
customElementComponent: Type<any>;
|
||||
}
|
||||
|
||||
class FakeComponentFactoryResolver extends ComponentFactoryResolver {
|
||||
constructor(private modulePath) { super(); }
|
||||
|
||||
resolveComponentFactory(component: Type<any>): ComponentFactory<any> {
|
||||
return FAKE_COMPONENT_FACTORIES.get(this.modulePath)!;
|
||||
}
|
||||
}
|
||||
|
||||
class FakeModuleRef extends NgModuleRef<WithCustomElementComponent> {
|
||||
injector = jasmine.createSpyObj('injector', ['get']);
|
||||
componentFactoryResolver = new FakeComponentFactoryResolver(this.modulePath);
|
||||
instance: WithCustomElementComponent = new FakeCustomElementModule();
|
||||
|
||||
constructor(private modulePath) {
|
||||
super();
|
||||
|
||||
this.injector.get.and.returnValue(this.componentFactoryResolver);
|
||||
}
|
||||
|
||||
destroy() {}
|
||||
onDestroy(callback: () => void) {}
|
||||
}
|
||||
|
||||
class FakeModuleFactory extends NgModuleFactory<any> {
|
||||
moduleType: Type<any>;
|
||||
moduleRefToCreate = new FakeModuleRef(this.modulePath);
|
||||
|
||||
constructor(private modulePath) { super(); }
|
||||
|
||||
create(parentInjector: Injector | null): NgModuleRef<any> {
|
||||
return this.moduleRefToCreate;
|
||||
}
|
||||
}
|
||||
|
||||
class FakeModuleFactoryLoader extends NgModuleFactoryLoader {
|
||||
load(modulePath: string): Promise<NgModuleFactory<any>> {
|
||||
const fakeModuleFactory = new FakeModuleFactory(modulePath);
|
||||
return Promise.resolve(fakeModuleFactory);
|
||||
}
|
||||
}
|
54
aio/src/app/custom-elements/elements-loader.ts
Normal file
54
aio/src/app/custom-elements/elements-loader.ts
Normal file
@ -0,0 +1,54 @@
|
||||
import {
|
||||
Inject,
|
||||
Injectable,
|
||||
NgModuleFactoryLoader,
|
||||
NgModuleRef,
|
||||
} from '@angular/core';
|
||||
import { ELEMENT_MODULE_PATHS_TOKEN } from './element-registry';
|
||||
import { from as fromPromise, Observable, of } from 'rxjs';
|
||||
import { createCustomElement } from '@angular/elements';
|
||||
|
||||
@Injectable()
|
||||
export class ElementsLoader {
|
||||
/** Map of unregistered custom elements and their respective module paths to load. */
|
||||
elementsToLoad: Map<string, string>;
|
||||
|
||||
constructor(private moduleFactoryLoader: NgModuleFactoryLoader,
|
||||
private moduleRef: NgModuleRef<any>,
|
||||
@Inject(ELEMENT_MODULE_PATHS_TOKEN) elementModulePaths) {
|
||||
this.elementsToLoad = new Map(elementModulePaths);
|
||||
}
|
||||
|
||||
/**
|
||||
* Queries the provided element for any custom elements that have not yet been registered with
|
||||
* the browser. Custom elements that are registered will be removed from the list of unregistered
|
||||
* elements so that they will not be queried in subsequent calls.
|
||||
*/
|
||||
loadContainingCustomElements(element: HTMLElement): Observable<void> {
|
||||
const selectors: any[] = Array.from(this.elementsToLoad.keys())
|
||||
.filter(s => element.querySelector(s));
|
||||
|
||||
if (!selectors.length) { return of(undefined); }
|
||||
|
||||
// Returns observable that completes when all discovered elements have been registered.
|
||||
return fromPromise(Promise.all(selectors.map(s => this.register(s))).then(result => undefined));
|
||||
}
|
||||
|
||||
/** Registers the custom element defined on the WithCustomElement module factory. */
|
||||
private register(selector: string) {
|
||||
const modulePath = this.elementsToLoad.get(selector)!;
|
||||
return this.moduleFactoryLoader.load(modulePath).then(elementModuleFactory => {
|
||||
if (!this.elementsToLoad.has(selector)) { return; }
|
||||
|
||||
const elementModuleRef = elementModuleFactory.create(this.moduleRef.injector);
|
||||
const CustomElementComponent = elementModuleRef.instance.customElementComponent;
|
||||
const CustomElement =
|
||||
createCustomElement(CustomElementComponent, {injector: elementModuleRef.injector});
|
||||
|
||||
customElements!.define(selector, CustomElement);
|
||||
this.elementsToLoad.delete(selector);
|
||||
|
||||
return customElements.whenDefined(selector);
|
||||
});
|
||||
}
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
<mat-expansion-panel style="background: inherit">
|
||||
<mat-expansion-panel-header>
|
||||
{{title}}
|
||||
</mat-expansion-panel-header>
|
||||
|
||||
<ng-content></ng-content>
|
||||
</mat-expansion-panel>
|
@ -0,0 +1,11 @@
|
||||
/* tslint:disable component-selector */
|
||||
import {Component, Input} from '@angular/core';
|
||||
|
||||
/** Custom element wrapper for the material expansion panel with a title input. */
|
||||
@Component({
|
||||
selector: 'aio-expandable-section',
|
||||
templateUrl: 'expandable-section.component.html',
|
||||
})
|
||||
export class ExpandableSectionComponent {
|
||||
@Input() title;
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
import { NgModule, Type } from '@angular/core';
|
||||
import { ExpandableSectionComponent } from './expandable-section.component';
|
||||
import { WithCustomElementComponent } from '../element-registry';
|
||||
import { MatExpansionModule } from '@angular/material';
|
||||
|
||||
@NgModule({
|
||||
imports: [ MatExpansionModule ],
|
||||
declarations: [ ExpandableSectionComponent, ],
|
||||
entryComponents: [ ExpandableSectionComponent ]
|
||||
})
|
||||
export class ExpandableSectionModule implements WithCustomElementComponent {
|
||||
customElementComponent: Type<any> = ExpandableSectionComponent;
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user