Compare commits

..

141 Commits
6.0.6 ... 6.0.x

Author SHA1 Message Date
0560751381 fix(core): stop reusing provider definitions across NgModuleRef instances (#25088)
Fixes #25018.

Instantiating a NgModuleRef from NgModuleFactory reuses the NgModuleDefinition if it is already present. However the NgModuleDefinition has a providers array which modified when tree shakable providers are instantiated. This corrupts the provider definitions the next time the same factory is used to create a new NgModuleRef - Two provider definitions can end up with the same index and the injector could potentially return a completely wrong object for a provider token.

This scenario is more likely on the server where the same NgModuleFactory is reused across requests.

The fix clones the cached NgModuleDefinition so that any tree shakable providers added later do not affect the cached copy.

PR Close #25022

PR Close #25088
2018-07-25 10:16:13 -07:00
e32c1b692a docs(animations): typo fix in the comments (#22652)
PR Close #22652
2018-07-25 10:13:19 -07:00
ae7b96ba13 docs: refactor style guide example 03-06 (#24996)
docs: refactor style guide example 03-06


docs: refactor style guide example 03-06


docs: refactor style guide example 03-06


PR Close #24996
2018-07-25 08:04:13 -07:00
01b6aad309 Revert "docs: refactor style guide example 03-06 (#24996)"
This reverts commit 93d325ccd5.
2018-07-24 22:12:19 -07:00
40cdab2225 docs: refactor ngmodules example (#25072)
PR Close #25072
2018-07-24 21:03:39 -07:00
a38127fb47 docs: replace angular/http with HttpClient (#25068)
PR Close #25068
2018-07-24 20:54:45 -07:00
cd811da672 docs: replace angular/http with HttpClient (#25066)
PR Close #25066
2018-07-24 20:51:50 -07:00
76fb905916 docs: replaced old angular/http example (#25065)
PR Close #25065
2018-07-24 20:47:20 -07:00
93d325ccd5 docs: refactor style guide example 03-06 (#24996)
PR Close #24996
2018-07-24 20:46:08 -07:00
c7d147eb96 Revert "build: update to newer circleCI bazel remote cache proxy (#25054)" (#25076)
This reverts commit d6016f1d1d.

PR Close #25076
2018-07-24 16:05:59 -07:00
70fb65fd00 docs(aio): cleanup aalert, callout, subsection use and author style (#24986)
PR Close #24986
2018-07-24 08:22:14 -07:00
10863e5817 build: update to newer circleCI bazel remote cache proxy (#25054)
it fixes the error we currently get on CI

PR Close #25054
2018-07-24 08:20:28 -07:00
5f680d4d6d refactor(common): fix a merge error (#25053)
A `keyvalue-pipe` was inadvertently pulled in  When merging #25028 (commit
6eca36756). This pipe is NOT in the patch branch and the test fails.

This commit remove the faulty spec.

PR Close #25053
2018-07-23 20:12:19 -07:00
6eca36756a docs: tests for number/percent/currency pipe (#25028)
Will avoid errors in examples like the one fixed in #24661

Closes #25028
2018-07-23 13:17:31 -07:00
060867dcc4 build: Fix windows tests (#24927)
closes #24927
2018-07-23 11:53:19 -07:00
4d840cba59 docs: technical review incorporated (#24744)
closes #24744
2018-07-23 11:46:16 -07:00
0222b5846b docs: add api doc to commonly queried elements 2018-07-23 11:45:31 -07:00
ac52e1a6b6 build(docs-infra): ensure all API headings are sentence cased (#24949)
Closes #24880

PR Close #24949
2018-07-23 08:43:08 -07:00
7f3a5ec741 docs: square odds example in rxjs guide (#24947)
Added argument type to filter function of rxjs. Fixed the
return value of filtering of odd numbers

PR Close #24947
2018-07-23 08:41:58 -07:00
ac7658e1b9 docs: fix multicasting example in observable guide (#24911)
PR Close #24911
2018-07-23 08:40:46 -07:00
dc0340c79e docs: add Truly-UI to resources (#24615)
PR Close #24615
2018-07-23 08:39:35 -07:00
6a74ef0fbc docs: fix instructions for switching directories (#24439)
docs: fix instructions for switching directories


PR Close #24439
2018-07-23 08:38:10 -07:00
68df0d2c26 docs: update rxjs link to version 6 (#24269)
PR Close #24269
2018-07-23 08:36:51 -07:00
d3656bcecc docs: refactor style guide example 01-01 (#22738)
docs: refactor style guide example 01-01


PR Close #22738
2018-07-23 08:35:38 -07:00
4834fdaf59 fix(service-worker): don't include sourceMappingURL in ngsw-worker (#24877)
Fixes #23596

PR Close #24877
2018-07-20 11:49:46 -07:00
f2aeb703de docs: fix bad link (#24825)
PR Close #24825
2018-07-20 11:34:39 -07:00
5a1ca35bc4 docs: remove closing parenthesis from provides guide (#24935)
PR Close #24935
2018-07-20 11:07:54 -07:00
2a5a05b28b fix(docs-infra): fix table header layout in API pages (#24919)
PR Close #24919
2018-07-20 10:48:43 -07:00
4a29100ac8 test(platform-webworker): avoid flakes due to existing PlatformRef (#24916)
PR Close #24916
2018-07-20 10:47:17 -07:00
39afb01510 docs: update i18n with requested changes (#24875)
use more general project name in code example

PR Close #24875
2018-07-20 10:36:13 -07:00
7229899396 docs: update i18n doc regarding aot compilation (#24875)
Add missing lines to code example to allow using ng serve with custom i18n configurations.

PR Close #24875
2018-07-20 10:36:13 -07:00
740ab7cdcf build(docs-infra): add support for examples of type elements (#24840)
Examples using `@angular/elements` need to transpile to es2015 for
Custom Elements to work (on browsers that natively support them).

Alternatively, a polyfill would need to be loaded. For now, changing the
transpilation target to es2015 is the simplest solution.

PR Close #24840
2018-07-20 10:34:48 -07:00
e22abb4d98 docs: add e2e tests for elements example (#24840)
PR Close #24840
2018-07-20 10:34:48 -07:00
a5f100947a docs: fix elements example (#24840)
PR Close #24840
2018-07-20 10:34:48 -07:00
731ceee440 docs: refactor elements example (#24840)
This makes the closing behavior more deterministic, which makes it
easier to be e2e-tested.

PR Close #24840
2018-07-20 10:34:48 -07:00
7a87680710 docs: clean up elements example (indentation, import order, etc) (#24840)
PR Close #24840
2018-07-20 10:34:47 -07:00
ae0fce613f docs: more info on currency digits (#24661)
Adds an example of using the `currency` pipe with a currency that has no cents like CLP,
which will format the amount with no digits if `digitsInfo` is not provided:

    <!-- outputs CA$14.00 -->
    {{ 14 | currency:'CAD' }}
    <!-- outputs CLP14 -->
    {{ 14 | currency:'CLP' }}

Amends the docs, adds an example and fix an error with a current example.

PR Close #24661
2018-07-20 10:33:07 -07:00
422de27601 docs: Add notes on manual sanitization to security guide (#24176)
Some users have remarked that we don't explain how to manually call
sanitization, so add a few lines on that.

PR Close #24176
2018-07-20 10:27:12 -07:00
28de0c7cb9 ci: remove Tina from pullaprove (#25006)
She has been removed as a collaborator to the project and pullaprove rejects
this config file which still lists her name.

PR Close #25006
2018-07-20 10:25:52 -07:00
6b32622e18 docs: add new Reactive Forms guide (#24578)
PR Close #24578
2018-07-19 13:46:31 -04:00
6731c3daba docs: fix typo in user input guide (#22630)
PR Close #22630
2018-07-18 14:04:10 -04:00
0cbef9a073 docs: typos in directives docs (#24665)
Fixes some typos introduced by #23902

PR Close #24665
2018-07-17 16:45:18 -04:00
e97d961234 fix(compiler): i18n_extractor now outputs the correct source file name (#24885)
for non-inline templates

- Non-inline templates used to ouput the path to the component TS file
instead of the path to the original HTML file.
- Inline templates keep the same behavior.

Fixes #24884

PR Close #24885
2018-07-16 16:09:01 -04:00
d42a6623fb build: disable IE web worker tests (#24908)
Travis (saucelabs) has been super flaky when running IE
web worker tests lately. This patch temporarily disables
these tests on IE (not edge) until things get more stable.

PR Close #24908
2018-07-16 16:07:57 -04:00
1f163cd1d6 feat(docs-infra): enable filtering by package on API list page (#24631)
PR Close #24631
2018-07-13 19:45:55 -04:00
6d690b5daa build(docs-infra): implement the 'package' API template (#24631)
PR Close #24631
2018-07-13 19:45:55 -04:00
15df5f749a build: update to Bazel 0.15 (#24841)
PR Close #24841
2018-07-13 15:05:17 -04:00
e295206965 docs: update component styles doc regarding relative URL (#24471)
Update the documentation to match the CLI mechanics regarding relative URL in link tags.
docs: update info on stylesheet location for CLI


PR Close #24471
2018-07-12 16:44:01 -04:00
0e7501b47a build: fix windows scripts (#23121)
The `packages/core/src/animation/dsl.ts` symlink ws removed in #22692,
so `create-/remove-symlinks.sh` scripts for Windows should not try to
"fix" it.

PR Close #23121
2018-07-12 16:42:56 -04:00
6bf8aefe7a docs(aio): Add Angular Training to list of training companies (#23907)
PR Close #23907
2018-07-12 16:39:56 -04:00
43baa2388f docs(forms): update form builder API reference (#24693)
PR Close #24693
2018-07-12 16:38:26 -04:00
48415ed6f0 build: update packages/core/test/bundling/todo/bundle.golden_symbols.json (#24816)
PR Close #24816
2018-07-12 16:31:22 -04:00
002ac471da docs: fix typo in component architecture guide (#24832)
Change the sentence from 'this tells Angular how provide ...' to 'this tells Angular how to provide ...'. The current sentence does not make grammatical sense.

PR Close #24832
2018-07-12 14:31:28 -04:00
9e45589085 release: cut the v6.0.9 release 2018-07-11 14:34:14 -07:00
3c93d07124 fix(common): format fractional seconds (#24844)
fix a bug introduced in #24831

PR Close #24844
2018-07-11 14:32:33 -07:00
024aba075c release: cut the v6.0.8 release 2018-07-11 13:43:59 -07:00
a86d038875 docs(forms): update API reference for form validators (#24734)
PR Close #24734
2018-07-10 18:52:40 -07:00
bc8a93e842 docs(forms): added missing backtick (#24451)
Fixed trivial markdown problem with a missing backtick.

PR Close #24451
2018-07-10 18:51:09 -07:00
4c18f637ae docs: unified string chaining (#22735)
PR Close #22735
2018-07-10 18:50:45 -07:00
fc189b2577 docs(aio): unified string chaining (#22735)
PR Close #22735
2018-07-10 18:50:45 -07:00
778ddb257a docs: fix incorrect forms selector references (#22631)
PR Close #22631
2018-07-10 18:50:18 -07:00
2d4f4b5d12 fix(router): add ability to recover from malformed url (#23283)
Fixes #21468

PR Close #23283
2018-07-10 18:48:53 -07:00
912742f1ca docs: fix typos referencing inline component styles (#22557)
PR Close #22557
2018-07-10 18:48:30 -07:00
0746485136 fix(common): do not round factional seconds (#24831)
fixes #24384

PR Close #24831
2018-07-10 18:48:06 -07:00
265489518e build: update to latest nodejs bazel rules (#24817)
PR Close #24817
2018-07-10 18:47:40 -07:00
00dd566b47 docs: correct project definition (#24807)
PR Close #24807
2018-07-10 18:47:20 -07:00
59fd91d785 Revert "build: make internal-angular karma reporter compatible with latest karma (#24803)" (#24809)
This reverts commit 98c509fecb.
Part of reverting PR #24803 on branch `6.0.x`, because that PR is a
follow-up to PR #19904, which was only merged into master.

PR Close #24809
2018-07-10 15:00:42 -07:00
56712aa771 Revert "build: remove unnecessary internal-angular karma reporter (#24803)" (#24809)
This reverts commit d7c4898081.
Part of reverting PR #24803 on branch `6.0.x`, because that PR is a
follow-up to PR #19904, which was only merged into master.

PR Close #24809
2018-07-10 15:00:42 -07:00
529e4b1565 docs: fix typo in Universal guide (#24812)
PR Close #24812
2018-07-10 11:12:45 -07:00
9ff4617956 docs: add tree-shakable providers (#24481)
PR Close #24481
2018-07-10 11:12:08 -07:00
8887d75723 docs: clarify wording in architecture overview (#24481)
Closes #23463
Closes #22158

PR Close #24481
2018-07-10 11:12:08 -07:00
7717ff187a fix(compiler-cli): Use typescript to resolve modules for metadata (#22856)
The current module resolution simply attaches .ts to the import/export path, which does
not work if the path is using Node / CommonJS behavior to resolve to an index.ts file.
This patch uses typescript's module resolution logic, and will attempt to load the original
typescript file if this resolution returns a .js or .d.ts file

PR Close #22856
2018-07-10 11:11:48 -07:00
98b18cd49f docs: unified console.log single string style (#22737)
PR Close #22737
2018-07-10 11:11:30 -07:00
fe23a6e77e docs(aio): unified console.log single string style (#22737)
PR Close #22737
2018-07-10 11:11:30 -07:00
d7c4898081 build: remove unnecessary internal-angular karma reporter (#24803)
The reporter was added in 87d56acda, with the purpose of fixing
source-map paths (which was apparently needed back then). Things have
moved around a lot since then and the custom reporter doesn't seem to be
necessary any more. By removing the reporter, we have one less thing to
worry about while upgrading karma; plus we get improvements in built-in
reporters for free.

Output with the custom reporter:
```
at someMethod (packages/core/.../some-file.ts:13:37)
```

Output with the built-in reporter:
```
at someMethod (packages/core/.../some-file.ts:13.37 <- dist/all/@angular/core/.../some-file.js:1:337)
```

PR Close #24803
2018-07-09 15:14:02 -07:00
98c509fecb build: make internal-angular karma reporter compatible with latest karma (#24803)
Due to changes in karma@1.0.0, `internal-angular` karma reporter stopped
showing browser logs (such as `console.log()` etc.).
Related to d571a5173.

PR Close #24803
2018-07-09 15:10:49 -07:00
a92f111b66 fix(common): use correct currency format for locale de-AT (#24658)
Fixes #24609
PR Close #24658
2018-07-09 15:10:07 -07:00
de1c44f6e3 fix(language-service): do not overwrite native Reflect (#24299)
Fixes #21420

PR Close #24299
2018-07-09 15:09:17 -07:00
183b079175 fix(service-worker): avoid network requests when looking up hashed resources in cache (#24127)
PR Close #24127
2018-07-06 13:50:38 -07:00
8f8caa13b7 refactor(service-worker): avoid unnecessary operations and remove unused code (#24127)
PR Close #24127
2018-07-06 13:50:38 -07:00
195dc0748b docs: update Angular Boot Camp description (#23653)
PR Close #23653
2018-07-06 13:49:57 -07:00
2c6f84b25d docs: refactored ng-container code (#22742)
PR Close #22742
2018-07-06 13:49:35 -07:00
8e726f7d7b build(bazel): update to rule_nodejs 0.10.0 (#24759)
PR Close #24759
2018-07-06 10:18:21 -07:00
2d1102f5bf docs: add workspace and related cli terms (#24633)
PR Close #24633
2018-07-06 10:13:40 -07:00
0437598609 docs(common): fix in the documentation of PUT (#24528)
PR Close #24528
2018-07-06 10:13:20 -07:00
bc2bf184a2 docs: describe rounding behaviour of 'DecimalPipe' (#24303)
PR Close #24303
2018-07-06 10:13:00 -07:00
b51ce62c58 docs(aio): added a link to Angular Zero online course (Traditional Chinese) (#24228)
PR Close #24228
2018-07-06 10:11:02 -07:00
25b532e819 docs: clarify faqs about services (#24079)
PR Close #24079
2018-07-06 10:10:41 -07:00
69c8226a9f docs: add app.module to changed documents (#23876)
PR Close #23876
2018-07-06 10:10:21 -07:00
5326537985 docs(router): add paramsInheritanceStrategy documentation (#22590)
PR Close #22590
2018-07-06 10:10:02 -07:00
ada486a1dd docs: fix typos in 'Httpclient' docs (#19127)
PR Close #19127
2018-07-06 10:09:41 -07:00
563e8e3e56 docs: fix documention for attributes directive (#24367)
fix:update documentation for attributes directive to fix error

PR Close #24367
2018-07-03 18:34:59 -04:00
dd931c73ec ci: fix broken build (#24747) 2018-07-03 13:30:17 -07:00
b8975a90ca fix(core): use addCustomEqualityTester instead of overriding toEqual (#22983)
This propagates other custom equality testers added by users. Additionally, if
an Angular project is using jasmine 2.6+, it will allow Jasmine's custom object
differ to print out pretty test error messages.

fixes #22939

PR Close #22983
2018-07-03 08:40:00 -07:00
f44161503a docs(aio): update contributors entry (#23786)
PR Close #23786
2018-07-02 15:45:39 -07:00
6c55a130b1 feat(core): add support for ShadowDOM v1 (#24718)
add a new ViewEncapsulation.ShadowDom option that uses the v1 Shadow DOM API to provide style encapsulation.

PR Close #24718
2018-07-02 14:37:42 -07:00
144a624088 docs: update HTTP error test example again (#24701)
This has somehow regressed since angular/angular#22844 was merged.

PR Close #24701
2018-07-02 14:37:18 -07:00
f561f5a460 docs: fix typo in pipes guide (#24452)
PR Close #24452
2018-07-02 14:36:55 -07:00
916914be13 docs: fix docregion in attribute directives for highlight directive (#23972)
Fixes #23503

PR Close #23972
2018-07-02 14:36:24 -07:00
9a98de941d fix(common): properly update collection reference in NgForOf (#24684)
closes #24155

PR Close #24684
2018-06-29 06:43:45 -07:00
0f1de35604 docs(core): rephrase doc for Injector.get (#24670)
PR Close #24670
2018-06-29 06:43:19 -07:00
d89f57f9d5 build(docs-infra): render short description of parameters in API docs (#24537)
PR Close #24537
2018-06-28 15:03:15 -07:00
ac5b69f783 fix(docs-infra): use clean package.json template when generating zips (#24691)
Closes #24689

PR Close #24691
2018-06-28 15:01:01 -07:00
5ddd6dcedd docs: include ts-loader as shared example dependency (#24691)
Closes #24671

PR Close #24691
2018-06-28 15:01:01 -07:00
ad68332fa0 docs: consistent spacing in tutorial html files (#23105) (#24497)
- Removed surrounding spaces in interpolation expressions following the styleguide
- Consistant spacing of two spaces in html

Fixes #23105

PR Close #24497
2018-06-28 17:56:20 -04:00
2880cf9ef1 release: cut the v6.0.7 release 2018-06-27 16:54:22 -07:00
64a8584a92 fix(common): use correct ICU plural for locale mk (#24659)
PR Close #24659
2018-06-27 15:03:34 -07:00
97897ab738 refactor(upgrade): fix examples for strictPropertyInitialization and remove internal comments (#18487)
PR Close #18487
2018-06-27 14:57:54 -07:00
9378f44d6d docs(aio): tech edits to upgrade-lazy (#18487)
PR Close #18487
2018-06-27 14:53:24 -07:00
afa46af4c6 docs(upgrade): use a class for upgraded service (#18487)
This makes the resulting use in Angular more ideomatic, since we can just
use the class type as the injection indicator.

PR Close #18487
2018-06-27 14:53:24 -07:00
dbffdcc442 docs(upgrade): fix sub-ordered-list syntax (#18487)
We must always use 1., 2. etc, to indicate ordered lists, even for sub-lists.
We can change the sublist to display as a., b. etc, via CSS.

PR Close #18487
2018-06-27 14:53:24 -07:00
06d68a1b9f docs(upgrade): add guide about downgradeModule() (#18487)
PR Close #18487
2018-06-27 14:53:24 -07:00
75dd3c5ca5 docs(upgrade): add API docs for downgradeModule() (#18487)
PR Close #18487
2018-06-27 14:53:24 -07:00
23f56198a5 docs(upgrade): add API docs for propagateDigest (#18487)
PR Close #18487
2018-06-27 14:53:24 -07:00
69167e4519 docs(upgrade): update API docs for upgrade/static (#18487)
PR Close #18487
2018-06-27 14:53:22 -07:00
10feafcf27 docs: minor fixes in docs-style-guide (#18487)
PR Close #18487
2018-06-27 14:49:14 -07:00
3f3fed95be test: minor improvements in examples e2e tests script (#18487)
PR Close #18487
2018-06-27 14:49:13 -07:00
94433f3b9e docs: fix unit tests in toh-pt6 (#24491)
Resolves #20373

PR Close #24491
2018-06-27 14:33:26 -07:00
aa753878e6 docs: add explanation for enableResourceInlining (#24644)
PR Close #24644
2018-06-27 14:31:54 -07:00
3513ae40cc docs(aio): fix adding to template driven forms (#23743)
PR Close #23743
2018-06-26 11:03:36 -07:00
979e7b6086 docs(aio): fix issues suggested by Brandon (#23743)
PR Close #23743
2018-06-26 11:03:36 -07:00
41f008d109 docs(aio): fix issues suggested by Kara (#23743)
PR Close #23743
2018-06-26 11:03:36 -07:00
c950410ee1 docs(aio): address pr review issues (#23743)
PR Close #23743
2018-06-26 11:03:36 -07:00
b0fa504d39 docs(aio): add cross field validation example (#23743)
PR Close #23743
2018-06-26 11:03:36 -07:00
426f9710a0 build(docs-infra): support hiding constructors of injectable classes (#24529)
Classes that are injectable often have constructors that should not be
called by the application developer. It is the responsibility of the
injector to instantiate the class and the constructor often contains
private implementation details that may need to change.

This commit removes constructors from the docs for API items that are
both:

a) Marked with an injectable decorator (e.g. Injectable, Directive,
Component, Pipe), and
b) Have no constructor description

This second rule allows the developer to override the removal if there
is something useful to say about the constructor.

Note that "normal" classes such as `angimations/HttpHeaders` do not have
their constructor removed, despite (at this time) having no description.

PR Close #24529
2018-06-26 10:58:11 -07:00
ae01c70bba ci: fix broken build do to bad merge (#24662)
PR Close #24662
2018-06-25 13:11:16 -07:00
3341a97154 docs: test doc for decorator templates (#23902)
PR Close #23902
2018-06-25 10:58:00 -07:00
2056e1f05c Revert "docs: test doc for decorator templates (#23902)"
This reverts commit 3938a8be75.
2018-06-25 10:54:47 -07:00
3938a8be75 docs: test doc for decorator templates (#23902)
PR Close #23902
2018-06-25 10:09:15 -07:00
393db94b8d docs: fix misdirected group links (#24569)
PR Close #24569
2018-06-25 10:03:43 -07:00
65744e4ae1 docs: test api doc for pipes (#24141)
PR Close #24141
2018-06-25 09:37:30 -07:00
56bc86992c test(aio): fix upgrade-phonecat examples e2e tests (#24583)
Closes #19625

PR Close #24583
2018-06-25 09:30:46 -07:00
9426c02648 build: upgrade AngularJS typings (#24583)
Previously, we were using [@types/angularjs][1], which is deprecated and
outdated (hasn't been updated for over two years). This PR switches to
[@types/angular][2], which is regularly updated (based on the
definitions on [DefinitelyTyped][3]).

[1]: https://www.npmjs.com/package/@types/angularjs
[2]: https://www.npmjs.com/package/@types/angular
[3]: https://github.com/DefinitelyTyped/DefinitelyTyped

PR Close #24583
2018-06-25 09:30:46 -07:00
0b356d4163 fix(animations): set animations styles properly on platform-server (#24624)
Animations styles weren't getting properly set on platform-server because of erroneous checks and absence of reflection of style property to attribute on the server.

The fix corrects the check for platform and explicitly reflects the style property to the attribute.

PR Close #24624
2018-06-25 07:58:12 -07:00
a886659444 docs: add guide-angular.wishtack.io to education resources (#24585)
PR Close #24585
2018-06-25 07:57:34 -07:00
3649958595 build(docs-infra): move overload short description above syntax (#24526)
PR Close #24526
2018-06-25 07:56:37 -07:00
8919577c54 docs: update Angular CLI option for sourcemaps (#24437)
PR Close #24437
2018-06-25 07:53:27 -07:00
84eff4219e docs: update lowercase pipe example in "AngularJS to Angular" guide (#24588)
PR Close #24588
2018-06-21 13:14:31 -07:00
c11e84ee18 build(docs-infra): redirect removed webpack guide to v5.angular.io (#24595)
The outdated webpack guide has been removed in #24478, but people might
still try to access it (via direct links or search-engine results).

Instead of returning 404, we will now redirect `/guide/webpack` to the
archived version of the guide at `v5.angular.io/guide/webpack`.

PR Close #24595
2018-06-20 16:51:34 -07:00
1ce5a495d3 docs(aio): add elana olson to contributor.json file (#24579)
Add new contributor, elana olson, to the contributors list.

PR Close #24579
2018-06-20 16:50:54 -07:00
1f532aaa5a feat(docs-infra): Add GitHub and Twitter external icon links to topnav toolbar (#24542)
PR Close #24542
2018-06-20 16:50:15 -07:00
353 changed files with 6736 additions and 5634 deletions

View File

@ -12,8 +12,8 @@
## IMPORTANT
# If you change the `docker_image` version, also change the `cache_key` suffix and the version of
# `com_github_bazelbuild_buildtools` in the `/WORKSPACE` file.
var_1: &docker_image angular/ngcontainer:0.3.2
var_2: &cache_key v2-angular-{{ .Branch }}-{{ checksum "yarn.lock" }}-0.3.2
var_1: &docker_image angular/ngcontainer:0.3.3
var_2: &cache_key v2-angular-{{ .Branch }}-{{ checksum "yarn.lock" }}-0.3.3
# Define common ENV vars
var_3: &define_env_vars

View File

@ -23,7 +23,6 @@
# petebacondarwin - Pete Bacon Darwin
# pkozlowski-opensource - Pawel Kozlowski
# robwormald - Rob Wormald
# tinayuangao - Tina Gao
# vicb - Victor Berchet
# vikerman - Vikram Subramanian
@ -218,7 +217,6 @@ groups:
- "aio/content/examples/reactive-forms/*"
users:
- kara #primary
- tinayuangao #secondary
- IgorMinar #fallback
- mhevery #fallback

View File

@ -1,3 +1,45 @@
<a name="6.0.9"></a>
## [6.0.9](https://github.com/angular/angular/compare/6.0.8...6.0.9) (2018-07-11)
### Bug Fixes
* **common:** format fractional seconds ([#24844](https://github.com/angular/angular/issues/24844)) ([3c93d07](https://github.com/angular/angular/commit/3c93d07)), closes [#24831](https://github.com/angular/angular/issues/24831)
<a name="6.0.8"></a>
## [6.0.8](https://github.com/angular/angular/compare/6.0.7...6.0.8) (2018-07-11)
### Bug Fixes
* **common:** do not round factional seconds ([#24831](https://github.com/angular/angular/issues/24831)) ([0746485](https://github.com/angular/angular/commit/0746485)), closes [#24384](https://github.com/angular/angular/issues/24384)
* **common:** properly update collection reference in NgForOf ([#24684](https://github.com/angular/angular/issues/24684)) ([9a98de9](https://github.com/angular/angular/commit/9a98de9)), closes [#24155](https://github.com/angular/angular/issues/24155)
* **common:** use correct currency format for locale de-AT ([#24658](https://github.com/angular/angular/issues/24658)) ([a92f111](https://github.com/angular/angular/commit/a92f111)), closes [#24609](https://github.com/angular/angular/issues/24609)
* **compiler-cli:** Use typescript to resolve modules for metadata ([#22856](https://github.com/angular/angular/issues/22856)) ([7717ff1](https://github.com/angular/angular/commit/7717ff1))
* **core:** use addCustomEqualityTester instead of overriding toEqual ([#22983](https://github.com/angular/angular/issues/22983)) ([b8975a9](https://github.com/angular/angular/commit/b8975a9)), closes [#22939](https://github.com/angular/angular/issues/22939)
* **language-service:** do not overwrite native `Reflect` ([#24299](https://github.com/angular/angular/issues/24299)) ([de1c44f](https://github.com/angular/angular/commit/de1c44f)), closes [#21420](https://github.com/angular/angular/issues/21420)
* **router:** add ability to recover from malformed url ([#23283](https://github.com/angular/angular/issues/23283)) ([2d4f4b5](https://github.com/angular/angular/commit/2d4f4b5)), closes [#21468](https://github.com/angular/angular/issues/21468)
* **service-worker:** avoid network requests when looking up hashed resources in cache ([#24127](https://github.com/angular/angular/issues/24127)) ([183b079](https://github.com/angular/angular/commit/183b079))
### Features
* **core:** add support for ShadowDOM v1 ([#24718](https://github.com/angular/angular/issues/24718)) ([6c55a13](https://github.com/angular/angular/commit/6c55a13))
<a name="6.0.7"></a>
## [6.0.7](https://github.com/angular/angular/compare/6.0.6...6.0.7) (2018-06-27)
### Bug Fixes
* **animations:** set animations styles properly on platform-server ([#24624](https://github.com/angular/angular/issues/24624)) ([0b356d4](https://github.com/angular/angular/commit/0b356d4))
* **common:** use correct ICU plural for locale mk ([#24659](https://github.com/angular/angular/issues/24659)) ([64a8584](https://github.com/angular/angular/commit/64a8584))
<a name="6.0.6"></a>
## [6.0.6](https://github.com/angular/angular/compare/6.0.5...6.0.6) (2018-06-20)

View File

@ -6,9 +6,9 @@ workspace(name = "angular")
http_archive(
name = "build_bazel_rules_nodejs",
url = "https://github.com/bazelbuild/rules_nodejs/archive/0.9.1.zip",
strip_prefix = "rules_nodejs-0.9.1",
sha256 = "6139762b62b37c1fd171d7f22aa39566cb7dc2916f0f801d505a9aaf118c117f",
url = "https://github.com/bazelbuild/rules_nodejs/archive/0.10.1.zip",
strip_prefix = "rules_nodejs-0.10.1",
sha256 = "634206524d90dc03c52392fa3f19a16637d2bcf154910436fe1d669a0d9d7b9c",
)
http_archive(
@ -20,9 +20,9 @@ http_archive(
http_archive(
name = "build_bazel_rules_typescript",
url = "https://github.com/bazelbuild/rules_typescript/archive/0.15.0.zip",
strip_prefix = "rules_typescript-0.15.0",
sha256 = "1aa75917330b820cb239b3c10a936a10f0a46fe215063d4492dd76dc6e1616f4",
url = "https://github.com/bazelbuild/rules_typescript/archive/0.15.3.zip",
strip_prefix = "rules_typescript-0.15.3",
sha256 = "a2b26ac3fc13036011196063db1bf7f1eae81334449201dc28087ebfa3708c99",
)
http_archive(
@ -77,7 +77,7 @@ http_archive(
load("@build_bazel_rules_nodejs//:defs.bzl", "check_bazel_version", "node_repositories", "yarn_install")
check_bazel_version("0.14.0")
check_bazel_version("0.15.0")
node_repositories(package_json = ["//:package.json"])
load("@io_bazel_rules_go//go:def.bzl", "go_rules_dependencies", "go_register_toolchains")

View File

@ -60,6 +60,8 @@ dist/
!rollup-config.js
aot-compiler/**/*.d.ts
aot-compiler/**/*.factory.d.ts
upgrade-phonecat-2-hybrid/aot/**/*
!upgrade-phonecat-2-hybrid/aot/index.html
# i18n
!i18n/src/systemjs-text-plugin.js

View File

@ -40,5 +40,7 @@ export class HighlightDirective {
// #docregion color-2
@Input() appHighlight: string;
// #enddocregion color-2
}
// #docregion
}
// #enddocregion

View File

@ -5,7 +5,7 @@
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
// #docregion directive-import
@ -24,7 +24,7 @@ import { ItemDirective } from './item.directive';
imports: [
BrowserModule,
FormsModule,
HttpModule
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]

View File

@ -1,7 +1,7 @@
// #docregion
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { HttpClientModule } from '@angular/common/http';
// import { AppRoutingModule } from './app-routing.module';
import { LocationStrategy,
@ -54,7 +54,7 @@ const c_components = [
imports: [
BrowserModule,
FormsModule,
HttpModule,
HttpClientModule,
InMemoryWebApiModule.forRoot(HeroData)
// AppRoutingModule TODO: add routes
],

View File

@ -0,0 +1,69 @@
'use strict'; // necessary for es6 output in node
import { browser, by, element } from 'protractor';
/* tslint:disable:quotemark */
describe('Elements', () => {
const messageInput = element(by.css('input'));
const popupButtons = element.all(by.css('button'));
beforeEach(() => browser.get(''));
describe('popup component', () => {
const popupComponentButton = popupButtons.get(0);
const popupComponent = element(by.css('popup-component'));
const closeButton = popupComponent.element(by.css('button'));
it('should be displayed on button click', () => {
expect(popupComponent.isPresent()).toBe(false);
popupComponentButton.click();
expect(popupComponent.isPresent()).toBe(true);
});
it('should display the specified message', () => {
messageInput.clear();
messageInput.sendKeys('Angular rocks!');
popupComponentButton.click();
expect(popupComponent.getText()).toContain('Popup: Angular rocks!');
});
it('should be closed on "close" button click', () => {
popupComponentButton.click();
expect(popupComponent.isPresent()).toBe(true);
closeButton.click();
expect(popupComponent.isPresent()).toBe(false);
});
});
describe('popup element', () => {
const popupElementButton = popupButtons.get(1);
const popupElement = element(by.css('popup-element'));
const closeButton = popupElement.element(by.css('button'));
it('should be displayed on button click', () => {
expect(popupElement.isPresent()).toBe(false);
popupElementButton.click();
expect(popupElement.isPresent()).toBe(true);
});
it('should display the specified message', () => {
messageInput.clear();
messageInput.sendKeys('Angular rocks!');
popupElementButton.click();
expect(popupElement.getText()).toContain('Popup: Angular rocks!');
});
it('should be closed on "close" button click', () => {
popupElementButton.click();
expect(popupElement.isPresent()).toBe(true);
closeButton.click();
expect(popupElement.isPresent()).toBe(false);
});
});
});

View File

@ -0,0 +1,3 @@
{
"projectType": "elements"
}

View File

@ -1,6 +1,5 @@
// #docregion
import { Component, Injector } from '@angular/core';
import { createNgElementConstructor } from '../elements-dist';
import { createCustomElement } from '@angular/elements';
import { PopupService } from './popup.service';
import { PopupComponent } from './popup.component';
@ -8,19 +7,15 @@ import { PopupComponent } from './popup.component';
selector: 'app-root',
template: `
<input #input value="Message">
<button (click)="popup.showAsComponent(input.value)">
Show as component </button>
<button (click)="popup.showAsElement(input.value)">
Show as element </button>
`
<button (click)="popup.showAsComponent(input.value)">Show as component</button>
<button (click)="popup.showAsElement(input.value)">Show as element</button>
`,
})
export class AppComponent {
constructor(private injector: Injector, public popup: PopupService) {
// on init, convert PopupComponent to a custom element
const PopupElement =
createNgElementConstructor(PopupComponent, {injector: this.injector});
// register the custom element with the browser.
customElements.define('popup-element', PopupElement);
constructor(injector: Injector, public popup: PopupService) {
// Convert `PopupComponent` to a custom element.
const PopupElement = createCustomElement(PopupComponent, {injector});
// Register the custom element with the browser.
customElements.define('popup-element', PopupElement);
}
}

View File

@ -1,22 +1,21 @@
// #docregion
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { PopupService } from './popup.service';
import { PopupComponent } from './popup.component';
import { PopupService } from './popup.service';
// include the PopupService provider,
// but exclude PopupComponent from compilation,
// because it will be added dynamically
// Include the `PopupService` provider,
// but exclude `PopupComponent` from compilation,
// because it will be added dynamically.
@NgModule({
declarations: [AppComponent, PopupComponent],
imports: [BrowserModule, BrowserAnimationsModule],
providers: [PopupService],
declarations: [AppComponent, PopupComponent],
bootstrap: [AppComponent],
entryComponents: [PopupComponent],
})
export class AppModule {}
export class AppModule {
}

View File

@ -1,14 +1,14 @@
// #docregion
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { AnimationEvent } from '@angular/animations';
import { animate, state, style, transition, trigger } from '@angular/animations';
@Component({
selector: 'my-popup',
template: 'Popup: {{message}}',
template: `
<span>Popup: {{message}}</span>
<button (click)="closed.next()">&#x2716;</button>
`,
host: {
'[@state]': 'state',
'(@state.done)': 'onAnimationDone($event)',
},
animations: [
trigger('state', [
@ -27,13 +27,17 @@ import { animate, state, style, transition, trigger } from '@angular/animations'
height: 48px;
padding: 16px;
display: flex;
justify-content: space-between;
align-items: center;
border-top: 1px solid black;
font-size: 24px;
}
button {
border-radius: 50%;
}
`]
})
export class PopupComponent {
private state: 'opened' | 'closed' = 'closed';
@ -41,18 +45,10 @@ export class PopupComponent {
set message(message: string) {
this._message = message;
this.state = 'opened';
setTimeout(() => this.state = 'closed', 2000);
}
get message(): string { return this._message; }
_message: string;
@Output()
closed = new EventEmitter();
onAnimationDone(e: AnimationEvent) {
if (e.toState === 'closed') {
this.closed.next();
}
}
}

View File

@ -1,9 +1,8 @@
// #docregion
import { ApplicationRef, ComponentFactoryResolver, Injectable, Injector } from '@angular/core';
import { NgElement, WithProperties } from '@angular/elements';
import { PopupComponent } from './popup.component';
import { NgElementConstructor } from '../elements-dist';
@Injectable()
export class PopupService {
@ -40,7 +39,7 @@ export class PopupService {
// This uses the new custom-element method to add the popup to the DOM.
showAsElement(message: string) {
// Create element
const popupEl = document.createElement('popup-element');
const popupEl: NgElement & WithProperties<PopupComponent> = document.createElement('popup-element') as any;
// Listen to the close event
popupEl.addEventListener('closed', () => document.body.removeChild(popupEl));

View File

@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<base href="/">
<title>Elements</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<app-root></app-root>
</body>
</html>

View File

@ -1,4 +1,3 @@
// tslint:disable:no-unused-variable
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
@ -10,4 +9,3 @@ if (environment.production) {
}
platformBrowserDynamic().bootstrapModule(AppModule);

View File

@ -16,6 +16,7 @@ describe('Form Validation Tests', function () {
tests('Template-Driven Form');
bobTests();
crossValidationTests();
});
describe('Reactive form', () => {
@ -25,6 +26,7 @@ describe('Form Validation Tests', function () {
tests('Reactive Form');
bobTests();
crossValidationTests();
});
});
@ -42,7 +44,8 @@ let page: {
powerOption: ElementFinder,
errorMessages: ElementArrayFinder,
heroFormButtons: ElementArrayFinder,
heroSubmitted: ElementFinder
heroSubmitted: ElementFinder,
crossValidationErrorMessage: ElementFinder,
};
function getPage(sectionTag: string) {
@ -59,7 +62,8 @@ function getPage(sectionTag: string) {
powerOption: section.element(by.css('#power option')),
errorMessages: section.all(by.css('div.alert')),
heroFormButtons: buttons,
heroSubmitted: section.element(by.css('.submitted-message'))
heroSubmitted: section.element(by.css('.submitted-message')),
crossValidationErrorMessage: section.element(by.css('.cross-validation-error-message')),
};
}
@ -172,3 +176,29 @@ function bobTests() {
expectFormIsValid();
});
}
function crossValidationTests() {
const emsg = 'Name cannot match alter ego.';
it(`should produce "${emsg}" error after setting name and alter ego to the same value`, function () {
page.nameInput.clear();
page.nameInput.sendKeys('Batman');
page.alterEgoInput.clear();
page.alterEgoInput.sendKeys('Batman');
expectFormIsInvalid();
expect(page.crossValidationErrorMessage.getText()).toBe(emsg);
});
it('should be ok again with different values', function () {
page.nameInput.clear();
page.nameInput.sendKeys('Batman');
page.alterEgoInput.clear();
page.alterEgoInput.sendKeys('Superman');
expectFormIsValid();
expect(page.crossValidationErrorMessage.isPresent()).toBe(false);
});
}

View File

@ -7,7 +7,7 @@ import { AppComponent } from './app.component';
import { HeroFormTemplateComponent } from './template/hero-form-template.component';
import { HeroFormReactiveComponent } from './reactive/hero-form-reactive.component';
import { ForbiddenValidatorDirective } from './shared/forbidden-name.directive';
import { IdentityRevealedValidatorDirective } from './shared/identity-revealed.directive';
@NgModule({
imports: [
@ -19,7 +19,8 @@ import { ForbiddenValidatorDirective } from './shared/forbidden-name.directive';
AppComponent,
HeroFormTemplateComponent,
HeroFormReactiveComponent,
ForbiddenValidatorDirective
ForbiddenValidatorDirective,
IdentityRevealedValidatorDirective
],
bootstrap: [ AppComponent ]
})

View File

@ -0,0 +1,42 @@
/* tslint:disable: member-ordering forin */
// #docplaster
// #docregion
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { forbiddenNameValidator } from '../shared/forbidden-name.directive';
@Component({
selector: 'app-hero-form-reactive',
templateUrl: './hero-form-reactive.component.html',
styleUrls: ['./hero-form-reactive.component.css'],
})
export class HeroFormReactiveComponent implements OnInit {
powers = ['Really Smart', 'Super Flexible', 'Weather Changer'];
hero = {name: 'Dr.', alterEgo: 'Dr. What', power: this.powers[0]};
heroForm: FormGroup;
// #docregion form-group
ngOnInit(): void {
// #docregion custom-validator
this.heroForm = new FormGroup({
'name': new FormControl(this.hero.name, [
Validators.required,
Validators.minLength(4),
forbiddenNameValidator(/bob/i) // <-- Here's how you pass in the custom validator.
]),
'alterEgo': new FormControl(this.hero.alterEgo),
'power': new FormControl(this.hero.power, Validators.required)
});
// #enddocregion custom-validator
}
get name() { return this.heroForm.get('name'); }
get power() { return this.heroForm.get('power'); }
// #enddocregion form-group
}
// #enddocregion

View File

@ -0,0 +1,5 @@
/* #docregion cross-validation-error-css */
.cross-validation-error input {
border-left: 5px solid red;
}
/* #enddocregion cross-validation-error-css */

View File

@ -7,33 +7,41 @@
<div [hidden]="formDir.submitted">
<div class="form-group">
<div class="cross-validation" [class.cross-validation-error]="heroForm.errors?.identityRevealed && (heroForm.touched || heroForm.dirty)">
<div class="form-group">
<label for="name">Name</label>
<!-- #docregion name-with-error-msg -->
<input id="name" class="form-control"
formControlName="name" required >
<label for="name">Name</label>
<!-- #docregion name-with-error-msg -->
<input id="name" class="form-control"
formControlName="name" required >
<div *ngIf="name.invalid && (name.dirty || name.touched)"
class="alert alert-danger">
<div *ngIf="name.invalid && (name.dirty || name.touched)"
class="alert alert-danger">
<div *ngIf="name.errors.required">
Name is required.
</div>
<div *ngIf="name.errors.minlength">
Name must be at least 4 characters long.
</div>
<div *ngIf="name.errors.forbiddenName">
Name cannot be Bob.
<div *ngIf="name.errors.required">
Name is required.
</div>
<div *ngIf="name.errors.minlength">
Name must be at least 4 characters long.
</div>
<div *ngIf="name.errors.forbiddenName">
Name cannot be Bob.
</div>
</div>
<!-- #enddocregion name-with-error-msg -->
</div>
<!-- #enddocregion name-with-error-msg -->
</div>
<div class="form-group">
<label for="alterEgo">Alter Ego</label>
<input id="alterEgo" class="form-control"
formControlName="alterEgo" >
<div class="form-group">
<label for="alterEgo">Alter Ego</label>
<input id="alterEgo" class="form-control"
formControlName="alterEgo" >
</div>
<!-- #docregion cross-validation-error-message -->
<div *ngIf="heroForm.errors?.identityRevealed && (heroForm.touched || heroForm.dirty)" class="cross-validation-error-message alert alert-danger">
Name cannot match alter ego.
</div>
<!-- #enddocregion cross-validation-error-message -->
</div>
<div class="form-group">

View File

@ -1,40 +1,36 @@
/* tslint:disable: member-ordering forin */
// #docplaster
// #docregion
import { Component, OnInit } from '@angular/core';
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { forbiddenNameValidator } from '../shared/forbidden-name.directive';
import { identityRevealedValidator } from '../shared/identity-revealed.directive';
@Component({
selector: 'app-hero-form-reactive',
templateUrl: './hero-form-reactive.component.html'
templateUrl: './hero-form-reactive.component.html',
styleUrls: ['./hero-form-reactive.component.css'],
})
export class HeroFormReactiveComponent implements OnInit {
powers = ['Really Smart', 'Super Flexible', 'Weather Changer'];
hero = {name: 'Dr.', alterEgo: 'Dr. What', power: this.powers[0]};
hero = { name: 'Dr.', alterEgo: 'Dr. What', power: this.powers[0] };
heroForm: FormGroup;
// #docregion form-group
ngOnInit(): void {
// #docregion custom-validator
this.heroForm = new FormGroup({
'name': new FormControl(this.hero.name, [
Validators.required,
Validators.minLength(4),
forbiddenNameValidator(/bob/i) // <-- Here's how you pass in the custom validator.
forbiddenNameValidator(/bob/i)
]),
'alterEgo': new FormControl(this.hero.alterEgo),
'power': new FormControl(this.hero.power, Validators.required)
});
// #enddocregion custom-validator
}, { validators: identityRevealedValidator }); // <-- add custom validator at the FormGroup level
}
get name() { return this.heroForm.get('name'); }
get power() { return this.heroForm.get('power'); }
// #enddocregion form-group
}
// #enddocregion

View File

@ -0,0 +1,25 @@
// #docregion
import { Directive } from '@angular/core';
import { AbstractControl, FormGroup, NG_VALIDATORS, ValidationErrors, Validator, ValidatorFn } from '@angular/forms';
// #docregion cross-validation-validator
/** A hero's name can't match the hero's alter ego */
export const identityRevealedValidator: ValidatorFn = (control: FormGroup): ValidationErrors | null => {
const name = control.get('name');
const alterEgo = control.get('alterEgo');
return name && alterEgo && name.value === alterEgo.value ? { 'identityRevealed': true } : null;
};
// #enddocregion cross-validation-validator
// #docregion cross-validation-directive
@Directive({
selector: '[appIdentityRevealed]',
providers: [{ provide: NG_VALIDATORS, useExisting: IdentityRevealedValidatorDirective, multi: true }]
})
export class IdentityRevealedValidatorDirective implements Validator {
validate(control: AbstractControl): ValidationErrors {
return identityRevealedValidator(control)
}
}
// #enddocregion cross-validation-directive

View File

@ -0,0 +1,4 @@
/* #docregion */
.cross-validation-error input {
border-left: 5px solid red;
}

View File

@ -2,41 +2,48 @@
<div class="container">
<h1>Template-Driven Form</h1>
<!-- #docregion form-tag-->
<form #heroForm="ngForm">
<!-- #enddocregion form-tag-->
<!-- #docregion cross-validation-register-validator -->
<form #heroForm="ngForm" appIdentityRevealed>
<!-- #enddocregion cross-validation-register-validator -->
<div [hidden]="heroForm.submitted">
<div class="cross-validation" [class.cross-validation-error]="heroForm.errors?.identityRevealed && (heroForm.touched || heroForm.dirty)">
<div class="form-group">
<label for="name">Name</label>
<!-- #docregion name-with-error-msg -->
<!-- #docregion name-input -->
<input id="name" name="name" class="form-control"
required minlength="4" appForbiddenName="bob"
[(ngModel)]="hero.name" #name="ngModel" >
<!-- #enddocregion name-input -->
<div class="form-group">
<label for="name">Name</label>
<!-- #docregion name-with-error-msg -->
<!-- #docregion name-input -->
<input id="name" name="name" class="form-control"
required minlength="4" appForbiddenName="bob"
[(ngModel)]="hero.name" #name="ngModel" >
<!-- #enddocregion name-input -->
<div *ngIf="name.invalid && (name.dirty || name.touched)"
class="alert alert-danger">
<div *ngIf="name.invalid && (name.dirty || name.touched)"
class="alert alert-danger">
<div *ngIf="name.errors.required">
Name is required.
</div>
<div *ngIf="name.errors.minlength">
Name must be at least 4 characters long.
</div>
<div *ngIf="name.errors.forbiddenName">
Name cannot be Bob.
</div>
<div *ngIf="name.errors.required">
Name is required.
</div>
<div *ngIf="name.errors.minlength">
Name must be at least 4 characters long.
</div>
<div *ngIf="name.errors.forbiddenName">
Name cannot be Bob.
</div>
<!-- #enddocregion name-with-error-msg -->
</div>
<!-- #enddocregion name-with-error-msg -->
</div>
<div class="form-group">
<label for="alterEgo">Alter Ego</label>
<input id="alterEgo" class="form-control"
name="alterEgo" [(ngModel)]="hero.alterEgo" >
<div class="form-group">
<label for="alterEgo">Alter Ego</label>
<input id="alterEgo" class="form-control"
name="alterEgo" [(ngModel)]="hero.alterEgo" >
</div>
<!-- #docregion cross-validation-error-message -->
<div *ngIf="heroForm.errors?.identityRevealed && (heroForm.touched || heroForm.dirty)" class="cross-validation-error-message alert alert-danger">
Name cannot match alter ego.
</div>
<!-- #enddocregion cross-validation-error-message -->
</div>
<div class="form-group">
@ -62,5 +69,4 @@
<button (click)="heroForm.resetForm({})">Add new hero</button>
</div>
</form>
</div>

View File

@ -3,9 +3,11 @@
// #docregion
import { Component } from '@angular/core';
// #docregion component
@Component({
selector: 'app-hero-form-template',
templateUrl: './hero-form-template.component.html'
templateUrl: './hero-form-template.component.html',
styleUrls: ['./hero-form-template.component.css'],
})
export class HeroFormTemplateComponent {
@ -14,3 +16,4 @@ export class HeroFormTemplateComponent {
hero = {name: 'Dr.', alterEgo: 'Dr. What', power: this.powers[0]};
}
// #enddocregion

View File

@ -2,6 +2,7 @@
"description": "Validation",
"files":[
"!**/*.d.ts",
"!**/*.js"
"!**/*.js",
"!**/*.[1].*"
]
}

View File

@ -4,7 +4,8 @@ button {
font-size: 100%;
}
code, .code {
code,
.code {
background-color: #eee;
color: black;
font-family: Courier, sans-serif;
@ -21,14 +22,18 @@ div.code {
}
hr {
margin: 40px 0
margin: 40px 0;
}
td, th {
td,
th {
text-align: left;
vertical-align: top;
}
/* #docregion p-span */
p span { color: red; font-size: 70%; }
p span {
color: red;
font-size: 70%;
}
/* #enddocregion p-span */

View File

@ -132,7 +132,7 @@
<!-- #docregion select-span -->
<select [(ngModel)]="hero">
<span *ngFor="let h of heroes">
<span *ngIf="showSad || h?.emotion != 'sad'">
<span *ngIf="showSad || h?.emotion !== 'sad'">
<option [ngValue]="h">{{h.name}} ({{h?.emotion}})</option>
</span>
</span>
@ -147,7 +147,7 @@
<!-- #docregion select-ngcontainer -->
<select [(ngModel)]="hero">
<ng-container *ngFor="let h of heroes">
<ng-container *ngIf="showSad || h?.emotion != 'sad'">
<ng-container *ngIf="showSad || h?.emotion !== 'sad'">
<option [ngValue]="h">{{h.name}} ({{h?.emotion}})</option>
</ng-container>
</ng-container>

View File

@ -6,14 +6,15 @@ import { heroes } from './hero';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
styleUrls: ['./app.component.css']
})
export class AppComponent {
heroes = heroes;
hero = this.heroes[0];
heroTraits = [ 'honest', 'brave', 'considerate' ];
heroTraits = ['honest', 'brave', 'considerate'];
// flags for the table
attrDirs = true;
strucDirs = true;
divNgIf = false;

View File

@ -1,9 +1,9 @@
// #docregion
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { AppComponent } from './app.component';
import { ContentComponent } from './content.component';
import { heroComponents } from './hero.components';

View File

@ -1,5 +1,6 @@
// #docregion
import { Component, Input } from '@angular/core';
import { Hero } from './hero';
@Component({
@ -33,11 +34,15 @@ export class ConfusedHeroComponent {
export class UnknownHeroComponent {
@Input() hero: Hero;
get message() {
return this.hero && this.hero.name ?
`${this.hero.name} is strange and mysterious.` :
'Are you feeling indecisive?';
return this.hero && this.hero.name
? `${this.hero.name} is strange and mysterious.`
: 'Are you feeling indecisive?';
}
}
export const heroComponents =
[ HappyHeroComponent, SadHeroComponent, ConfusedHeroComponent, UnknownHeroComponent ];
export const heroComponents = [
HappyHeroComponent,
SadHeroComponent,
ConfusedHeroComponent,
UnknownHeroComponent
];

View File

@ -6,8 +6,8 @@ export class Hero {
}
export const heroes: Hero[] = [
{ id: 1, name: 'Mr. Nice', emotion: 'happy'},
{ id: 2, name: 'Narco', emotion: 'sad' },
{ id: 1, name: 'Mr. Nice', emotion: 'happy' },
{ id: 2, name: 'Narco', emotion: 'sad' },
{ id: 3, name: 'Windstorm', emotion: 'confused' },
{ id: 4, name: 'Magneta'}
{ id: 4, name: 'Magneta' }
];

View File

@ -1,7 +1,5 @@
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
/* App Root */
import { AppComponent } from './app.component';

View File

@ -15,7 +15,7 @@ function sequenceSubscriber(observer) {
if (idx === arr.length - 1) {
observer.complete();
} else {
doSequence(arr, idx++);
doSequence(arr, ++idx);
}
}, 1000);
}
@ -95,7 +95,7 @@ function multicastSequenceSubscriber() {
},
complete() {
// Notify all complete callbacks
observers.forEach(obs => obs.complete());
observers.slice(0).forEach(obs => obs.complete());
}
}, seq, 0);
}
@ -121,13 +121,13 @@ function doSequence(observer, arr, idx) {
if (idx === arr.length - 1) {
observer.complete();
} else {
doSequence(observer, arr, idx++);
doSequence(observer, arr, ++idx);
}
}, 1000);
}
// Create a new Observable that will deliver the above sequence
const multicastSequence = new Observable(multicastSequenceSubscriber);
const multicastSequence = new Observable(multicastSequenceSubscriber());
// Subscribe starts the clock, and begins to emit after 1 second
multicastSequence.subscribe({

View File

@ -1,3 +0,0 @@
[1030/162525.401:ERROR:process_reader_win.cc(123)] NtOpenThread: {Acceso denegado} Un proceso ha solicitado acceso a un objeto, pero no se le han concedido esos derechos de acceso. (0xc0000022)
[1030/162525.402:ERROR:exception_snapshot_win.cc(87)] thread ID 26896 not found in process
[1030/162525.402:WARNING:crash_report_exception_handler.cc(62)] ProcessSnapshotWin::Initialize failed

File diff suppressed because it is too large Load Diff

View File

@ -1,24 +0,0 @@
{
"description": "Angular Reactive Forms (final)",
"files":[
"src/styles.css",
"src/app/app.component.ts",
"src/app/app.component.html",
"src/app/app.component.css",
"src/app/app.module.ts",
"src/app/data-model.ts",
"src/app/hero.service.ts",
"src/app/hero-detail/hero-detail.component.html",
"src/app/hero-detail/hero-detail.component.ts",
"src/app/hero-detail/hero-detail.component.css",
"src/app/hero-list/hero-list.component.html",
"src/app/hero-list/hero-list.component.ts",
"src/app/hero-list/hero-list.component.css",
"src/main-final.ts",
"src/index-final.html"
],
"main": "src/index-final.html",
"tags": ["reactive", "forms"]
}

View File

@ -1,4 +1,10 @@
<div class="container">
<h1>Reactive Forms</h1>
<app-hero-detail></app-hero-detail>
</div>
<!-- #docplaster -->
<h1>Reactive Forms</h1>
<!-- #docregion app-name-editor-->
<app-name-editor></app-name-editor>
<!-- #enddocregion app-name-editor-->
<!-- #docregion app-profile-editor -->
<app-profile-editor></app-profile-editor>
<!-- #enddocregion app-profile-editor -->

View File

@ -1,4 +1,17 @@
<div class="container">
<h1>Reactive Forms</h1>
<app-hero-list></app-hero-list>
</div>
<!-- #docplaster -->
<!-- #docregion app-name-editor -->
<h1>Reactive Forms</h1>
<!-- #enddocregion app-name-editor -->
<nav>
<a (click)="toggleEditor('name')">Name Editor</a>
<a (click)="toggleEditor('profile')">Profile Editor</a>
</nav>
<!-- #docregion app-name-editor -->
<app-name-editor *ngIf="showNameEditor"></app-name-editor>
<!-- #enddocregion app-name-editor -->
<!-- #docregion app-profile-editor -->
<app-profile-editor *ngIf="showProfileEditor"></app-profile-editor>
<!-- #enddocregion app-profile-editor -->

View File

@ -0,0 +1,27 @@
import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
}).compileComponents();
}));
it('should create the app', async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));
it(`should have as title 'app'`, async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('app');
}));
it('should render title in a h1 tag', async(() => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('h1').textContent).toContain('Welcome to reactive-forms!');
}));
});

View File

@ -1,9 +1,24 @@
// #docregion
import { Component } from '@angular/core';
export type EditorType = 'name' | 'profile';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent { }
export class AppComponent {
editor: EditorType = 'name';
get showNameEditor() {
return this.editor === 'name';
}
get showProfileEditor() {
return this.editor === 'profile';
}
toggleEditor(type: EditorType) {
this.editor = type;
}
}

View File

@ -1,45 +1,34 @@
// #docplaster
// #docregion
// #docregion v1
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms'; // <-- #1 import module
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
// #docregion imports
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HeroDetailComponent } from './hero-detail/hero-detail.component';
// #enddocregion v1
// #docregion hero-service-list
// add JavaScript imports
import { HeroListComponent } from './hero-list/hero-list.component';
import { HeroService } from './hero.service';
// #docregion v1
// #enddocregion imports
import { AppComponent } from './app.component';
import { NameEditorComponent } from './name-editor/name-editor.component';
import { ProfileEditorComponent } from './profile-editor/profile-editor.component';
// #docregion imports
@NgModule({
// #enddocregion imports
declarations: [
AppComponent,
HeroDetailComponent,
// #enddocregion v1
HeroListComponent // <--declare HeroListComponent
// #docregion v1
NameEditorComponent,
ProfileEditorComponent
],
// #enddocregion hero-service-list
// #docregion imports
imports: [
// #enddocregion imports
BrowserModule,
ReactiveFormsModule // <-- #2 add to @NgModule imports
// #docregion imports
// other imports ...
ReactiveFormsModule
],
// #enddocregion v1
// export for the DemoModule
// #docregion hero-service-list
// ...
exports: [
AppComponent,
HeroDetailComponent,
HeroListComponent // <-- export HeroListComponent
],
providers: [ HeroService ], // <-- provide HeroService
// #enddocregion hero-service-list
// #docregion v1
bootstrap: [ AppComponent ]
// #enddocregion imports
providers: [],
bootstrap: [AppComponent]
// #docregion imports
})
export class AppModule { }
// #enddocregion v1
// #enddocregion imports

View File

@ -1,40 +0,0 @@
// #docregion
// #docregion model-classes
export class Hero {
id = 0;
name = '';
addresses: Address[];
}
export class Address {
street = '';
city = '';
state = '';
zip = '';
}
// #enddocregion model-classes
export const heroes: Hero[] = [
{
id: 1,
name: 'Whirlwind',
addresses: [
{street: '123 Main', city: 'Anywhere', state: 'CA', zip: '94801'},
{street: '456 Maple', city: 'Somewhere', state: 'VA', zip: '23226'},
]
},
{
id: 2,
name: 'Bombastic',
addresses: [
{street: '789 Elm', city: 'Smallville', state: 'OH', zip: '04501'},
]
},
{
id: 3,
name: 'Magneta',
addresses: [ ]
},
];
export const states = ['CA', 'MD', 'OH', 'VA'];

View File

@ -1,40 +0,0 @@
<div class="container">
<h1>Reactive Forms</h1>
<h4><i>Pick a demo:</i>
<select [selectedIndex]="demo - 1" (change)="selectDemo($event.target.selectedIndex)">
<option *ngFor="let demo of demos">{{demo}}</option>
</select>
</h4>
<hr>
<div class="demo">
<app-hero-list *ngIf="demo===final"></app-hero-list>
<app-hero-detail-1 *ngIf="demo===1"></app-hero-detail-1>
<app-hero-detail-2 *ngIf="demo===2"></app-hero-detail-2>
<app-hero-detail-3 *ngIf="demo===3"></app-hero-detail-3>
<app-hero-detail-4 *ngIf="demo===4"></app-hero-detail-4>
<app-hero-detail-5 *ngIf="demo===5"></app-hero-detail-5>
<div *ngIf="demo >= 6 && demo !== final" >
<h3 *ngIf="isLoading"><i>Loading heroes ... </i></h3>
<h3 *ngIf="!isLoading">Select a hero:</h3>
<nav>
<button (click)="getHeroes()" class="btn btn-primary">Refresh</button>
<a *ngFor="let hero of heroes | async" (click)="select(hero)">{{hero.name}}</a>
</nav>
<div *ngIf="selectedHero">
<hr>
<h2>Hero Detail</h2>
<h3>Editing: {{selectedHero.name}}</h3>
<app-hero-detail-6 [hero]=selectedHero *ngIf="demo===6"></app-hero-detail-6>
<app-hero-detail-7 [hero]=selectedHero *ngIf="demo===7"></app-hero-detail-7>
<app-hero-detail-8 [hero]=selectedHero *ngIf="demo===8"></app-hero-detail-8>
</div>
</div>
</div>
</div>

View File

@ -1,49 +0,0 @@
/* tslint:disable:member-ordering */
import { Component } from '@angular/core';
import { Observable } from 'rxjs';
import { finalize } from 'rxjs/operators';
import { Hero } from './data-model';
import { HeroService } from './hero.service';
@Component({
selector: 'app-root',
templateUrl: './demo.component.html'
})
export class DemoComponent {
demos: string[] = [
'Just a FormControl',
'FormControl in a FormGroup',
'Simple FormBuilder group',
'Group with multiple controls',
'Nested FormBuilder group',
'PatchValue',
'SetValue',
'FormArray',
'Final'].map(n => n + ' Demo');
final = this.demos.length;
demo = this.final; // current demo
heroes: Observable<Hero[]>;
isLoading = false;
selectedHero: Hero;
constructor(private heroService: HeroService) { }
getHeroes() {
this.isLoading = true;
this.heroes = this.heroService.getHeroes().pipe(
finalize(() => this.isLoading = false)
);
this.selectedHero = undefined;
}
select(hero: Hero) { this.selectedHero = hero; }
selectDemo(demo: number) {
this.demo = demo + 1;
this.getHeroes();
}
}

View File

@ -1,33 +0,0 @@
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { AppModule } from './app.module';
import { DemoComponent } from './demo.component';
import { HeroDetailComponent1 } from './hero-detail/hero-detail-1.component';
import { HeroDetailComponent2 } from './hero-detail/hero-detail-2.component';
import { HeroDetailComponent3 } from './hero-detail/hero-detail-3.component';
import { HeroDetailComponent4 } from './hero-detail/hero-detail-4.component';
import { HeroDetailComponent5 } from './hero-detail/hero-detail-5.component';
import { HeroDetailComponent6 } from './hero-detail/hero-detail-6.component';
import { HeroDetailComponent7 } from './hero-detail/hero-detail-7.component';
import { HeroDetailComponent8 } from './hero-detail/hero-detail-8.component';
@NgModule({
imports: [
BrowserModule,
ReactiveFormsModule,
AppModule,
],
declarations: [ DemoComponent,
HeroDetailComponent1,
HeroDetailComponent2,
HeroDetailComponent3,
HeroDetailComponent4,
HeroDetailComponent5,
HeroDetailComponent6,
HeroDetailComponent7,
HeroDetailComponent8],
bootstrap: [ DemoComponent ]
})
export class DemoModule { }

View File

@ -1,8 +0,0 @@
<!-- #docregion simple-control-->
<h2>Hero Detail</h2>
<h3><i>Just a FormControl</i></h3>
<label class="center-block">Name:
<input class="form-control" [formControl]="name">
</label>
<!-- #enddocregion simple-control-->

View File

@ -1,15 +0,0 @@
/* tslint:disable:component-class-suffix */
import { Component } from '@angular/core';
// #docregion import
import { FormControl } from '@angular/forms';
// #enddocregion import
@Component({
selector: 'app-hero-detail-1',
templateUrl: './hero-detail-1.component.html'
})
// #docregion v1
export class HeroDetailComponent1 {
name = new FormControl();
}

View File

@ -1,18 +0,0 @@
<!-- #docregion basic-form-->
<h2>Hero Detail</h2>
<h3><i>FormControl in a FormGroup</i></h3>
<form [formGroup]="heroForm">
<div class="form-group">
<label class="center-block">Name:
<input class="form-control" formControlName="name">
</label>
</div>
</form>
<!-- #enddocregion basic-form-->
<!-- #docregion form-value-json -->
<p>Form value: {{ heroForm.value | json }}</p>
<!-- #enddocregion form-value-json -->

View File

@ -1,17 +0,0 @@
/* tslint:disable:component-class-suffix */
// #docregion imports
import { Component } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
// #enddocregion imports
@Component({
selector: 'app-hero-detail-2',
templateUrl: './hero-detail-2.component.html'
})
// #docregion v2
export class HeroDetailComponent2 {
heroForm = new FormGroup ({
name: new FormControl()
});
}
// #enddocregion v2

View File

@ -1,16 +0,0 @@
<!-- #docregion basic-form-->
<h2>Hero Detail</h2>
<h3><i>A FormGroup with a single FormControl using FormBuilder</i></h3>
<form [formGroup]="heroForm">
<div class="form-group">
<label class="center-block">Name:
<input class="form-control" formControlName="name">
</label>
</div>
</form>
<!-- #enddocregion basic-form-->
<!-- #docregion form-value-json -->
<p>Form value: {{ heroForm.value | json }}</p>
<p>Form status: {{ heroForm.status | json }}</p>
<!-- #enddocregion form-value-json -->

View File

@ -1,27 +0,0 @@
/* tslint:disable:component-class-suffix */
// #docregion imports
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
// #enddocregion imports
@Component({
selector: 'app-hero-detail-3',
templateUrl: './hero-detail-3.component.html'
})
// #docregion v3
export class HeroDetailComponent3 {
heroForm: FormGroup; // <--- heroForm is of type FormGroup
constructor(private fb: FormBuilder) { // <--- inject FormBuilder
this.createForm();
}
createForm() {
// #docregion required
this.heroForm = this.fb.group({
name: ['', Validators.required ],
});
// #enddocregion required
}
}
// #enddocregion v3

View File

@ -1,25 +0,0 @@
/* tslint:disable:component-class-suffix */
// #docregion imports
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
// #enddocregion imports
@Component({
selector: 'app-hero-detail-3',
templateUrl: './hero-detail-3.component.html'
})
// #docregion v3a
export class HeroDetailComponent3 {
heroForm: FormGroup; // <--- heroForm is of type FormGroup
constructor(private fb: FormBuilder) { // <--- inject FormBuilder
this.createForm();
}
createForm() {
this.heroForm = this.fb.group({
name: '', // <--- the FormControl called "name"
});
}
}
// #enddocregion v3a

View File

@ -1,46 +0,0 @@
<!-- #docregion -->
<h2>Hero Detail</h2>
<h3><i>A FormGroup with multiple FormControls</i></h3>
<form [formGroup]="heroForm">
<div class="form-group">
<label class="center-block">Name:
<input class="form-control" formControlName="name">
</label>
</div>
<div class="form-group">
<label class="center-block">Street:
<input class="form-control" formControlName="street">
</label>
</div>
<div class="form-group">
<label class="center-block">City:
<input class="form-control" formControlName="city">
</label>
</div>
<div class="form-group">
<label class="center-block">State:
<select class="form-control" formControlName="state">
<option *ngFor="let state of states" [value]="state">{{state}}</option>
</select>
</label>
</div>
<div class="form-group">
<label class="center-block">Zip Code:
<input class="form-control" formControlName="zip">
</label>
</div>
<div class="form-group radio">
<h4>Super power:</h4>
<label class="center-block"><input type="radio" formControlName="power" value="flight">Flight</label>
<label class="center-block"><input type="radio" formControlName="power" value="x-ray vision">X-ray vision</label>
<label class="center-block"><input type="radio" formControlName="power" value="strength">Strength</label>
</div>
<div class="checkbox">
<label class="center-block">
<input type="checkbox" formControlName="sidekick">I have a sidekick.
</label>
</div>
</form>
<p>Form value: {{ heroForm.value | json }}</p>

View File

@ -1,34 +0,0 @@
/* tslint:disable:component-class-suffix */
// #docregion imports
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { states } from '../data-model';
// #enddocregion imports
@Component({
selector: 'app-hero-detail-4',
templateUrl: './hero-detail-4.component.html'
})
// #docregion v4
export class HeroDetailComponent4 {
heroForm: FormGroup;
states = states;
constructor(private fb: FormBuilder) {
this.createForm();
}
createForm() {
this.heroForm = this.fb.group({
name: ['', Validators.required ],
street: '',
city: '',
state: '',
zip: '',
power: '',
sidekick: ''
});
}
}
// #enddocregion v4

View File

@ -1,56 +0,0 @@
<form [formGroup]="heroForm">
<div class="form-group">
<label class="center-block">Name:
<input class="form-control" formControlName="name">
</label>
</div>
<!-- #docregion add-group-->
<div formGroupName="address" class="well well-lg">
<h4>Secret Lair</h4>
<div class="form-group">
<label class="center-block">Street:
<input class="form-control" formControlName="street">
</label>
</div>
<div class="form-group">
<label class="center-block">City:
<input class="form-control" formControlName="city">
</label>
</div>
<div class="form-group">
<label class="center-block">State:
<select class="form-control" formControlName="state">
<option *ngFor="let state of states" [value]="state">{{state}}</option>
</select>
</label>
</div>
<div class="form-group">
<label class="center-block">Zip Code:
<input class="form-control" formControlName="zip">
</label>
</div>
</div>
<!-- #enddocregion add-group-->
<div class="form-group radio">
<h4>Super power:</h4>
<label class="center-block"><input type="radio" formControlName="power" value="flight">Flight</label>
<label class="center-block"><input type="radio" formControlName="power" value="x-ray vision">X-ray vision</label>
<label class="center-block"><input type="radio" formControlName="power" value="strength">Strength</label>
</div>
<div class="checkbox">
<label class="center-block">
<input type="checkbox" formControlName="sidekick">I have a sidekick.
</label>
</div>
</form>
<p>heroForm value: {{ heroForm.value | json}}</p>
<h4>Extra info for the curious:</h4>
<!-- #docregion inspect-value -->
<p>Name value: {{ heroForm.get('name').value }}</p>
<!-- #enddocregion inspect-value -->
<!-- #docregion inspect-child-control -->
<p>Street value: {{ heroForm.get('address.street').value}}</p>
<!-- #enddocregion inspect-child-control -->

View File

@ -1,35 +0,0 @@
/* tslint:disable:component-class-suffix */
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { states } from '../data-model';
@Component({
selector: 'app-hero-detail-5',
templateUrl: './hero-detail-5.component.html'
})
// #docregion v5
export class HeroDetailComponent5 {
heroForm: FormGroup;
states = states;
constructor(private fb: FormBuilder) {
this.createForm();
}
createForm() {
this.heroForm = this.fb.group({ // <-- the parent FormGroup
name: ['', Validators.required ],
address: this.fb.group({ // <-- the child FormGroup
street: '',
city: '',
state: '',
zip: ''
}),
power: '',
sidekick: ''
});
}
}
// #enddocregion v5

View File

@ -1,46 +0,0 @@
<!-- #docregion -->
<h2>Hero Detail</h2>
<h3><i>PatchValue to initialize a value</i></h3>
<form [formGroup]="heroForm">
<div class="form-group">
<label class="center-block">Name:
<input class="form-control" formControlName="name">
</label>
</div>
<div class="form-group">
<label class="center-block">Street:
<input class="form-control" formControlName="street">
</label>
</div>
<div class="form-group">
<label class="center-block">City:
<input class="form-control" formControlName="city">
</label>
</div>
<div class="form-group">
<label class="center-block">State:
<select class="form-control" formControlName="state">
<option *ngFor="let state of states" [value]="state">{{state}}</option>
</select>
</label>
</div>
<div class="form-group">
<label class="center-block">Zip Code:
<input class="form-control" formControlName="zip">
</label>
</div>
<div class="form-group radio">
<h4>Super power:</h4>
<label class="center-block"><input type="radio" formControlName="power" value="flight">Flight</label>
<label class="center-block"><input type="radio" formControlName="power" value="x-ray vision">X-ray vision</label>
<label class="center-block"><input type="radio" formControlName="power" value="strength">Strength</label>
</div>
<div class="checkbox">
<label class="center-block">
<input type="checkbox" formControlName="sidekick">I have a sidekick.
</label>
</div>
</form>
<p>Form value: {{ heroForm.value | json }}</p>

View File

@ -1,66 +0,0 @@
/* tslint:disable:component-class-suffix */
// #docregion import-input
import { Component, Input, OnChanges } from '@angular/core';
// #enddocregion import-input
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
// #docregion import-hero
import { Hero, states } from '../data-model';
// #enddocregion import-hero
////////// 6 ////////////////////
@Component({
selector: 'app-hero-detail-6',
templateUrl: './hero-detail-5.component.html'
})
// #docregion v6
export class HeroDetailComponent6 implements OnChanges {
// #docregion hero
@Input() hero: Hero;
// #enddocregion hero
heroForm: FormGroup;
states = states;
constructor(private fb: FormBuilder) {
this.createForm();
}
createForm() {
// #docregion hero-form-model
this.heroForm = this.fb.group({
name: ['', Validators.required ],
address: this.fb.group({
street: '',
city: '',
state: '',
zip: ''
}),
power: '',
sidekick: ''
});
// #enddocregion hero-form-model
}
// #docregion patch-value-on-changes
ngOnChanges() { // <-- call rebuildForm in ngOnChanges
this.rebuildForm();
}
// #enddocregion patch-value-on-changes
// #docregion patch-value-rebuildform
rebuildForm() { // <-- wrap patchValue in rebuildForm
this.heroForm.reset();
// #docregion patch-value
this.heroForm.patchValue({
name: this.hero.name
});
// #enddocregion patch-value
}
// #enddocregion patch-value-rebuildform
}
// #enddocregion v6

View File

@ -1,46 +0,0 @@
<!-- #docregion -->
<h2>Hero Detail</h2>
<h3><i>A FormGroup with multiple FormControls</i></h3>
<form [formGroup]="heroForm">
<div class="form-group">
<label class="center-block">Name:
<input class="form-control" formControlName="name">
</label>
</div>
<div class="form-group">
<label class="center-block">Street:
<input class="form-control" formControlName="street">
</label>
</div>
<div class="form-group">
<label class="center-block">City:
<input class="form-control" formControlName="city">
</label>
</div>
<div class="form-group">
<label class="center-block">State:
<select class="form-control" formControlName="state">
<option *ngFor="let state of states" [value]="state">{{state}}</option>
</select>
</label>
</div>
<div class="form-group">
<label class="center-block">Zip Code:
<input class="form-control" formControlName="zip">
</label>
</div>
<div class="form-group radio">
<h4>Super power:</h4>
<label class="center-block"><input type="radio" formControlName="power" value="flight">Flight</label>
<label class="center-block"><input type="radio" formControlName="power" value="x-ray vision">X-ray vision</label>
<label class="center-block"><input type="radio" formControlName="power" value="strength">Strength</label>
</div>
<div class="checkbox">
<label class="center-block">
<input type="checkbox" formControlName="sidekick">I have a sidekick.
</label>
</div>
</form>
<p>Form value: {{ heroForm.value | json }}</p>

View File

@ -1,68 +0,0 @@
/* tslint:disable:component-class-suffix */
// #docplaster
// #docregion imports
import { Component, Input, OnChanges } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
// #docregion import-address
import { Address, Hero, states } from '../data-model';
// #enddocregion import-address
// #enddocregion imports
@Component({
selector: 'app-hero-detail-7',
templateUrl: './hero-detail-5.component.html'
})
// #docregion v7
export class HeroDetailComponent7 implements OnChanges {
@Input() hero: Hero;
heroForm: FormGroup;
states = states;
constructor(private fb: FormBuilder) {
this.createForm();
}
createForm() {
// #docregion address-form-group
this.heroForm = this.fb.group({
name: ['', Validators.required ],
address: this.fb.group(new Address()), // <-- a FormGroup with a new address
power: '',
sidekick: ''
});
// #enddocregion address-form-group
}
// #docregion ngOnChanges
ngOnChanges() {
this.rebuildForm();
}
// #enddocregion ngOnChanges
// #docregion rebuildForm
rebuildForm() {
this.heroForm.reset({
name: this.hero.name,
// #docregion set-value-address
address: this.hero.addresses[0] || new Address()
// #enddocregion set-value-address
});
}
// #enddocregion rebuildForm
/* First version of rebuildForm */
rebuildForm1() {
// #docregion reset
this.heroForm.reset();
// #enddocregion reset
// #docregion set-value
this.heroForm.setValue({
name: this.hero.name,
address: this.hero.addresses[0] || new Address()
});
// #enddocregion set-value
}
}

View File

@ -1,72 +0,0 @@
<!-- #docplaster-->
<h3><i>Using FormArray to add groups</i></h3>
<form [formGroup]="heroForm">
<p>Form Changed: {{ heroForm.dirty }}</p>
<div class="form-group">
<label class="center-block">Name:
<input class="form-control" formControlName="name">
</label>
</div>
<!-- #docregion form-array-->
<!-- #docregion form-array-skeleton -->
<!-- #docregion form-array-name -->
<div formArrayName="secretLairs" class="well well-lg">
<!-- #enddocregion form-array-name -->
<div *ngFor="let address of secretLairs.controls; let i=index" [formGroupName]="i" >
<!-- The repeated address template -->
<!-- #enddocregion form-array-skeleton -->
<h4>Address #{{i + 1}}</h4>
<div style="margin-left: 1em;">
<div class="form-group">
<label class="center-block">Street:
<input class="form-control" formControlName="street">
</label>
</div>
<div class="form-group">
<label class="center-block">City:
<input class="form-control" formControlName="city">
</label>
</div>
<div class="form-group">
<label class="center-block">State:
<select class="form-control" formControlName="state">
<option *ngFor="let state of states" [value]="state">{{state}}</option>
</select>
</label>
</div>
<div class="form-group">
<label class="center-block">Zip Code:
<input class="form-control" formControlName="zip">
</label>
</div>
</div>
<br>
<!-- End of the repeated address template -->
<!-- #docregion form-array-skeleton -->
</div>
<!-- #enddocregion form-array-skeleton -->
<!-- #enddocregion form-array-->
<!-- #docregion add-lair -->
<button (click)="addLair()" type="button">Add a Secret Lair</button>
<!-- #enddocregion add-lair -->
<!-- #docregion form-array-->
<!-- #docregion form-array-skeleton -->
</div>
<!-- #enddocregion form-array-skeleton -->
<!-- #enddocregion form-array-->
<div class="form-group radio">
<h4>Super power:</h4>
<label class="center-block"><input type="radio" formControlName="power" value="flight">Flight</label>
<label class="center-block"><input type="radio" formControlName="power" value="x-ray vision">X-ray vision</label>
<label class="center-block"><input type="radio" formControlName="power" value="strength">Strength</label>
</div>
<div class="checkbox">
<label class="center-block">
<input type="checkbox" formControlName="sidekick">I have a sidekick.
</label>
</div>
</form>
<p>heroForm value: {{ heroForm.value | json}}</p>

View File

@ -1,74 +0,0 @@
/* tslint:disable:component-class-suffix */
// #docregion imports
import { Component, Input, OnChanges } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Address, Hero, states } from '../data-model';
// #enddocregion imports
@Component({
selector: 'app-hero-detail-8',
templateUrl: './hero-detail-8.component.html'
})
// #docregion v8
export class HeroDetailComponent8 implements OnChanges {
@Input() hero: Hero;
heroForm: FormGroup;
states = states;
// #docregion ctor
constructor(private fb: FormBuilder) {
this.createForm();
this.logNameChange();
}
// #enddocregion ctor
createForm() {
// #docregion secretLairs-form-array
this.heroForm = this.fb.group({
name: ['', Validators.required ],
secretLairs: this.fb.array([]), // <-- secretLairs as an empty FormArray
power: '',
sidekick: ''
});
// #enddocregion secretLairs-form-array
}
logNameChange() {/* Coming soon */}
// #docregion onchanges
ngOnChanges() {
this.rebuildForm();
}
// #enddocregion onchanges
// #docregion rebuildform
rebuildForm() {
this.heroForm.reset({
name: this.hero.name
});
this.setAddresses(this.hero.addresses);
}
// #enddocregion rebuildform
// #docregion get-secret-lairs
get secretLairs(): FormArray {
return this.heroForm.get('secretLairs') as FormArray;
};
// #enddocregion get-secret-lairs
// #docregion set-addresses
setAddresses(addresses: Address[]) {
const addressFGs = addresses.map(address => this.fb.group(address));
const addressFormArray = this.fb.array(addressFGs);
this.heroForm.setControl('secretLairs', addressFormArray);
}
// #enddocregion set-addresses
// #docregion add-lair
addLair() {
this.secretLairs.push(this.fb.group(new Address()));
}
// #enddocregion add-lair
}

View File

@ -1,73 +0,0 @@
<!-- #docplaster -->
<!-- #docregion -->
<!-- #docregion buttons -->
<form [formGroup]="heroForm" (ngSubmit)="onSubmit()">
<div style="margin-bottom: 1em">
<button type="submit"
[disabled]="heroForm.pristine" class="btn btn-success">Save</button> &nbsp;
<button type="button" (click)="revert()"
[disabled]="heroForm.pristine" class="btn btn-danger">Revert</button>
</div>
<!-- Hero Detail Controls -->
<!-- #enddocregion buttons -->
<div class="form-group">
<label class="center-block">Name:
<input class="form-control" formControlName="name">
</label>
</div>
<div formArrayName="secretLairs" class="well well-lg">
<div *ngFor="let address of secretLairs.controls; let i=index" [formGroupName]="i" >
<!-- The repeated address template -->
<h4>Address #{{i + 1}}</h4>
<div style="margin-left: 1em;">
<div class="form-group">
<label class="center-block">Street:
<input class="form-control" formControlName="street">
</label>
</div>
<div class="form-group">
<label class="center-block">City:
<input class="form-control" formControlName="city">
</label>
</div>
<div class="form-group">
<label class="center-block">State:
<select class="form-control" formControlName="state">
<option *ngFor="let state of states" [value]="state">{{state}}</option>
</select>
</label>
</div>
<div class="form-group">
<label class="center-block">Zip Code:
<input class="form-control" formControlName="zip">
</label>
</div>
</div>
<br>
<!-- End of the repeated address template -->
</div>
<button (click)="addLair()" type="button">Add a Secret Lair</button>
</div>
<!-- #docregion buttons -->
<div class="form-group radio">
<h4>Super power:</h4>
<label class="center-block"><input type="radio" formControlName="power" value="flight">Flight</label>
<label class="center-block"><input type="radio" formControlName="power" value="x-ray vision">X-ray vision</label>
<label class="center-block"><input type="radio" formControlName="power" value="strength">Strength</label>
</div>
<div class="checkbox">
<label class="center-block">
<input type="checkbox" formControlName="sidekick">I have a sidekick.
</label>
</div>
</form>
<!-- #enddocregion buttons -->
<p>heroForm value: {{ heroForm.value | json}}</p>
<!-- #docregion name-change-log -->
<h4>Name change log</h4>
<div *ngFor="let name of nameChangeLog">{{name}}</div>
<!-- #enddocregion name-change-log -->

View File

@ -1,113 +0,0 @@
// #docplaster
// #docregion
import { Component, Input, OnChanges } from '@angular/core';
import { FormArray, FormBuilder, FormGroup } from '@angular/forms';
import { Address, Hero, states } from '../data-model';
// #docregion import-service
import { HeroService } from '../hero.service';
// #enddocregion import-service
@Component({
selector: 'app-hero-detail',
templateUrl: './hero-detail.component.html',
styleUrls: ['./hero-detail.component.css']
})
// #docregion onchanges-implementation
export class HeroDetailComponent implements OnChanges {
// #enddocregion onchanges-implementation
@Input() hero: Hero;
heroForm: FormGroup;
// #docregion log-name-change
nameChangeLog: string[] = [];
// #enddocregion log-name-change
states = states;
// #docregion ctor
constructor(
private fb: FormBuilder,
private heroService: HeroService) {
this.createForm();
this.logNameChange();
}
// #enddocregion ctor
createForm() {
this.heroForm = this.fb.group({
name: '',
secretLairs: this.fb.array([]),
power: '',
sidekick: ''
});
}
ngOnChanges() {
this.rebuildForm();
}
rebuildForm() {
this.heroForm.reset({
name: this.hero.name
});
this.setAddresses(this.hero.addresses);
}
get secretLairs(): FormArray {
return this.heroForm.get('secretLairs') as FormArray;
};
setAddresses(addresses: Address[]) {
const addressFGs = addresses.map(address => this.fb.group(address));
const addressFormArray = this.fb.array(addressFGs);
this.heroForm.setControl('secretLairs', addressFormArray);
}
addLair() {
this.secretLairs.push(this.fb.group(new Address()));
}
// #docregion on-submit
onSubmit() {
this.hero = this.prepareSaveHero();
this.heroService.updateHero(this.hero).subscribe(/* error handling */);
this.rebuildForm();
}
// #enddocregion on-submit
// #docregion prepare-save-hero
prepareSaveHero(): Hero {
const formModel = this.heroForm.value;
// deep copy of form model lairs
const secretLairsDeepCopy: Address[] = formModel.secretLairs.map(
(address: Address) => Object.assign({}, address)
);
// return new `Hero` object containing a combination of original hero value(s)
// and deep copies of changed form model values
const saveHero: Hero = {
id: this.hero.id,
name: formModel.name as string,
// addresses: formModel.secretLairs // <-- bad!
addresses: secretLairsDeepCopy
};
return saveHero;
}
// #enddocregion prepare-save-hero
// #docregion revert
revert() { this.rebuildForm(); }
// #enddocregion revert
// #docregion log-name-change
logNameChange() {
const nameControl = this.heroForm.get('name');
nameControl.valueChanges.forEach(
(value: string) => this.nameChangeLog.push(value)
);
}
// #enddocregion log-name-change
}

View File

@ -1,8 +0,0 @@
<!-- #docregion -->
<nav>
<a *ngFor="let hero of heroes | async" (click)="select(hero)">{{hero.name}}</a>
</nav>
<div *ngIf="selectedHero">
<app-hero-detail [hero]="selectedHero"></app-hero-detail>
</div>

View File

@ -1,17 +0,0 @@
<!-- #docregion -->
<h3 *ngIf="isLoading"><i>Loading heroes ... </i></h3>
<h3 *ngIf="!isLoading">Select a hero:</h3>
<nav>
<button (click)="getHeroes()" class="btn btn-primary">Refresh</button>
<a *ngFor="let hero of heroes | async" (click)="select(hero)">{{hero.name}}</a>
</nav>
<div *ngIf="selectedHero">
<hr>
<h2>Hero Detail</h2>
<h3>Editing: {{selectedHero.name}}</h3>
<!-- #docregion hero-binding -->
<app-hero-detail [hero]="selectedHero"></app-hero-detail>
<!-- #enddocregion hero-binding -->
</div>

View File

@ -1,32 +0,0 @@
// #docregion
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { finalize } from 'rxjs/operators';
import { Hero } from '../data-model';
import { HeroService } from '../hero.service';
@Component({
selector: 'app-hero-list',
templateUrl: './hero-list.component.html',
styleUrls: ['./hero-list.component.css']
})
export class HeroListComponent implements OnInit {
heroes: Observable<Hero[]>;
isLoading = false;
selectedHero: Hero;
constructor(private heroService: HeroService) { }
ngOnInit() { this.getHeroes(); }
getHeroes() {
this.isLoading = true;
this.heroes = this.heroService.getHeroes()
// TODO: error handling
.pipe(finalize(() => this.isLoading = false));
this.selectedHero = undefined;
}
select(hero: Hero) { this.selectedHero = hero; }
}

View File

@ -1,25 +0,0 @@
// #docregion
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { delay } from 'rxjs/operators';
import { Hero, heroes } from './data-model';
@Injectable()
export class HeroService {
delayMs = 500;
// Fake server get; assume nothing can go wrong
getHeroes(): Observable<Hero[]> {
return of(heroes).pipe(delay(this.delayMs)); // simulate latency with delay
}
// Fake server update; assume nothing can go wrong
updateHero(hero: Hero): Observable<Hero> {
const oldHero = heroes.find(h => h.id === hero.id);
const newHero = Object.assign(oldHero, hero); // Demo: mutate cached hero
return of(newHero).pipe(delay(this.delayMs)); // simulate latency with delay
}
}

View File

@ -0,0 +1,19 @@
:host {
display: flex;
flex-direction: column;
padding-top: 24px;
}
label {
display: block;
width: 6em;
margin: .5em 0;
color: #607D8B;
font-weight: bold;
}
input {
height: 2em;
font-size: 1em;
padding-left: .4em;
}

View File

@ -0,0 +1,21 @@
<!-- #docregion control-binding -->
<label>
Name:
<input type="text" [formControl]="name">
</label>
<!-- #enddocregion control-binding -->
<!-- #docregion display-value -->
<p>
Value: {{ name.value }}
</p>
<!-- #enddocregion display-value -->
<!-- #docregion update-value -->
<p>
<button (click)="updateName()">Update Name</button>
</p>
<!-- #enddocregion update-value -->

View File

@ -0,0 +1,22 @@
// #docplaster
// #docregion create-control
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'app-name-editor',
templateUrl: './name-editor.component.html',
styleUrls: ['./name-editor.component.css']
})
export class NameEditorComponent {
name = new FormControl('');
// #enddocregion create-control
// #docregion update-value
updateName() {
this.name.setValue('Nancy');
}
// #enddocregion update-value
// #docregion create-control
}
// #enddocregion create-control

View File

@ -0,0 +1,67 @@
<!-- #docplaster -->
<!-- #docregion formgroup -->
<form [formGroup]="profileForm">
<label>
First Name:
<input type="text" formControlName="firstName">
</label>
<label>
Last Name:
<input type="text" formControlName="lastName">
</label>
<!-- #enddocregion formgroup -->
<!-- #docregion formgroupname -->
<div formGroupName="address">
<h3>Address</h3>
<label>
Street:
<input type="text" formControlName="street">
</label>
<label>
City:
<input type="text" formControlName="city">
</label>
<label>
State:
<input type="text" formControlName="state">
</label>
<label>
Zip Code:
<input type="text" formControlName="zip">
</label>
</div>
<!-- #enddocregion formgroupname -->
<!-- #docregion formarrayname -->
<div formArrayName="aliases">
<h3>Aliases</h3> <button (click)="addAlias()">Add Alias</button>
<div *ngFor="let address of aliases.controls; let i=index">
<!-- The repeated alias template -->
<label>
Alias:
<input type="text" [formControlName]="i">
</label>
</div>
</div>
<!-- #enddocregion formarrayname -->
<!-- #docregion formgroup -->
</form>
<!-- #enddocregion formgroup -->
<p>
Form Value: {{ profileForm.value | json }}
</p>
<!-- #docregion patch-value -->
<p>
<button (click)="updateProfile()">Update Profile</button>
</p>
<!-- #enddocregion patch-value -->

View File

@ -0,0 +1,40 @@
// #docplaster
// #docregion formgroup, nested-formgroup
import { Component } from '@angular/core';
// #docregion imports
import { FormGroup, FormControl } from '@angular/forms';
// #enddocregion imports
@Component({
selector: 'app-profile-editor',
templateUrl: './profile-editor.component.html',
styleUrls: ['./profile-editor.component.css']
})
export class ProfileEditorComponent {
// #docregion formgroup-compare
profileForm = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl(''),
// #enddocregion formgroup
address: new FormGroup({
street: new FormControl(''),
city: new FormControl(''),
state: new FormControl(''),
zip: new FormControl('')
})
// #docregion formgroup
});
// #enddocregion formgroup, nested-formgroup, formgroup-compare
// #docregion patch-value
updateProfile() {
this.profileForm.patchValue({
firstName: 'Nancy',
address: {
street: '123 Drew Street'
}
});
}
// #enddocregion patch-value
// #docregion formgroup, nested-formgroup
}
// #enddocregion formgroup

View File

@ -0,0 +1,58 @@
// #docplaster
// #docregion form-builder
import { Component } from '@angular/core';
// #docregion form-builder-imports
import { FormBuilder } from '@angular/forms';
// #enddocregion form-builder-imports, form-builder
// #docregion form-array-imports
import { FormArray } from '@angular/forms';
// #docregion form-builder-imports, form-builder
// #enddocregion form-builder-imports, form-array-imports
@Component({
selector: 'app-profile-editor',
templateUrl: './profile-editor.component.html',
styleUrls: ['./profile-editor.component.css']
})
export class ProfileEditorComponent {
// #docregion formgroup-compare
profileForm = this.fb.group({
firstName: [''],
lastName: [''],
address: this.fb.group({
street: [''],
city: [''],
state: [''],
zip: ['']
}),
// #enddocregion form-builder, formgroup-compare
aliases: this.fb.array([
this.fb.control('')
])
// #docregion form-builder, formgroup-compare
});
// #enddocregion form-builder, formgroup-compare
get aliases() {
return this.profileForm.get('aliases') as FormArray;
}
// #docregion inject-form-builder, form-builder
constructor(private fb: FormBuilder) { }
// #enddocregion inject-form-builder, form-builder
updateProfile() {
this.profileForm.patchValue({
firstName: 'Nancy',
address: {
street: '123 Drew Street'
}
});
}
addAlias() {
this.aliases.push(this.fb.control(''));
}
// #docregion form-builder
}
// #enddocregion form-builder

View File

@ -0,0 +1,39 @@
/* ProfileEditorComponent's private CSS styles */
:host {
display: flex;
flex-direction: column;
padding-top: 24px;
}
label {
display: block;
width: 6em;
margin: .5em 0;
color: #607D8B;
font-weight: bold;
}
input {
height: 2em;
font-size: 1em;
padding-left: .4em;
}
button {
font-family: Arial;
background-color: #eee;
border: none;
padding: 5px 10px;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #cfd8dc;
}
button:disabled {
background-color: #eee;
color: #ccc;
cursor: auto;
}

View File

@ -0,0 +1,80 @@
<!-- #docplaster -->
<!-- #docregion ng-submit -->
<form [formGroup]="profileForm" (ngSubmit)="onSubmit()">
<!-- #enddocregion ng-submit -->
<label>
First Name:
<!-- #docregion required-attribute -->
<input type="text" formControlName="firstName" required>
<!-- #enddocregion required-attribute -->
</label>
<label>
Last Name:
<input type="text" formControlName="lastName">
</label>
<div formGroupName="address">
<h3>Address</h3>
<label>
Street:
<input type="text" formControlName="street">
</label>
<label>
City:
<input type="text" formControlName="city">
</label>
<label>
State:
<input type="text" formControlName="state">
</label>
<label>
Zip Code:
<input type="text" formControlName="zip">
</label>
</div>
<!-- #docregion formarrayname -->
<div formArrayName="aliases">
<h3>Aliases</h3> <button (click)="addAlias()">Add Alias</button>
<div *ngFor="let address of aliases.controls; let i=index">
<!-- The repeated alias template -->
<label>
Alias:
<input type="text" [formControlName]="i">
</label>
</div>
</div>
<!-- #enddocregion formarrayname -->
<!-- #docregion submit-button -->
<button type="submit" [disabled]="!profileForm.valid">Submit</button>
<!-- #enddocregion submit-button -->
</form>
<hr>
<!-- #docregion display-value -->
<p>
Form Value: {{ profileForm.value | json }}
</p>
<!-- #enddocregion display-value -->
<!-- #docregion display-status -->
<p>
Form Status: {{ profileForm.status }}
</p>
<!-- #enddocregion display-status -->
<!-- #docregion patch-value -->
<p>
<button (click)="updateProfile()">Update Profile</button>
</p>
<!-- #enddocregion patch-value -->

View File

@ -0,0 +1,73 @@
// #docplaster
// #docregion form-builder
import { Component } from '@angular/core';
// #docregion form-builder-imports
import { FormBuilder } from '@angular/forms';
// #enddocregion form-builder-imports
// #docregion validator-imports
import { Validators } from '@angular/forms';
// #enddocregion validator-imports
// #docregion form-array-imports
import { FormArray } from '@angular/forms';
// #enddocregion form-array-imports
@Component({
selector: 'app-profile-editor',
templateUrl: './profile-editor.component.html',
styleUrls: ['./profile-editor.component.css']
})
export class ProfileEditorComponent {
// #docregion required-validator, aliases
profileForm = this.fb.group({
firstName: ['', Validators.required],
lastName: [''],
address: this.fb.group({
street: [''],
city: [''],
state: [''],
zip: ['']
}),
// #enddocregion form-builder, required-validator
aliases: this.fb.array([
this.fb.control('')
])
// #docregion form-builder, required-validator
});
// #enddocregion form-builder, required-validator, aliases
// #docregion aliases-getter
get aliases() {
return this.profileForm.get('aliases') as FormArray;
}
// #enddocregion aliases-getter
// #docregion inject-form-builder, form-builder
constructor(private fb: FormBuilder) { }
// #enddocregion inject-form-builder
updateProfile() {
this.profileForm.patchValue({
firstName: 'Nancy',
address: {
street: '123 Drew Street'
}
});
}
// #enddocregion form-builder
// #docregion add-alias
addAlias() {
this.aliases.push(this.fb.control(''));
}
// #enddocregion add-alias
// #docregion on-submit
onSubmit() {
// TODO: Use EventEmitter with form value
console.warn(this.profileForm.value);
}
// #enddocregion on-submit
// #docregion form-builder
}
// #enddocregion form-builder

View File

@ -1,17 +0,0 @@
<!DOCTYPE html>
<!-- #docregion -->
<html lang="en">
<head>
<title>Hero Form</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- #docregion bootstrap -->
<link rel="stylesheet" href="https://unpkg.com/bootstrap@3.3.7/dist/css/bootstrap.min.css">
</head>
<body>
<app-root></app-root>
</body>
</html>

View File

@ -2,10 +2,9 @@
<!-- #docregion -->
<html lang="en">
<head>
<title>Hero Form</title>
<title>Angular Reactive Forms</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://unpkg.com/bootstrap@3.3.7/dist/css/bootstrap.min.css">
</head>
<body>

View File

@ -2,12 +2,11 @@
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module'; // just the final version
import { DemoModule } from './app/demo.module'; // demo picker
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(DemoModule);
platformBrowserDynamic().bootstrapModule(AppModule);

View File

@ -1 +0,0 @@
@import url('https://unpkg.com/bootstrap@3.3.7/dist/css/bootstrap.min.css');

View File

@ -3,6 +3,7 @@
"files":[
"!**/*.d.ts",
"!**/*.js",
"!**/*.[0-9].*",
"!src/app/app.component.1.ts",
"!src/app/hero-list.component.1.html",

View File

@ -8,7 +8,7 @@ const nums = of(1, 2, 3, 4, 5);
// Create a function that accepts an Observable.
const squareOddVals = pipe(
filter(n => n % 2),
filter((n: number) => n % 2 !== 0),
map(n => n * n)
);

View File

@ -9,6 +9,6 @@ import { HeroService } from './heroes';
<toh-heroes></toh-heroes>
`,
styleUrls: ['./app.component.css'],
providers: [ HeroService ]
providers: [HeroService]
})
export class AppComponent { }
export class AppComponent {}

View File

@ -1,9 +1,8 @@
// #docregion
/* avoid */
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { Component, NgModule, OnInit } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, Component, OnInit } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
class Hero {
id: number;
@ -24,24 +23,24 @@ class AppComponent implements OnInit {
heroes: Hero[] = [];
ngOnInit() {
getHeroes().then(heroes => this.heroes = heroes);
getHeroes().then(heroes => (this.heroes = heroes));
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent ],
exports: [ AppComponent ],
bootstrap: [ AppComponent ]
imports: [BrowserModule],
declarations: [AppComponent],
exports: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
export class AppModule {}
platformBrowserDynamic().bootstrapModule(AppModule);
const HEROES: Hero[] = [
{id: 1, name: 'Bombasto'},
{id: 2, name: 'Tornado'},
{id: 3, name: 'Magneta'},
{ id: 1, name: 'Bombasto' },
{ id: 2, name: 'Tornado' },
{ id: 3, name: 'Magneta' }
];
function getHeroes(): Promise<Hero[]> {

View File

@ -2,7 +2,7 @@
import { Hero } from './hero.model';
export const HEROES: Hero[] = [
{id: 1, name: 'Bombasto'},
{id: 2, name: 'Tornado'},
{id: 3, name: 'Magneta'},
{ id: 1, name: 'Bombasto' },
{ id: 2, name: 'Tornado' },
{ id: 3, name: 'Magneta' }
];

View File

@ -1,6 +1,6 @@
// #docregion
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { AppModule } from './app/app.module';
platformBrowserDynamic().bootstrapModule(AppModule);

View File

@ -3,9 +3,8 @@
/* avoid */
import { ExceptionService, SpinnerService, ToastService } from '../../core';
import { Http } from '@angular/http';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators';
import { Hero } from './hero.model';
// #enddocregion example
@ -16,18 +15,15 @@ export class HeroService {
private exceptionService: ExceptionService,
private spinnerService: SpinnerService,
private toastService: ToastService,
private http: Http
private http: HttpClient
) { }
getHero(id: number) {
return this.http.get(`api/heroes/${id}`).pipe(
map(response => response.json().data as Hero));
return this.http.get<Hero>(`api/heroes/${id}`);
}
getHeroes() {
return this.http.get(`api/heroes`).pipe(
map(response => response.json().data as Hero[]));
return this.http.get<Hero[]>(`api/heroes`);
}
}

View File

@ -1,11 +1,11 @@
// #docregion
// #docregion example
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { map } from 'rxjs/operators';
import { Hero } from './hero.model';
import { ExceptionService, SpinnerService, ToastService } from '../../core';
import { Hero } from './hero.model';
// #enddocregion example
@Injectable()
@ -16,18 +16,15 @@ export class HeroService {
private exceptionService: ExceptionService,
private spinnerService: SpinnerService,
private toastService: ToastService,
private http: Http
private http: HttpClient
) { }
getHero(id: number) {
return this.http.get(`api/heroes/${id}`).pipe(
map(response => response.json() as Hero));
return this.http.get<Hero>(`api/heroes/${id}`);
}
getHeroes() {
return this.http.get(`api/heroes`).pipe(
map(response => response.json() as Hero[]));
return this.http.get<Hero[]>(`api/heroes`);
}
}

View File

@ -3,15 +3,15 @@
<!-- #enddocregion show-hero-1 -->
<!-- #docregion show-hero-2 -->
<h2>{{ hero.name }} Details</h2>
<h2>{{hero.name}} Details</h2>
<div><span>id: </span>{{hero.id}}</div>
<div><span>name: </span>{{hero.name}}</div>
<!-- #enddocregion show-hero-2 -->
<!-- #docregion name-input -->
<div>
<label>name:
<input [(ngModel)]="hero.name" placeholder="name">
</label>
<label>name:
<input [(ngModel)]="hero.name" placeholder="name">
</label>
</div>
<!-- #enddocregion name-input -->

View File

@ -1,10 +1,10 @@
<!-- #docregion -->
<!-- #docregion pipe -->
<h2>{{ hero.name | uppercase }} Details</h2>
<h2>{{hero.name | uppercase}} Details</h2>
<!-- #enddocregion pipe -->
<div><span>id: </span>{{hero.id}}</div>
<div>
<label>name:
<input [(ngModel)]="hero.name" placeholder="name">
</label>
<label>name:
<input [(ngModel)]="hero.name" placeholder="name">
</label>
</div>

View File

@ -14,7 +14,7 @@
<div *ngIf="selectedHero">
<!-- #docregion selectedHero-details -->
<h2>{{ selectedHero.name | uppercase }} Details</h2>
<h2>{{selectedHero.name | uppercase}} Details</h2>
<div><span>id: </span>{{selectedHero.id}}</div>
<div>
<label>name:

View File

@ -1,6 +1,6 @@
<div *ngIf="hero">
<h2>{{ hero.name | uppercase }} Details</h2>
<h2>{{hero.name | uppercase}} Details</h2>
<div><span>id: </span>{{hero.id}}</div>
<div>
<label>name:

View File

@ -1,5 +1,5 @@
<div *ngIf="hero">
<h2>{{ hero.name | uppercase }} Details</h2>
<h2>{{hero.name | uppercase}} Details</h2>
<div><span>id: </span>{{hero.id}}</div>
<div>
<label>name:

View File

@ -1,5 +1,5 @@
<div *ngIf="hero">
<h2>{{ hero.name | uppercase }} Details</h2>
<h2>{{hero.name | uppercase}} Details</h2>
<div><span>id: </span>{{hero.id}}</div>
<div>
<label>name:

View File

@ -1,16 +1,36 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { DashboardComponent } from './dashboard.component';
import { HeroSearchComponent } from '../hero-search/hero-search.component';
import { RouterTestingModule } from '@angular/router/testing';
import { of } from 'rxjs';
import { HEROES } from '../mock-heroes';
import { HeroService } from '../hero.service';
describe('DashboardComponent', () => {
let component: DashboardComponent;
let fixture: ComponentFixture<DashboardComponent>;
let heroService;
let getHeroesSpy;
beforeEach(async(() => {
heroService = jasmine.createSpyObj('HeroService', ['getHeroes']);
getHeroesSpy = heroService.getHeroes.and.returnValue( of(HEROES) );
TestBed.configureTestingModule({
declarations: [ DashboardComponent ]
declarations: [
DashboardComponent,
HeroSearchComponent
],
imports: [
RouterTestingModule.withRoutes([])
],
providers: [
{ provide: HeroService, useValue: heroService }
]
})
.compileComponents();
}));
beforeEach(() => {
@ -22,4 +42,17 @@ describe('DashboardComponent', () => {
it('should be created', () => {
expect(component).toBeTruthy();
});
it('should display "Top Heroes" as headline', () => {
expect(fixture.nativeElement.querySelector('h3').textContent).toEqual('Top Heroes');
});
it('should call heroService', async(() => {
expect(getHeroesSpy.calls.any()).toBe(true);
}));
it('should display 4 links', async(() => {
expect(fixture.nativeElement.querySelectorAll('a').length).toEqual(4);
}));
});

Some files were not shown because too many files have changed in this diff Show More