Compare commits

...

236 Commits

Author SHA1 Message Date
Jessica Janiuk 35690fdf6d release: cut the v15.2.8 release 2023-04-19 12:13:35 -07:00
lonikadze 3d7b8cdb4d docs: add information on how to use index option in configuration (#49813)
#49780

PR Close #49813
2023-04-19 18:46:10 +00:00
Kristiyan Kostadinov 2fff8fadbe fix(core): handle invalid classes in class array bindings (#49924)
When binding an array to `class` like `[class]="['foo', 'bar']"`, the runtime treats it the same as a literal binding with all the values being `true`, e.g. `{foo: true, bar: true}`. While object literals can only have string keys, arrays can have any value which can lead to errors if the array contains non-string values.

These changes add some logic to stringify the keys and ignore invalid ones.

Fixes #48473.

PR Close #49924
2023-04-19 16:28:26 +00:00
Lars Gyrup Brink Nielsen 0454158084 docs(core): add version ranges for Angular 14.3 (#48753)
PR Close #48753
2023-04-19 14:07:31 +00:00
Lars Gyrup Brink Nielsen 1575f9d8f3 docs: change section heading (#48753)
Co-authored-by: Daniel Scalzi <d_scalzi@yahoo.com>
PR Close #48753
2023-04-19 14:07:31 +00:00
Lars Gyrup Brink Nielsen fc428f0443 docs(core): add version ranges for Angular 15.2 (#48753)
PR Close #48753
2023-04-19 14:07:31 +00:00
Lars Gyrup Brink Nielsen 9fa0ab5151 docs(core): split versions table into LTS and non-LTS tables (#48753)
PR Close #48753
2023-04-19 14:07:31 +00:00
Lars Gyrup Brink Nielsen 2a59e19886 docs(docs-infra): add versions document to code owners (#48753)
PR Close #48753
2023-04-19 14:07:31 +00:00
Lars Gyrup Brink Nielsen 4d8b164d3c docs(docs-infra): add versions document to the navigation (#48753)
PR Close #48753
2023-04-19 14:07:31 +00:00
Lars Gyrup Brink Nielsen b13587c802 docs(core): include introductory text about version compatibility (#48753)
PR Close #48753
2023-04-19 14:07:31 +00:00
Lars Gyrup Brink Nielsen 2f64981f7c docs(core): add Angular, Node.js, TypeScript, and RxJS version compatibility matrix (#48753)
PR Close #48753
2023-04-19 14:07:31 +00:00
Angular Robot f02812d00e docs: update events (#49569)
Generated `events.json` with the latest events retrieved from the Firebase DB.

Closes #49545

PR Close #49569
2023-04-19 14:05:45 +00:00
Angular Robot f3907e1654 build: update angular/dev-infra digest to 1564c4e patch (#49917)
See associated pull request for more information.

PR Close #49917
2023-04-19 14:04:57 +00:00
arturovt 296459ac16 docs: add Artur Androsovych to GDE resources (#48520)
PR Close #48520
2023-04-18 21:35:45 +00:00
Angular Robot 279e9e7fdb build: update dependency build_bazel_rules_nodejs to v5.8.2 (#49910)
See associated pull request for more information.

PR Close #49910
2023-04-18 20:45:24 +00:00
Angular Robot 6a939562ea build: update cross-repo angular dependencies (#49891) patch PR (#49913)
See associated pull request for more information.

Patch of #49891

PR Close #49913
2023-04-18 20:15:42 +00:00
Angular Robot b9e1e7e308 build: update actions/cache digest to 88522ab (#49437)
See associated pull request for more information.

PR Close #49437
2023-04-18 19:46:16 +00:00
Angular Robot 77eb4d8ecf build: update dependency google-closure-compiler to v20230411 (#49892) (#49912)
See associated pull request for more information.

PR Close #49892

PR Close #49912
2023-04-18 19:45:23 +00:00
Douglas Diniz Carvalho 48c946f8c9 docs: type clearTimer function as VoidFunction or undefined (#48480)
PR Close #48480
2023-04-18 19:03:58 +00:00
Douglas Diniz Carvalho 81ad3c62d6 docs: standardize examples using timers for SSR compatibility (#48480)
PR Close #48480
2023-04-18 19:03:57 +00:00
CodeMaster7000 cab701d0ee docs: update README.md (#48423)
PR Close #48423
2023-04-18 16:59:38 +00:00
Vasil Chimev 70ef08fc31 docs: typos and wording (#48597)
PR Close #48597
2023-04-18 16:58:31 +00:00
Vladyslav Makarenko 5a13eb8da0 docs: add a dot (#49434)
The first sentence misses a dot in the end, however other sentences have it
PR Close #49434
2023-04-18 16:22:51 +00:00
Ikko Eltociear Ashimine 3dc43e3577 refactor: fix typo in windows-chromium-path.js (#49676)
preceeding -> preceding
PR Close #49676
2023-04-18 16:22:10 +00:00
John Manners 9abe0d6d32 docs: fix errors in toh-pt6.md (#49129)
Line 182 and line 185 - grammatical and typo errors.
PR Close #49129
2023-04-18 16:21:35 +00:00
Angular Robot c75fe04e28 build: update io_bazel_rules_sass digest to 898e4dd (#49575)
See associated pull request for more information.

PR Close #49575
2023-04-18 16:20:54 +00:00
Matthieu Riegler bce7f6bfd9 refactor(core): Remove ununsed Zone mock from testing internals. (#49873)
The last time it was used in was on the v10 branch.

PR Close #49873
2023-04-18 14:00:16 +00:00
Angular Robot edfc087998 build: update scorecard action dependencies (#49897)
See associated pull request for more information.

PR Close #49897
2023-04-18 13:58:54 +00:00
Lara Newsom 1d4cf95a94 docs(docs-infra): add lara newsom to GDE resources (#49620)
PR Close #49620
2023-04-17 18:31:14 +00:00
Matthieu Riegler 79a8b3c049 docs: Specify when an app is debuggable by the DevTools. (#48970)
DevMode is when the ng debug object is available. `Optimization:true` is responsible for treeshaking everything behind `ngDevMode`.

Fixes #48968

PR Close #48970
2023-04-17 17:32:42 +00:00
Matthieu Riegler fe20496554 fix(devtools): Specify when an app is considered in dev mode. (#48970)
DevMode is when the ng debug object is available. `Optimization:true` is responsible for treeshaking everything behind `ngDevMode`.

PR Close #48970
2023-04-17 17:32:42 +00:00
Matthieu Riegler 461503be8e refactor(compiler-cli): cleanup inferences (#49863)
With the ts compiler updates these inferences have been fixed.

PR Close #49863
2023-04-17 17:23:30 +00:00
Angular Robot 628c52055a build: update dependency eslint-plugin-jsdoc to v41 (#49885)
See associated pull request for more information.

PR Close #49885
2023-04-17 15:48:24 +00:00
Andrew Scott 0a9d1060b9 refactor(router): Do not access browserPageId if not computed resolution (#49850)
This commit avoids accessing the routerPageId if the
canceldNavigationResolution is not computed.

PR Close #49850
2023-04-17 14:47:16 +00:00
Matthieu Riegler 1017630d04 refactor(docs-infra): cleanup deprecated code (#49671)
This commit replaces (non material-related) deprecated code present in the aio app.

* `pageYOffset` can be replaced by `scrollY`
*  RxJs' `mapTo()` is just a `map()`
* `createNgModuleRef` can be replaced by `createNgModule`
* HttpEmits `ProgressEvent` not `ErrorEvent`  (see #34748)
* `SwUpdate.available` is replaced by  `versionUpdates` with a `filter`
* `SwUpdate.activated` is replaced by the returned promised of `SwUpdate.activateUpdate`.

PR Close #49671
2023-04-17 14:04:26 +00:00
Matthieu Riegler 08ba49296a refactor(core): improve styling coverage (#49868)
The test was waiting for #34202 to be merged.

PR Close #49868
2023-04-17 14:02:41 +00:00
Matthieu Riegler aad9db2c5c docs: remove outdated/unsupported webworker doc (#49856)
The webworker platform has been removed in v11 by #38846

PR Close #49856
2023-04-17 14:01:41 +00:00
Qiuran Hu b6f119e182 docs: fix typo in Hierarchical injectors doc (#49824)
PR Close #49824
2023-04-17 13:59:09 +00:00
ChrTall a6f2c03204 docs: Fixed Typo (#49753)
Fixed Typo
PR Close #49753
2023-04-17 13:58:16 +00:00
Angular Robot a63d9a30d8 build: update actions/checkout digest to 8e5e7e5 (#49815)
See associated pull request for more information.

PR Close #49815
2023-04-17 13:31:20 +00:00
Andrew Scott 09a42d988e fix(router): canceledNavigationResolution: 'computed' with redirects to the current URL (#49793)
The `canceledNavigationResolution: 'computed'` option does not correctly
assign page IDs or restore them when redirects result in navigating to
the current URL. This change ensures that the page IDs are still
incremented and restored correctly in this scenario.

PR Close #49793
2023-04-14 14:55:06 +00:00
Matthieu Riegler 8235bc94f7 ci: Remove environment files and EnableProdMode on integration tests (#49746)
Since v15, prod mode is handled by the CLI with the `optimization` flag. We can remove the environement files and `enableProdMode` when the tests use the CLI.

PR Close #49746
2023-04-14 14:13:33 +00:00
Matthieu Riegler f266a05d2f refactor(core): drop IE workarounds (#49763)
Angular doesn't support IE anymore. We can remove the workarounds related to IE.

Some workarounds are keep because of the support of domino but the comments related to IE are removed.

PR Close #49763
2023-04-13 14:01:45 +00:00
Danilo Bassi 05a0225deb fix(http): prevent headers from throwing an error when initializing numerical values (#49379)
Some libraries could use numbers in headers. this fix prevents Angular from
throwing an error by casting those numerical values into strings.

Fixes #49353

PR Close #49379
2023-04-13 14:00:17 +00:00
Andrew Kushnir 1d761bd7c7 release: cut the v15.2.7 release 2023-04-12 12:06:05 -07:00
Angular Robot 2c140f4871 build: update github/codeql-action action to v2.2.11 (#49775)
See associated pull request for more information.

PR Close #49775
2023-04-12 09:26:03 -07:00
Alan Agius a3de0c3cea docs: remove preboot reference from universal doc (#49808)
This package is no longer actively maintained and in general is not needed.

PR Close #49808
2023-04-12 09:24:05 -07:00
Andrew Scott b0c1a90f55 fix(compiler): Produce diagnositc if directive used in host binding is not exported (#49792)
The compiler currently does not check to make sure that directives in
the host bindings are exported. These directives are part of the public
API of the component so they do have to be.

PR Close #49792
2023-04-11 14:39:03 -07:00
Andrew Scott a40529af2e fix(compiler-cli): Catch FatalDiagnosticError during template type checking (#49792)
This commit updates the type checking operation to catch
`FatalDiagnosticError` and surface them as diagnostics rather than
crashing.

Fixes https://github.com/angular/vscode-ng-language-service/issues/1881

PR Close #49792
2023-04-11 14:39:03 -07:00
Andrew Kushnir ebd14e79fb build: update minimum supported Node version from 16.13.0 -> 16.14.0 for CI and AIO (#49790)
This commit updates the minimum supported Node version for CI and AIO from 16.13.0 -> 16.14.0 to ensure compatibility with dependencies.

PR Close #49790
2023-04-11 13:03:11 -07:00
Andrew Kushnir d1c83ccc02 ci: disable size tracking CI job in favor of integration tests size checks (#49788)
Currently we have multiple integration apps which are instrumented with the payload size checks. In addition to that, there is a separate CI job that performs similar checks. The checks in CI job are redundant, thus this commit disables a separate CI job.

PR Close #49788
2023-04-11 10:48:01 -07:00
Nikola Kološnjaji 108145020f docs: Typo (#49781)
PR Close #49781
2023-04-11 10:27:53 -07:00
Andrew Scott 702ec90110 fix(core): When using setInput, mark view dirty in same way as markForCheck (#49747)
`ComponentRef.setInput` internally calls `markDirtyIfOnPush` which only marks
the given view as dirty but does not mark parents dirty like `ChangeDetectorRef.markForCheck` would.
https://github.com/angular/angular/blob/f071224720f8affb97fd32fb5aeaa13155b13693/packages/core/src/render3/instructions/shared.ts#L1018-L1024

`markDirtyIfOnPush` has an assumption that it’s being called from the parent’s template. That is, we don’t need to mark dirty to the root, because we’ve already traversed down to it.
The function used to only be called during template execution for input
bindings but was added to `setInput` later. It's not a good fit because
it means that if you are responding to events such as an emit from an `Observable`
and call `setInput`, the view of your `ComponentRef` won't necessarily get checked
when change detection runs next. If this lives inside some `OnPush` component tree
that's not already dirty, it only gets refreshed if you also call
`ChangeDetectorRef.markForCheck` in the host component (because it will be "shielded" be a non-dirty parent).

PR Close #49747
2023-04-10 13:29:11 -07:00
Kristiyan Kostadinov ffdfdc238f refactor(migrations): log a link to the standalone migration (#49752)
Resolves an old TODO about adding a link to the standalone migration guide.

PR Close #49752
2023-04-10 09:04:03 -07:00
Matthieu Riegler e7dd72c8de docs: update docs about prodMode. (#49745)
Following angular#49723, this commit updates the doc to reflect the actual message prompted in the console.

PR Close #49745
2023-04-10 09:02:30 -07:00
Matthieu Riegler 9c07a42fbe docs: Improve previous version navigation (#49063)
In archive mode the link to the current doc will now point to same page.
If the page doesn't exist anymore, it will show a contextualized warning message.

See #46850

PR Close #49063
2023-04-06 11:07:01 -07:00
Dylan Hunn 9a37a7786a release: cut the v15.2.6 release 2023-04-05 19:44:18 -07:00
Matthieu Riegler da5f316ebf refactor(core): Use the nullish coalescing assignment in render3 functions (#49698)
The usage of `??=` make the code more clear & concise.

PR Close #49698
2023-04-05 09:45:55 -07:00
Andrew Scott cad7274ef9 fix(router): create correct URL relative to path with empty child (#49691)
The previous fix for squashing empty children didn't quite work when the
existing route had segments. The result would be that the segments from
the existing route were dropped from the final URL.

PR Close #49691
2023-04-04 15:05:42 -07:00
Guillaume Weghsteen d9efa1b0d7 feat(core): change the URL sanitization to only block javascript: URLs (#49659)
In modern browsers, the 'javascript:' URL scheme is the only scheme that
can execute JavaScript when passed in a navigation URL context (e.g.
`a.href` value). Validate URL shemes to only contain characters allowed
in the URL specification ([a-zA-Z-+.]), and that are not javascript
(case insensitive). This is not a breaking change. The URL sanitization
is loosen.

PR Close #49659
2023-04-04 15:01:14 -07:00
Robin Richtsfeld c26e4bea9d docs: fix typo (#49704)
PR Close #49704
2023-04-04 15:00:39 -07:00
Sandra Limacher bd82fbeec4 docs: fix typo (#49669)
PR Close #49669
2023-04-03 19:18:41 -07:00
Matthieu Riegler 1d32253ca6 refactor(core): remove unnecessary reflect-metadata import. (#49673)
The import is not needed for the tests to run.

PR Close #49673
2023-04-03 19:17:03 -07:00
vikram menon 6e1b3adadb docs: fix typo in quick reference (#49655)
Change indicatedr5t to indicated

PR Close #49655
2023-04-03 19:13:16 -07:00
Johnny Gérard a6def648f5 docs: fix typo (#49664)
PR Close #49664
2023-04-02 22:10:13 -07:00
Andrew Scott 9b61379096 fix(router): Ensure initial navigation clears current navigation when blocking (#49572)
The navigation transition clears the current navigation in the finalize
operator of the current navigation Observer. This commit both completes
the `bootstrapDone` observable and updates the transition to only take 1
emit from the completed navigation. Either of these changes on their own
would fix the issue. The latter is a preventative measure in case a
mistake like the former is made again.

fixes #49567

PR Close #49572
2023-03-31 17:04:02 -07:00
John Manners 08979e4589 docs: fix typo in toh-pg6.md (#49141)
Line 425. Change burning to burn.
PR Close #49141
2023-03-31 12:00:44 -07:00
Angular Robot 233f33e6f1 build: update scorecard action dependencies (#49609)
See associated pull request for more information.

PR Close #49609
2023-03-31 11:49:47 -07:00
Vinit Neogi 35f491880c docs(core): fix view hierarchy links (#49629)
fixes incorrect links to view-hierarchy (currently view-tree)

Fixes #49623

PR Close #49629
2023-03-30 09:39:39 -07:00
Sarthak Thakkar 43e89bdacf docs: fixed typo error (#49637)
PR Close #49637
2023-03-30 09:38:43 -07:00
Matthieu Riegler 07e78bbbf4 docs: Update Popup.service example to remove ComponentFactoryResolver (#49638)
`ComponentFactoryResolver` has been deprecated and can be replaced by `createComponent()`.

PR Close #49638
2023-03-30 09:38:16 -07:00
Andrew Scott e78a2a4a47 release: cut the v15.2.5 release (#49635) 2023-03-29 12:37:48 -07:00
Alan Agius 077f6b4674 fix(compiler): do not unquote CSS values (#49460)
Currently we are unsafely unquoting CSS values which in some cases causes valid values to become invalid and invalid values to become valid.

Example:
```html
<div style="width:&quot;1px;&quot;"></div>
```

In the above case, `width` has an invalid value of `"1px"`, however the compiler will transform it to `1px` which makes it valid.

On the other hand,  in the below case
```html
<div style="content:&quot;foo&quot;"></div>
```

`content` has a valid value of `"foo"`, but since the compiler unwraps it to `foo` it becomes invalid. For correctness, we should not remove quotes.

```js
const div = document.createElement('div');
div.style.width='"1px"';
div.style.content='foo';

div.style.width; // ''
div.style.content; // ''

div.style.width='1px';
div.style.content='"foo"';

div.style.width; // '1px'
div.style.content; // '"foo"'
```

More information about values can be found https://www.w3.org/TR/CSS21/syndata.html#value-def-identifier

PR Close #49460
2023-03-28 11:35:39 -07:00
Alan Agius d201fc2dec fix(core): set style property value to empty string instead of an invalid value (#49460)
Currently when the value of a styling property that has a unit is empty string a invalid value is generated.

Example:
`[style.width.px] = ""` will generate a value of `"px"`, when instead it should be `""`.

This causes browser to reset the value to an empty string. This is however not the case in Domino with changes in https://github.com/angular/domino/commit/bfc9114d1eb5b7591c43a7c6aef6ad50d24e369f.

This commit fixes the issues and generate correct values.

PR Close #49460
2023-03-28 11:35:39 -07:00
Matthieu Riegler 6d6fc12c88 refactor(core): Remove usage of deprecated Injector.create() (#49606)
This commit removes all usages of the deprecated `Injector.create` method but does not remove the deprecated signature itself.

PR Close #49606
2023-03-28 10:15:36 -07:00
Asaf Malin 8ed4083a98 docs: fixed grammar (#49560)
PR Close #49560
2023-03-28 10:14:45 -07:00
Matthieu Riegler 4c89a2497a refactor(common): add missing override to satisfy the linter (#49599)
Linter was complaining of missing `override` despite being OK on the CI. this commits add them.

PR Close #49599
2023-03-28 10:12:36 -07:00
Paul Gschwendtner 0fecbabfd2 ci: update pullapprove config to reflect current availability (#49592)
Updating PullApprove to reflect current availability. Looks like it cannot be set via UI anymore...
PR Close #49592
2023-03-27 08:43:06 -07:00
Tano Abeleyra ca5acadb78 fix(common): invalid ImageKit transformation (#49201)
q-auto is an invalid/unsupported transformation and should not be used

PR Close #49201
2023-03-27 08:33:22 -07:00
Andrew Scott 978d37f324 fix(router): Ensure Router preloading works with lazy component and static children (#49571)
The preloading strategy did not handle a `loadComponent` on a route with
a static `children`. It only preloaded children if they were also
`loadChildren` or both were not lazy loaded.

fixes #49558

PR Close #49571
2023-03-24 10:41:11 -07:00
Angular Robot 656a38899a build: update actions/checkout digest to 8f4b7f8 (#49577)
See associated pull request for more information.

PR Close #49577
2023-03-24 10:27:35 -07:00
Paul Gschwendtner 29c682ce5b ci: update github.com known host given recent RSA update (#49580)
See: https://github.blog/2023-03-23-we-updated-our-rsa-ssh-host-key/

PR Close #49580
2023-03-24 12:54:11 +00:00
Sid 3f8e4fb724 docs: add missing word (#49565)
I have added a word to make the sentence more meaningful.
PR Close #49565
2023-03-23 11:44:04 -07:00
Kristiyan Kostadinov c3cff35869 fix(compiler): handle trailing comma in object literal (#49535)
Fixes that the compiler wasn't parsing an object literal with a trailing comma correctly.

Fixes #49534.

PR Close #49535
2023-03-23 11:35:45 -07:00
Jan Cabadaj a844435514 fix(router): fix #49457 outlet activating with old info (#49459)
Avoid activating outlet with old info if route was changed before outlet activated

PR Close #49459
2023-03-22 14:41:43 -07:00
Andrew Scott 901353ec7a release: cut the v15.2.4 release 2023-03-22 13:15:53 -07:00
Kristiyan Kostadinov 288156b06b Revert "fix(migrations): preserve trailing commas in code generated by standalone migration (#49533)" (#49547)
This reverts commit bf4d856834.

PR Close #49547
2023-03-22 10:21:27 -07:00
Kristiyan Kostadinov bf4d856834 fix(migrations): preserve trailing commas in code generated by standalone migration (#49533)
This is based on some internal feedback. Adds logic to the standalone migration that attempts to preserve trailing commas when updating existing AST nodes. When creating new ones, it tries to infer whether to generate the trailing comma based on the surrounding code.

PR Close #49533
2023-03-22 16:41:53 +01:00
Peter Götz 3bb76768a6 docs: remove ticks in code sample to generate components (#49525)
These ticks appear in the actual documentation and when copied verbatim while following the tutorial, running this command in the terminal simply does nothing.
PR Close #49525
2023-03-22 16:02:48 +01:00
Andrew Scott be2db59a55 refactor(router): Remove deprecated loadChildren file (#49504)
This file was used while migrations were happening internally. All code is now updated to the callback

PR Close #49504
2023-03-21 14:09:23 -07:00
Andrew Scott 9c57b656a1 refactor(router): Update router export location for deprecated interfaces (#49504)
Moving these exports to a separate file will allow easier local patches internally.

PR Close #49504
2023-03-21 14:09:22 -07:00
Andrew Scott b293c6a77c refactor(core): Remove VE/Render3 aliases from ViewRef code (#49499)
These aliases were used while we needed to maintain compatibility with ViewEngine

PR Close #49499
2023-03-21 14:08:30 -07:00
Alex Rickabaugh 951a3474d6 test: increase size tracking threshold to 5K / 5% (#49520)
This commit increases the threshold of payload size tracking tests from
500 bytes to 5,000 bytes, and from 1% to 5%. This is done to minimize merge
conflicts while still catching real regressions.

PR Close #49520
2023-03-21 20:30:05 +01:00
Paul Gschwendtner b5e68e42c1 build: exclude draft PRs from triage queue (#49515)
Excludes draft PRs from triage queue. Note that we cannot use
`draft:false` as otherwise all issues would be filtered. Rather
we need to negate `draft:true` which matches non-draft PRs and
normal issues.

PR Close #49515
2023-03-21 16:40:48 +01:00
Angular Robot a404587615 build: update scorecard action dependencies (#49508)
See associated pull request for more information.

PR Close #49508
2023-03-21 16:39:10 +01:00
Angular Robot 6c9886b1ca build: update cross-repo angular dependencies (#49517)
See associated pull request for more information.

PR Close #49517
2023-03-21 15:30:37 +01:00
Thomas Pischke 3c75f98117 docs: remove pipe in exponential backoff (#49494)
PR Close #49494
2023-03-21 07:58:06 +01:00
Thomas Pischke cd5d7b6615 docs: update deprecated exponential backoff example (#49494)
PR Close #49494
2023-03-21 07:58:06 +01:00
Aditya Srinivasan 97d58ec091 docs: fix link ngFor documentation link (#49479)
Fix the `ngFor` API link under the "Structural directive shorthand" section
PR Close #49479
2023-03-21 07:56:38 +01:00
Masaoki Kobayashi 087f4412af fix(core): more accurate matching of classes during content projection (#48888)
Showing a minimum app to reproduce the bug.
1. Create the app and add angular material.
```
ng new project
cd project
ng add @angular/material
```
1. Overwrite the src/app/app.component.html with minimal content.
```
<button mat-button *ngIf="true"><span *ngIf="true" class="{{'a'}}"></span></button>
```
1. Run the app. The button is not shown because of an exception.
```
main.ts:6
ERROR TypeError: item.toLowerCase is not a function
    at isCssClassMatching (core.mjs:8726:35)
    at isNodeMatchingSelector (core.mjs:8814:22)
    at isNodeMatchingSelectorList (core.mjs:8931:13)
    at matchingProjectionSlotIndex (core.mjs:14179:13)
    at Module.ɵɵprojectionDef (core.mjs:14222:49)
    at MatButton_Template (button.mjs:113:99)
    at executeTemplate (core.mjs:10534:9)
    at renderView (core.mjs:10356:13)
    at renderComponent (core.mjs:11529:5)
    at renderChildComponents (core.mjs:10216:9)
```
Because isCssClassMatching() function does not take care if the value is not string, while attrs[] may contain AttributeMarker which is actually numbers, item.toLowerCase() throws the exception.
Just inserted a check if the item is string.

Created a testcase for the original fix. It causes an exception without the fix.

fix(core): add a check code to avoid an exception inside isCssClassMatching

Showing a minimum app to reproduce the bug.
1. Create the app and add angular material.
```
ng new project
cd project
ng add @angular/material
```
1. Add `import { MatButtonModule } from '@angular/material/button'`,
   and also MatButtonModule inside @NgModule imports in src/app/app.module.ts to use MatButtonModule.
1. Overwrite the src/app/app.component.html with minimal content.
```
<button mat-button *ngIf="true"><span *ngIf="true" class="{{'a'}}"></span></button>
```
1. Run the app. The button is not shown because of an exception.
```
main.ts:6
ERROR TypeError: item.toLowerCase is not a function
    at isCssClassMatching (core.mjs:8726:35)
    at isNodeMatchingSelector (core.mjs:8814:22)
    at isNodeMatchingSelectorList (core.mjs:8931:13)
    at matchingProjectionSlotIndex (core.mjs:14179:13)
    at Module.ɵɵprojectionDef (core.mjs:14222:49)
    at MatButton_Template (button.mjs:113:99)
    at executeTemplate (core.mjs:10534:9)
    at renderView (core.mjs:10356:13)
    at renderComponent (core.mjs:11529:5)
    at renderChildComponents (core.mjs:10216:9)
```
Because isCssClassMatching() function does not take care if the value is not string, while attrs[] may contain AttributeMarker which is actually numbers, item.toLowerCase() throws the exception.
Just inserted a check if the item is string.

PR Close #48888
2023-03-20 16:07:14 +01:00
avmaxim 0f0c0a9452 docs(docs-infra): improve docs for @angular/localize package. (#49393)
This PR adds missing documentation for `@angular/localize` package and fixes a tiny one-word typo in the `README.md` file for `@angular/localize schematic`.

Fixes #49219.

PR Close #49393
2023-03-20 13:12:19 +01:00
Matthieu Riegler bae6b5ceb1 fix(core): Allow TestBed.configureTestingModule to work with recursive cycle of standalone components. (#49473)
When having a recursive circle of imports on standalone components, `queueTypesFromModulesArrayRecur` triggered a `Maximum call stack size exceeded` error.
This commit fixes this.

Fixes #49469

PR Close #49473
2023-03-20 10:02:15 +01:00
Virginia Dooley 868dcabdee docs: Send data to server - insert updated links. (#49447)
PR Close #49447
2023-03-20 08:49:21 +01:00
Matthieu Riegler 8f6cbb66a2 docs: remove bazel builder section (#49423)
PR Close #49423
2023-03-20 08:48:43 +01:00
Angular Robot c807a324d1 build: update actions/checkout digest to 24cb908 (#49436)
See associated pull request for more information.

PR Close #49436
2023-03-17 08:38:16 +01:00
Virginia Dooley 2e37e2365b docs: Optimize server interaction - insert updated link. (#49438)
PR Close #49438
2023-03-17 08:36:59 +01:00
Virginia Dooley bb2753decb docs: Track and show request progress - insert updated link. (#49439)
PR Close #49439
2023-03-17 08:35:45 +01:00
Virginia Dooley e6736c77a0 docs: Intercept requests - insert updated link. (#49446)
PR Close #49446
2023-03-17 08:34:15 +01:00
Alex Rickabaugh 3d71d9ddd9 release: cut the v15.2.3 release 2023-03-16 12:08:14 -07:00
Angular Robot c9816448ed build: update actions/cache digest to 940f3d7 (#49377)
See associated pull request for more information.

PR Close #49377
2023-03-15 17:27:22 -07:00
Alan Agius 589e76b7ef test(common): update async pipe tests to fix test errors (#49433)
The below error is displayed during some tests

```js
ERROR: 'Unhandled Promise rejection:', 'Cannot read properties of null (reading 'markForCheck')', '; Zone:', 'ProxyZone', '; Task:', 'Promise.then', '; Value:', TypeError: Cannot read properties of null (reading 'markForCheck')
TypeError: Cannot read properties of null (reading 'markForCheck')
    at AsyncPipe2._updateLatestValue (http://angular-ci.local:9876/base/dist/legacy-test-bundle.spec.js?49174f830d8743d5c8a9551b77550b859b934291:51947:19)
```

This is caused by the fact that `ref` in `AsyncPipe` is initialized with a value of `null` which causes `_updateLatestValue` to fail since it is not expected to be `null`.

This change ensures that a `ref` is always provided and that all subscriptions are disposed off after each test.

PR Close #49433
2023-03-15 17:19:38 -07:00
Virginia Dooley bba3fcb30b docs: Understanding communicating with http - insert updated links. (#49429)
PR Close #49429
2023-03-15 17:18:54 -07:00
Angular Robot 6f139b4f0b build: update io_bazel_rules_sass digest to 3d2ad47 (#49428)
See associated pull request for more information.

PR Close #49428
2023-03-15 17:11:56 -07:00
Angular Robot dfa7f648d6 build: update github/codeql-action action to v2.2.6 (#49420)
See associated pull request for more information.

PR Close #49420
2023-03-15 17:01:01 -07:00
Alan Agius 5a3d121204 test: fix misconfiguration in tests (#49391)
Currently, tests are tested twice using "production" like configuration. This commit disabled "optimization" for non production builds.

PR Close #49391
2023-03-15 16:59:51 -07:00
Esteban Gehring e4516c75d2 docs(upgrade): mark lifecycle methods as nodoc (#49416)
PR Close #49416
2023-03-14 09:41:36 -07:00
Esteban Gehring 32e98f7937 docs(common): mark lifecycle methods as nodoc (#49416)
PR Close #49416
2023-03-14 09:41:36 -07:00
Angular Robot 6c189ed0f1 build: update io_bazel_rules_sass digest to aa03944 (#49397)
See associated pull request for more information.

PR Close #49397
2023-03-14 09:25:16 -07:00
Angular Robot 2df92f7633 build: update cross-repo angular dependencies (#49410)
See associated pull request for more information.

PR Close #49410
2023-03-13 13:50:33 +00:00
Virginia Dooley 1535ab90da docs: New doc: Understanding communicating with backend services using HTTP (#49294)
PR Close #49294
2023-03-09 09:21:14 -08:00
Virginia Dooley c2726650f6 docs: New doc extract from original HTTP doc to be retired. (#48914)
PR Close #48914
2023-03-09 09:19:04 -08:00
Virginia Dooley a44224ce59 docs: delete outdated link. (#48909)
PR Close #48909
2023-03-09 09:17:02 -08:00
Virginia Dooley 3c71e4846a docs: delete or revise outdated links. (#48909)
PR Close #48909
2023-03-09 09:17:02 -08:00
Virginia Dooley 43dff1fc27 docs: New doc extract from original HTTP doc to be retired. (#48909)
PR Close #48909
2023-03-09 09:17:01 -08:00
Matthieu Riegler 7e23883b5d refactor(dev-infra): remove obsolete todos (#49362)
These todos do not apply anymore, let's remove them.

PR Close #49362
2023-03-08 15:39:56 -08:00
Matthieu Riegler 7efaf525a5 docs: Remove RenderComponentType from the depreciation list. (#49363)
`RenderComponentType` was removed by #33019

PR Close #49363
2023-03-08 15:39:03 -08:00
Angular Robot f099df839e docs: update events (#49366)
Generated `events.json` with the latest events retrieved from the Firebase DB.

Closes #49355

PR Close #49366
2023-03-08 21:54:24 +00:00
Angular Robot c9e8804b5c build: update eslint dependencies to v5.54.1 (#49348)
See associated pull request for more information.

PR Close #49348
2023-03-08 13:08:34 -08:00
Alan Agius 2dee505582 refactor(core): split ɵɵdefineDirective and ɵɵdefineComponent (#49350)
Before this change `ɵɵdefineDirective` called `ɵɵdefineComponent` under the hood. This is problematic for the consistent component id generation as it could result in hash collisions for certain directives. Directives however do not require an id.

This changes moves common definition generation logic into a separate function that is re-used in `ɵɵdefineDirective` and `ɵɵdefineComponent`.

PR Close #49350
2023-03-08 13:07:54 -08:00
Jessica Janiuk 75d5bfda1e release: cut the v15.2.2 release 2023-03-08 10:43:09 -08:00
Paul Gschwendtner 993750815e refactor(compiler-cli): remove unused class decorator downlevel code (#49351)
The decorator downlevel transform is never used for actual class
decorators because Angular class decorators rely on immediate execution
for JIT. Initially we also supported downleveling of class decorators
for View Engine library output, but libraries are shipped using partial
compilation output and are not using this transform anymore.

The transform is exclusively used for JIT processing, commonly for
test files to help ease temporal dead-zone/forward-ref issues. We can
remove the class decorator downlevel logic to remove technical debt.

PR Close #49351
2023-03-08 17:59:12 +00:00
Matthieu Riegler 88a0ff74ad docs(docs-infra): Split Error by categories & sort by code. (#49343)
* 2 categories : Runtime errors and Compiler Errors.
* Numeric sort on error code.

PR Close #49343
2023-03-07 19:18:01 +00:00
Sai Kartheek Bommisetty 75b2a265a9 docs: update toh-pt5.md (#49307)
PR Close #49307
2023-03-07 19:17:25 +00:00
Vinit Neogi d0a73b24fe docs(docs-infra): missing "is" in glossary (#49356)
documentation glossary for view hierarchy is missing a "is" to be grammatically correct

Fixes #49352

PR Close #49356
2023-03-07 19:16:42 +00:00
Matthieu Riegler e0be553abf docs(forms): change error code in filename to match enum value. (#49344)
Error code for bad AsyncValidatorFn is 1101 not 1003.

PR Close #49344
2023-03-07 17:38:02 +00:00
Matthieu Riegler ffccb8e3a7 refactor(animations): handle #24571 todos (#49231)
This commit removes the remaining ones in animations code base

PR Close #49231
2023-03-06 18:45:34 +00:00
Matthieu Riegler b13e079bc7 refactor(core): Remove ChangeDetectorStatus & isDefaultChangeDetectionStrategy (#49299)
Unused code in core and other packages. They were private exports.

PR Close #49299
2023-03-06 16:57:02 +00:00
Matthieu Riegler 84f45363eb refactor(platform-browser): remove ununsed functions. (#49302)
Both `camelCaseToDashCase` and `dashCaseToCamelCase` haven't been used since 2.2.0.

PR Close #49302
2023-03-06 16:56:32 +00:00
Andrew Kushnir 980147555c refactor(core): rename TNode.tViews to TNode.tView (#49313)
Previously (at the early days of Ivy) a TNode used to keep an array of TViews, but the logic was changed since that time, but the `tViews` field remained on TNode interface (+ corresponding typings).

This commit renames TNode.tViews to TNode.tView and cleans up typings.

PR Close #49313
2023-03-06 16:56:00 +00:00
Matthieu Riegler 182258520d refactor(platform-browser): handle #24571 todos (#49232)
This commit removes the remaining TODO(issue/24571) in platform-browser code base.

PR Close #49232
2023-03-06 16:54:38 +00:00
Andrew Scott ac59054cd4 refactor(migrations): Move ChangeTracker to common utils (#49308)
The `ChangeTracker` is generally useful and could be used by a lot of
migrations instead of having to rewrite similar boilerplate.

PR Close #49308
2023-03-03 22:03:37 +00:00
Paul Gschwendtner b90b3299aa test: fix router testing example breaking due to non-existent stub (#49293)
We recently migrated the testing example to use the router testing
harness. There was one instance of the previous non-`TestBed` examples
left that still relies on a stub that has already been removed.

This example is not used anywhere and we should rather encourage
a single pattern of testing. i.e. the harness as per recent changes.

This commit removes the broken file.

PR Close #49293
2023-03-03 19:41:36 +00:00
Paul Gschwendtner 4ae753d84f build: always preserve symlinks when executing e2e test commands (#49293)
Currently, examples with test commands like `ng build` are *never*
using the local version of `//packages/compiler-cli`. This is because
the CLI is invoked accidentally from within `external/aio_example_deps`.

Since the CLI relies on importing the compiler-cli, it will always
resolve the dependency from that directory- causing it to be always
the version installed via `aio/examples/tools/shared/package.json`.

We should never resolve symlinks and escape the e2e sandbox. That way
the compiler-cli would be resolved properly and could also become the
locally built one, depending on the test mode (i.e. npm or "local").

PR Close #49293
2023-03-03 19:41:36 +00:00
Paul Gschwendtner f859de3e60 build: ensure chromium is not using sandbox within Bazel sandbox for AIO example e2e tests (#49293)
Chromium is launched via Karma from within the Bazel AIO example e2e
tests. This breaks depending on the platform and sandbox mechanism used.

We should never use Chromium's sandbox on top of Bazel's sandbox
invocation. The Angular CLI exposes a browser exactly for this use-case.

PR Close #49293
2023-03-03 19:41:36 +00:00
Paul Gschwendtner 5bb4407c01 build: fix AIO local e2e examples picking up incorrect dependencies (#49293)
Whenever we run example tests using the local framework packages, the
e2e tests will have the local framework packages symlinked in the
`node_modules`.

This works well in general, but due to NodeJS by default resolving
symlinks to the target location, NodeJS will end up looking for
transitive dependencies in the `bazel-bin` instead of in the example
`node_modules` folder. This means that we end up incorrectly resolving
older versions of `@angular/core` that end up existing in the main
project dependencies. This causes errors like:

```
Error: ../../home/circleci/.cache/bazel/_bazel_circleci/9ce5c2144ecf75d11717c0aa41e45a8d/execroot/angular/bazel-out/k8-fastbuild/bin/packages/common/npm_package/http/testing/index.d.ts:12:21 - error TS2307: Cannot find module '@angular/common/http' or its corresponding type declarations.

12 import * as i1 from '@angular/common/http';
                       ~~~~~~~~~~~~~~~~~~~~~~

Error: ../../home/circleci/.cache/bazel/_bazel_circleci/9ce5c2144ecf75d11717c0aa41e45a8d/execroot/angular/bazel-out/k8-fastbuild/bin/packages/common/npm_package/index.d.ts:1630:18 - error TS2707: Generic type 'ɵɵDirectiveDeclaration' requires between 6 and 8 type arguments.

1630     static ɵdir: i0.ɵɵDirectiveDeclaration<NgClass, "[ngClass]", never, { "klass": "class"; "ngClass": "ngClass"; }, {}, never, never, true, never>;
                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
```

We can fix this by properly ensuring that NodeJS does not resolve
symlinks, but rather preserves them.

In the error above, the e2e tests end up accidentally resolving
`@angular/core` v14 that comes from `@angular/benchpress`. Angular
Benchpress is installed via `@angular/build-tooling` in the project
root.

PR Close #49293
2023-03-03 19:41:36 +00:00
Paul Gschwendtner 5e85c138fa test: fix node and dom types conflict in practical-observable-usage example (#49293)
This causes the e2e tests to fail. The tests were compiled using a
tsconfig with `lib=dom`, but the tests explicitly tried to pull in the
Node types. This causes a conflict for e.g. `AbortController` types.

PR Close #49293
2023-03-03 19:41:36 +00:00
Paul Gschwendtner b23fa5e977 build(docs-infra): fix example e2e tests not failing properly in some situations (#49293)
The `run-example-e2e` script does not properly fail if configured
tests of examples are failing. This happens when a CLI example
configures multiple tests in the `example-config`. Due to incorrect
usage of promises in combination with reduce, only the last test
command had an effect on the overall test conclusion.

A similar issue seems to occur with SystemJS Protractor tests.

This commit fixes the problem and also cleans up the code a little
by switching it to `async/await`.

PR Close #49293
2023-03-03 19:41:36 +00:00
Paul Gschwendtner 05db4797e8 build: format run-example-e2e.mjs with prettier (#49293)
Formats the `run-example-e2e.mjs` file with prettier to ease
future diffs.

PR Close #49293
2023-03-03 19:41:36 +00:00
Matthieu Riegler 6b9ec0b830 refactor(core): Remove ɵivyEnabled (#49296)
The unit tests have been updated in #44120, this export is unused now.

PR Close #49296
2023-03-03 19:41:10 +00:00
Matthieu Riegler b0a9e67419 docs: fix links on untyped forms (#49306)
PR Close #49306
2023-03-03 19:40:00 +00:00
Matthieu Riegler f321e65c46 refactor(common): remove BrowserPlatformLocation from private exports. (#49301)
`BrowserPlatformLocation` was add to the public API by #48488.

PR Close #49301
2023-03-03 16:39:54 +00:00
Angular Robot 13e675ea87 build: update all non-major dependencies (#49267)
See associated pull request for more information.

PR Close #49267
2023-03-02 14:09:15 -08:00
Kristiyan Kostadinov de48c99afb refactor(migrations): expose current file in import remapper (#49288)
Passes the path of the current file to the import remapper. Useful if we want to generate absolute paths.

PR Close #49288
2023-03-02 21:48:35 +00:00
Andrew Scott 81e32f4283 docs(router): Update component testing to user RouterTestingHarness (#48553)
This commit updates the documentation on testing the
`Router` to use the `RouterTestingHarness` rather than stubs.

The stubs described in the previous form of this document actually
creates tests which are incapable of catching bugs related to the
component's interaction with the `Router`. In addition, managing the
stubs is more difficult than using the real `Router` classes.

Stubbing something like the `RouterLink` is quite harmful because it
neither tests the actual URL being created, nor the end result of the
navigation. There have been serveral bug fixes in the Router over the
years the would change the outcome of these but would not be caught by
tests which create a stub.

PR Close #48553
2023-03-02 13:17:17 -08:00
Paul Gschwendtner e20b6d98d9 build: remove ts-node forking bug workaround (#49289)
In the past, `ts-node` had a bug that prevented forking processes
when used in combination with `--esm`.

We contributed a fix upstream to `ts-node` to fix this, and this
commit updates to the latest version so that we can simplify our
`ng-dev` invocation.

https://github.com/TypeStrong/ts-node/commit/32d07e2b2fcbaab97c11e71ee5fc3a79fc20c802

Fixes #46858

PR Close #49289
2023-03-02 13:16:20 -08:00
Matthieu Riegler d42032a380 refactor(core): Remove isListLikeIterable from private export. (#49297)
PR #48433 removed the last external usage of `isListLikeIterable`. We can now remove it from the private exports.

PR Close #49297
2023-03-02 20:53:01 +00:00
Matthieu Riegler ffc684381f docs: Add NG8107 entry : Optional chain not nullable extended diagnostic (#49287)
PR Close #49287
2023-03-02 19:56:37 +00:00
Matthieu Riegler 8f7fbddb51 refactor: remove duplicate key from component metadata (#49065)
`directiveMetadata()` already assigns the `standalone` property to the `R3ComponentMetadataFacade` there is no need to do it twice.

PR Close #49065
2023-03-01 22:36:50 +00:00
Alan Agius bca3aed9e4 build: remove core-js-bundle from dependencies (#49259)
This is no longer needed as Angular is ever green.

PR Close #49259
2023-03-01 11:19:49 -08:00
Andrew Kushnir 819b9f32b4 refactor(core): move APP_BOOTSTRAP_LISTENER to avoid circular deps (#49273)
This commit moves the `APP_BOOTSTRAP_LISTENER` token into the `application_ref.ts` to avoid a risk of circular dependencies. The main problem is that the token refers to the `ComponentRef`, which in turn refers to more symbols, thus making the `application_tokens.ts` file susceptible to circular dependencies. Such a dependency was identified in https://github.com/angular/angular/pull/49271.

PR Close #49273
2023-03-01 11:18:28 -08:00
Kristiyan Kostadinov 6207d6f1f0 fix(migrations): add protractor support if protractor imports are detected (#49274)
The new `bootstrapApplication` API doesn't include Protractor support anymore which may cause existing e2e tests to break after the migration. These changes add some logic that will provide Protractor support if any imports to `protractor` or `protractor/*` are detected.

PR Close #49274
2023-03-01 11:13:57 -08:00
Andrew Kushnir 174997150f release: cut the v15.2.1 release 2023-03-01 10:53:10 -08:00
Stephanie Tuerk 439b4d3a89 docs: clarify ActivatedRouter injection location (#49270)
The example in the code snippet below this line of text shows `ActivatedRouter` being injected into a component's constructor. When I read instruction to inject A`ActivatedRouter` into **application's** constructor, I assumed this meant the constructor for `app.component.ts`. 

Editing to clarify/match code example below.
PR Close #49270
2023-02-28 17:13:37 -08:00
Joey Perrott 377d0c9c1e build: update cross-repo angular dependencies (#49268)
See associated pull request for more information.

PR Close #49268
2023-02-28 12:43:42 -08:00
Alan Agius d60ea6ab5a fix(core): update zone.js peerDependencies ranges (#49244)
This ensures that the latest version of zone.js is supported.

PR Close #49244
2023-02-28 11:55:54 -08:00
Matthieu Riegler dafb765926 refactor(core): Drop Symbol.iterator shim (#49207)
We are targeting evergreen browsers, we can drop the shim.

PR Close #49207
2023-02-28 10:05:42 -08:00
Kristiyan Kostadinov 44d095a61c fix(migrations): avoid migrating the same class multiple times in standalone migration (#49245)
If a class is declared in multiple modules, the standalone migration may end up generating invalid code. While declaring a class in multiple modules is an error, it can happen with modules in tests. These changes avoid the issue by using a `Set` to track the classes being migrated.

PR Close #49245
2023-02-28 10:04:55 -08:00
Virginia Dooley 600fd12fda docs: New doc extract from original HTTP doc to be retired. (#48915)
PR Close #48915
2023-02-28 09:32:30 -08:00
Virginia Dooley d100ddfd6e docs: New doc extract from original HTTP doc to be retired. (#48912)
PR Close #48912
2023-02-28 09:31:31 -08:00
Virginia Dooley 1aadabb508 docs: New doc extract from original HTTP doc to be retired. (#48908)
PR Close #48908
2023-02-28 09:30:14 -08:00
Virginia Dooley d252187c45 docs: New document extracted from the original Communicating with backend services using HTTP document, which is to be retired. (#47971)
PR Close #47971
2023-02-28 09:29:13 -08:00
Matthieu Riegler 6d6b76c59f docs(router): Improving linking (#49203)
Add links to @see elements and suggest a more explicit alternative for the depreciation of `CanActivate`.

PR Close #49203
2023-02-28 08:24:11 -08:00
Matthieu Riegler 5f2822ce1f refactor(platform-server): handle #24571 todos (#49233)
This commit removes the remaining TODO(issue/24571) in platform-server code base.

PR Close #49233
2023-02-28 08:19:58 -08:00
Matthieu Riegler acc87a41ce docs: remove TODO from doc example (#49233)
This commit removes a TODO(issue/24571) that leaking into the docs examples

PR Close #49233
2023-02-28 08:19:57 -08:00
Matthieu Riegler 7eec66c449 refactor(elements): handle #24571 todos (#49233)
This commit removes the remaining TODO(issue/24571) in elements code base.

PR Close #49233
2023-02-28 08:19:57 -08:00
Angular Robot 8fc02f56d0 build: update eslint dependencies to v5.54.0 (#49243)
See associated pull request for more information.

PR Close #49243
2023-02-28 08:19:07 -08:00
Angular Robot 313760b851 build: update github/codeql-action action to v2.2.5 (#49242)
See associated pull request for more information.

PR Close #49242
2023-02-28 08:18:22 -08:00
Matthieu Riegler 87252dcbbc docs: improve section title in TOH-pt4 (#49208)
fixes #49165

PR Close #49208
2023-02-28 08:16:39 -08:00
Alan Agius 785ab81a7b ci: add several dependencies to renovate ignore list (#49258)
Add ignored dependencies in Renovate config. These have been collected from the dependency dashboard (https://github.com/angular/angular/issues/46728)

The reason for this change is that Renovate is re-opened dependency updates for ignored PRs.

Example:
https://github.com/angular/angular/pull/49256
https://github.com/angular/angular/pull/47852

PR Close #49258
2023-02-28 08:15:05 -08:00
Virginia Dooley 19a4cdec7d docs: New document extracted from the original Communicating with backend services using HTTP document, which is to be retired. (#47937)
PR Close #47937
2023-02-27 15:24:41 -08:00
Iván Navarro 3062442728 fix(router): add error message when using loadComponent with a NgModule (#49164)
Add a more specific error message when defining a lazy-loaded route using
`loadComponent` and passing it a NgModule instead of a standalone component,
when the user should actually be using `loadChildren`.

PR Close #49164
2023-02-27 10:09:55 -08:00
Doug Parker 138b4936b7 release: bump DevTools version (#49121)
PR Close #49121
2023-02-27 10:07:54 -08:00
Matthieu Riegler af31adb8dd refactor(common): Use isPromise from @angular/core (#49210)
This commit removes `isPromise()` from Common as it's a duplicate function that can be imported from `@angular/core`.

PR Close #49210
2023-02-27 10:03:21 -08:00
Vincent f0e926074d fix(common): make Location.normalize() return the correct path when the base path contains characters that interfere with regex syntax. (#49181)
Fix the function stripping the base path from the URL, as the current implementation uses the base path as part of a regex, which wrongly makes paths fails that contain characters such as a parenthesis (example: C:/Users/MyUser(Test)/project).

Fixes #49179

PR Close #49181
2023-02-27 10:02:33 -08:00
Andrew Kushnir 7ec76dea5f refactor(core): add previous sibling node reference to TNode (#49223)
This commit updates the `TNode` to include a reference to the previous sibling node. Currently, TNode has references to the next sibling and parent nodes, but in followup changes we'd need to have access to previous TNodes (to determine position of the current node).

PR Close #49223
2023-02-27 10:00:26 -08:00
Paul Gschwendtner a852862ff9 build: cleanup unused dependencies (#49227)
Cleans up a few more unused dependencies.

Related: https://github.com/angular/angular/pull/49226

PR Close #49227
2023-02-27 08:06:00 -08:00
Aristeidis Bampakos 6107d2ebbc docs: change link for Angular Projects book (#49198)
PR Close #49198
2023-02-27 08:05:21 -08:00
Aristeidis Bampakos 56f7d1f61a docs: add new edition of Learning Angular book (#49199)
PR Close #49199
2023-02-27 08:04:35 -08:00
Matthieu Riegler 6d912960b9 docs: bump first-app to 15.2 (#49217)
The stackblitz demo of the quick-start guide was broken with incompatible dependencies.
This commit fixes this.

Fixes #49213

PR Close #49217
2023-02-27 08:03:47 -08:00
Andrew Kushnir 8542593c80 refactor(platform-browser): move TransferState init logic into its constructor (#49191)
This commit updates the TransferState class to move its init logic from the `useFactory` function to its constructor. The change is needed to make the init behavior consistent across different injection scenarios and tolerate the issue described in https://github.com/angular/angular/issues/49190.

PR Close #49191
2023-02-24 10:41:17 -08:00
Andrew Kushnir d0fa598fe4 refactor(core): avoid creating DOM nodes before creating a TNode (#49172)
This commit updates the `elementStart` instruction to avoid creating DOM nodes before creating a corresponding TNode. This refactoring is needed to make sure this internal logic is consistent across all instructions.

PR Close #49172
2023-02-24 08:29:06 -08:00
Paul Gschwendtner 04d8b6c61a fix(compiler-cli): do not persist component analysis if template/styles are missing (#49184)
Consider the following scenario:

1. A TS file with a component and templateUrl exists
2. The template file does not exist.
3. First build: ngtsc will properly report the error, via a FatalDiagnosticError
4. The template file is now created
5. Second build: ngtsc still reports the same errror.

ngtsc persists the analysis data of the component and never invalidates
it when the template/style file becomes available later.

This breaks incremental builds and potentially common workflows
where resource files are added later after the TS file is created. This
did surface as an issue in the Angular CLI yet because Webpack requires
users to re-start the process when a new file is added. With ESBuild
this will change and this also breaks incremental builds with
Bazel/Blaze workers.

To fix this, we have a few options:

* Invalidate the analysis when e.g. the template file is missing. Never
  caching it means that it will be re-analyzed on every build iteration.
* Add the resource dependency to ngtsc's incremental file graph. ngtsc
  will then know via `host.getModifiedResources` when the file becomes
  available- and fresh analysis of component would occur.

The first approach is straightforward to implement and was chosen here.
The second approach would allow ngtsc to re-use more of the analysis
when we know that e.g. the template file still not there, but it
increases complexity unnecessarily because there is no **single**
obvious resource path for e.g. a `templateUrl`. The URL is attempted
to be resolved using multiple strategies, such as TS program root dirs,
or there is support for a custom resolution through
`host.resourceNameToFileName`.

It would be possible to determine some candidate paths and add them to
the dependency tracker, but it seems incomplete given possible external
resolvers like `resourceNameToFileName` and also would likely not have
a sufficient-enough impact given that a broken component decorator is
not expected to remain for too long between N incremental build
iterations.

PR Close #49184
2023-02-24 08:24:08 -08:00
Kristiyan Kostadinov 92b0bda9e4 fix(migrations): delete barrel exports in standalone migration (#49176)
Adds some logic to automatically delete `export * from './foo'` style imports. Previously they weren't being picked up, because finding all the references using the language service doesn't include barrel exports.

PR Close #49176
2023-02-24 08:23:02 -08:00
Michael Ziluck d7835e4f1a docs(router): fix code block closing ticks (#49185)
PR Close #49185
2023-02-23 10:37:25 -08:00
Craig Spence e384c69b83 docs(core): Improved README.md (#49171)
PR Close #49171
2023-02-23 10:35:42 -08:00
Angular Robot aa10532458 build: update io_bazel_rules_sass digest to 1f27790 (#49132)
See associated pull request for more information.

PR Close #49132
2023-02-23 10:34:43 -08:00
Alex Rickabaugh 7677963bd9 release: cut the v15.2.0 release 2023-02-22 13:04:10 -08:00
cexbrayat 03fcb36cfd fix(migrations): migrate HttpClientModule to provideHttpClient() (#48949)
The `standalone-bootstrap` migration now migrates `HttpClientModule` imports to `provideHttpClient(withInterceptorsFromDi())` instead of `importProvidersFrom(HttpClientModule)`.

The `withInterceptorsFromDi()` feature is added to make sure class-based interceptors still works if there are any in the application.

Fixes #48948

PR Close #48949
2023-02-22 11:30:01 -08:00
Matthieu Riegler 2f0856070b docs: escape script tag to prevent rendering problems (#49152)
un-commented tags are responsible for rendering problem of markdown document. This commit fixes the http make jsonp request guide.

fixes #49151

PR Close #49152
2023-02-22 11:29:33 -08:00
Angular Robot 7b4d3c036d build: update actions/cache digest to 69d9d44 (#49148)
See associated pull request for more information.

PR Close #49148
2023-02-21 13:36:41 -08:00
Kristiyan Kostadinov c98c6a8452 fix(migrations): don't copy animations modules into the imports of test components (#49147)
Since we have less information about how to copy test components, we copy all the `imports` from the `configureTestingModule` call into the component's `imports`. It fixes some tests, but it can cause issues with animations modules, because they throw errors if they're imported multiple times.

These changes add an exception for animations modules imported in testing modules.

PR Close #49147
2023-02-21 13:35:43 -08:00
Angular Robot 630193543f build: update eslint dependencies to v5.53.0 (#49146)
See associated pull request for more information.

PR Close #49146
2023-02-21 13:24:16 -08:00
Walid Bouguima cff84d00cf docs(router): canMatch route guard method signature update (#49140)
Very cosmetic, but it might be necessary : 

I updated the ```canAccess``` method second signature name and type in the provided sample. As it stands, it triggers `TS(2345):  Argument of type 'Route' is not assignable to parameter of type 'string'`.
PR Close #49140
2023-02-21 13:23:08 -08:00
Kristiyan Kostadinov ba7a757cc5 fix(migrations): return correct alias when conflicting import exists (#49139)
Fixes that the `ImportManager` was returning the `propertyName` instead of the `name` when there's an import with a conflicting identifier.

PR Close #49139
2023-02-21 13:17:21 -08:00
Kristiyan Kostadinov ecb309152f build: update AIO to TypeScript 4.9 (#49135)
Updates AIO to the latest stable version of TypeScript as a prerequisite to drop support for 4.8.

PR Close #49135
2023-02-21 13:16:36 -08:00
Kalbarczyk 2fd81940d3 docs: add NG Poland 2023 and JS Poland 2023 to events (#48972)
docs: add NG Poland 2023 and JS Poland 2023 to events
PR Close #48972
2023-02-21 13:16:06 -08:00
Paul Gschwendtner 0950ef6a49 ci: attempt to fix node windows job flakiness (#49142)
Ocasionally Node is randomly not installed in the Windows job. We've
been trying to debug this for a while. With the additonal debug
information it looks like in some situations the NodeJS folder from
NVM is not even present.

One idea is to use `nvm on` to ensure NVM is actually enabled. It's
unclear why it would be `off` at VM start, but it's worth giving a try.

Trying `nvm off` via SSH yields similar issues as we saw in the flaky
workflows:
https://app.circleci.com/pipelines/github/angular/angular/56160/workflows/2f1b80b3-29c7-4274-804e-cb994c20aff0/jobs/1287228

PR Close #49142
2023-02-20 15:16:54 +00:00
Paul Gschwendtner e69ba26c55 ci: fix rbe initialization failing in windows job (#49142)
The RBE init script from dev-infra is using ES2020 but
the image NodeJS version does not support e.g. nullish coalescing.

PR Close #49142
2023-02-20 15:16:54 +00:00
Joey Perrott 61878883ed build: update to latest remote build execution setup (#49133)
Update to the latest RBE setup after key rotation.

PR Close #49133
2023-02-18 02:42:28 +00:00
Andrew Kushnir 8ed653b93f ci: update AIO payload size tracking (#49130)
This commit updates a golden file to decrease an expected payload size.

PR Close #49130
2023-02-17 11:55:02 -08:00
cexbrayat b76b176733 refactor(http): simplify HttpClientModule XSRF configuration (#48957)
The current configuration of `HttpClientModule` explicitely enables the XSRF configuration,
but this XSRF configuration is the one used by default by `provideHttpClient`.

See https://github.com/angular/angular/blob/main/packages/common/http/src/provider.ts#L50-L98

PR Close #48957
2023-02-17 11:17:55 -08:00
Angular Robot f8a932afbb build: update io_bazel_rules_sass digest to a2efcd6 (#49122)
See associated pull request for more information.

PR Close #49122
2023-02-17 11:11:01 -08:00
Alan Agius d784986cd3 Revert "fix(platform-server): insert transfer state script before other script tags (#48868)" (#49112)
This reverts commit 2fc5b70fce as this change is no longer needed since `type=module` script are deferred by default. Which causes the transfer data to be queried after the browser has finished parsing the DOM.

PR Close #49112
2023-02-17 11:09:22 -08:00
Matthieu Riegler 31a71a0f89 refactor: remove unnecessary file (#49042)
view had a single export from a file located in the same package, no need to keep it.

PR Close #49042
2023-02-17 11:08:34 -08:00
Alan Agius 3d8efece03 test: remove cli-hello-world-ivy-compat integration test (#49111)
This now is the same as `cli-hello-world` since this test does not use View Engine

PR Close #49111
2023-02-17 11:07:28 -08:00
Virginia Dooley 345817f427 docs: New doc HTTP client - Pass metadata to interceptors. (#48918)
PR Close #48918
2023-02-17 11:06:58 -08:00
Virginia Dooley 24b6eea0a9 docs: New doc HTTP client - Test requests (#48917)
PR Close #48917
2023-02-17 11:06:04 -08:00
Virginia Dooley d457ffc408 docs: New doc HTTP client - Security: Cross-Site Request Forgery (XSRF) protection (#48916)
PR Close #48916
2023-02-17 11:05:27 -08:00
Virginia Dooley a378267117 docs: New doc extract from original HTTP doc to be retired. (#48913)
PR Close #48913
2023-02-17 11:04:51 -08:00
Virginia Dooley 11f8f8d8e4 docs: new doc extract from original HTTP doc to be retired. (#48911)
PR Close #48911
2023-02-17 11:04:22 -08:00
Virginia Dooley 4811850607 docs: new doc extract from original HTTP doc which is to be retired. (#48905)
PR Close #48905
2023-02-17 11:03:49 -08:00
Virginia Dooley 5d6440947a docs: New document extracted from the original Communicating with backend services using HTTP document, which is to be retired. (#47965)
PR Close #47965
2023-02-17 11:03:06 -08:00
Andrew Kushnir 25e220a23a fix(platform-server): avoid duplicate TransferState info after renderApplication call (#49094)
This commit updates the `renderApplication` function to avoid duplicate serialization of the data from the `TransferState` class. The `renderApplication` function imports providers from the `ServerModule`, which already include the `TransferState` serialization providers, but the same providers were also included inside the `renderApplication` as well, which led to the duplication.

PR Close #49094
2023-02-16 16:00:30 -08:00
Matthieu Riegler c95766ed12 refactor: restore tree shaking for a warning message (#49064)
`getInheritedInjectableDef` logs a depreciation warning that can be tree shaked in prod. Let's do it.

PR Close #49064
2023-02-16 15:55:44 -08:00
Matthieu Riegler 43e9301783 docs: fixing typo in angular compiler options (#49085)
The strictness flags that this "option" instead of "open".

Fixes #49078

PR Close #49085
2023-02-16 15:54:15 -08:00
Andrew Scott e63fb8031a refactor(router): Remove warning for an invalid ActivatedRoute (#49117)
This warning was put in place to surface an error when developers use an ActivatedRoute
with an invalid structure in tests. However, there isn't a clear path to fixing it and
the tests continue to pass (ideally - that's what the recovery code is there for).
Rather than surfacing an error that developers would be confused by and likely ignore,
it would be better to not warn at all unless there is a clearer action to take to
resolve the issue.

resolves #49116

PR Close #49117
2023-02-16 15:53:29 -08:00
John Manners 25bed17c5f docs: fix typo in toh-pt5.md (#49108)
Line 254 - change 'liberate' to 'liberates'.
PR Close #49108
2023-02-16 15:52:33 -08:00
John Manners 117af7d8b5 docs: improve sentence in toh-pt5.md (#49109)
Line 302 - improve clarity.
PR Close #49109
2023-02-16 15:51:27 -08:00
Ikko Eltociear Ashimine ee7a9248a8 docs: fix typo in router-tutorial-toh.md (#49095)
non-existant -> non-existent
PR Close #49095
2023-02-16 15:50:56 -08:00
Ilyass e1607cdbd4 docs(core): typo adding missing comma (#49088)
PR Close #49088
2023-02-16 15:49:09 -08:00
Kristiyan Kostadinov b06a1d0349 docs: add guide for standalone migration (#49044)
Adds a guide describing how to use the standalone migration schematic. The new guide is grouped together with the existing standalone guide.

PR Close #49044
2023-02-16 15:33:18 -08:00
mgechev a814ed1382 docs: close the developer survey (#49092)
PR Close #49092
2023-02-16 15:32:45 -08:00
Paul Gschwendtner 1a7444f99f build: avoid unnecessary re-evaluation of starlark code (#49106)
The experimental allow tags propagation flag is a `BuildLanguage` option
and causes all Starlark code to be re-invoked. This causes a slow-down
when switching between bazel query/ bazel build because the option is not set for `bazel query`.

We fix it by applying the option to all commands, using `common`.

PR Close #49106
2023-02-16 15:31:56 -08:00
Alan Agius bf4ad38117 fix(platform-browser): remove styles from DOM of destroyed components (#48298)
Currently style of components using `encapsulation`, `None` or `Emulated` will not be removed from the DOM once the component get destroyed.

This change addresses this by keeping track of the number of times a component is rendered, when the component is destroyed the counter is decreased and once this reaches zero the style element is removed from the DOM.

Currently, this new behaviour is on opt-in bases, but it will be changed in the next major version.

To opt-in, set the `REMOVE_STYLES_ON_COMPONENT_DESTROY` DI token to `true`.

Example
```ts
@NgModule({
 declarations: [
   AppComponent,
 ],
 imports: [
   BrowserModule
 ],
 providers: [
   { provide: REMOVE_STYLES_ON_COMPONENT_DESTROY, useValue: true }
 ],
 bootstrap: [AppComponent]
})
export class AppModule { }
```

Closes #16670

PR Close #48298
2023-02-16 15:31:24 -08:00
Kristiyan Kostadinov 86d4016d23 refactor(compiler): remove remaining usage of getMutableClone (#49070)
Uses an alternate approach of preserving default imports that doesn't involve the `getMutableClone` function that is being removed in TypeScript 5.0.

The alternate approach was already used in the downlevel transform and it works by patching the EmitResolver of the current transformation context to tell TypeScript to preserve the import.

PR Close #49070
2023-02-16 15:30:53 -08:00
Pawel Kozlowski 440b51b7af release: cut the v15.2.0-rc.0 release 2023-02-15 18:45:14 +01:00
424 changed files with 9534 additions and 8170 deletions
+3 -2
View File
@@ -134,9 +134,10 @@ build:remote --project_id=internal-200822
build:remote --remote_cache=remotebuildexecution.googleapis.com
build:remote --remote_executor=remotebuildexecution.googleapis.com
# Ensure that tags like "no-remote-exec" get propagated to actions created by rules.
# Ensure that tags like "no-remote-exec" get propagated to actions created by rules,
# even if the rule implementation does not explicitly pass them to the execution requirements.
# https://bazel.build/reference/command-line-reference#flag--experimental_allow_tags_propagation
build --experimental_allow_tags_propagation
common --experimental_allow_tags_propagation
# Disable network access in the sandbox by default. To enable network access
# for a particular target, use:
+15 -13
View File
@@ -74,7 +74,7 @@ var_9: &only_release_branches
# https://circleci.com/developer/orbs.
orbs:
node: circleci/node@5.0.1
devinfra: angular/dev-infra@1.0.6
devinfra: angular/dev-infra@1.0.8
# Executor Definitions
# https://circleci.com/docs/2.0/reusing-config/#authoring-reusable-executors
@@ -89,7 +89,7 @@ executors:
type: string
default: medium
docker:
- image: cimg/node:16.13.0
- image: cimg/node:16.14.0
resource_class: << parameters.resource_class >>
working_directory: ~/ng
@@ -99,7 +99,7 @@ executors:
type: string
default: medium
docker:
- image: cimg/node:16.13.0-browsers
- image: cimg/node:16.14.0-browsers
resource_class: << parameters.resource_class >>
working_directory: ~/ng
@@ -150,7 +150,7 @@ commands:
name: Configure git
command: |
mkdir -p ~/.ssh
echo 'github.com ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ==' >> ~/.ssh/known_hosts
echo 'github.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCj7ndNxQowgcQnjshcLrqPEiiphnt+VTTvDP6mHBL9j1aNUkY4Ue1gvwnGLVlOhGeYrnZaMgRK6+PKCUXaDbC7qtbW8gIkhL7aGCsOr/C56SJMy/BCZfxd1nWzAOxSDPgVsmerOBYfNqltV9/hWCqBywINIR+5dIg6JTJ72pcEpEjcYgXkE2YEFXV1JHnsKgbLWNlhScqb2UmyRkQyytRLtL+38TGxkxCflmO+5Z8CSSNY7GidjMIZ7Q4zMjA2n1nGrlTDkzwDCsw+wqFPGQA179cnfGWOWRVruj16z6XyvxvjJwbz0wQZ75XK5tKSb7FNyeIEs4TT4jk+S4dhPeAUC5y+bDYirYgM4GC7uEnztnZyaVWQ7B381AK4Qdrwt51ZqExKbQpTUNn+EjqoTwvqNj4kqx5QUCI0ThS/YkOxJCXmPUWZbhjpCg56i+2aB6CmK2JGhn57K5mj0MNdBXA4/WnwH6XoPWJzK5Nyu2zB3nAZp+S5hpQs+p1vN1/wsjk=' >> ~/.ssh/known_hosts
git config --global url."ssh://git@github.com".insteadOf "https://github.com" || true
git config --global gc.auto 0 || true
@@ -595,22 +595,16 @@ jobs:
executor: windows-executor
steps:
- checkout
- save_month_to_file
- capture_patches_for_cache_key
- init_environment
# Setup the proper NodeJS version. The image comes pre-installed with `nvm-windows`.
# Note: This happens immediately after checkout because environment initialization logic
# might rely on Node and shouldn't use the older image-provided NodeJS version.
- run:
name: Install NodeJS version from `.nvmrc`.
command: |
nvm on
nvm install $(cat .nvmrc)
nvm use $(cat .nvmrc)
- restore_cache:
keys:
- *cache_key_win
- *cache_key_win_fallback
- run:
name: Debug information for flakiness of Windows job
command: |
@@ -621,6 +615,14 @@ jobs:
echo "Path: $PATH"
yarn node -v
- save_month_to_file
- capture_patches_for_cache_key
- init_environment
- restore_cache:
keys:
- *cache_key_win
- *cache_key_win_fallback
# Install project dependencies, and install Bazelisk globally. This is necessary as
# Windows might error when `bazel` is invoked from the project node modules. The Bazel
# invocation might modify the symlinked project `node_modules` again, causing failures.
+1 -1
View File
@@ -4,7 +4,7 @@ description: 'Installs the dependencies using Yarn'
runs:
using: 'composite'
steps:
- uses: actions/cache@6998d139ddd3e68c71e9e398d8e40b71a2f39812 # v3
- uses: actions/cache@88522ab9f39a2ea568f7027eddc7d8d8bc9d59c8 # v3
with:
path: |
./node_modules/
+2 -3
View File
@@ -1,8 +1,8 @@
# Configuration for angular-robot
#options for the size plugin
# options for the size plugin
size:
disabled: false
disabled: true
maxSizeIncrease: 2000
circleCiStatusName: 'ci/circleci: test'
@@ -70,7 +70,6 @@ merge:
requiredStatuses:
- 'ci/circleci: build'
- 'ci/circleci: lint'
- 'ci/angular: size'
- 'google-internal-tests'
- 'pullapprove'
+2 -2
View File
@@ -25,7 +25,7 @@ jobs:
- uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0
- uses: ./.github/actions/yarn-install
- uses: angular/dev-infra/github-actions/setup-bazel-remote-exec@accc3c96df0d40ff639070132acb0699a58bfcf8
- uses: angular/dev-infra/github-actions/setup-bazel-remote-exec@1564c4e45db49460f2351cba356311e28062aa2f
with:
bazelrc: ./.bazelrc.user
@@ -34,7 +34,7 @@ jobs:
# the number of concurrent actions is determined based on the host resources.
- run: bazel build //aio:build --jobs=32 --announce_rc --verbose_failures
- uses: angular/dev-infra/github-actions/deploy-previews/pack-and-upload-artifact@accc3c96df0d40ff639070132acb0699a58bfcf8
- uses: angular/dev-infra/github-actions/deploy-previews/pack-and-upload-artifact@1564c4e45db49460f2351cba356311e28062aa2f
with:
workflow-artifact-name: 'aio'
pull-number: '${{github.event.pull_request.number}}'
+2 -2
View File
@@ -25,7 +25,7 @@ jobs:
runs-on: ubuntu-latest
if: ${{ github.event.workflow_run.conclusion == 'success' }}
steps:
- uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # tag=v3
- uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # v3
- name: Configure Firebase deploy target
working-directory: aio/
@@ -34,7 +34,7 @@ jobs:
npx -y firebase-tools@latest target:clear --project ${{env.PREVIEW_PROJECT}} hosting aio
npx -y firebase-tools@latest target:apply --project ${{env.PREVIEW_PROJECT}} hosting aio ${{env.PREVIEW_SITE}}
- uses: angular/dev-infra/github-actions/deploy-previews/upload-artifacts-to-firebase@accc3c96df0d40ff639070132acb0699a58bfcf8
- uses: angular/dev-infra/github-actions/deploy-previews/upload-artifacts-to-firebase@1564c4e45db49460f2351cba356311e28062aa2f
with:
github-token: '${{secrets.GITHUB_TOKEN}}'
workflow-artifact-name: 'aio'
@@ -16,6 +16,6 @@ jobs:
- uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0
with:
persist-credentials: false
- uses: angular/dev-infra/github-actions/branch-manager@accc3c96df0d40ff639070132acb0699a58bfcf8
- uses: angular/dev-infra/github-actions/branch-manager@1564c4e45db49460f2351cba356311e28062aa2f
with:
angular-robot-key: ${{ secrets.ANGULAR_ROBOT_PRIVATE_KEY }}
+4 -4
View File
@@ -12,14 +12,14 @@ jobs:
labels:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0
- uses: angular/dev-infra/github-actions/commit-message-based-labels@accc3c96df0d40ff639070132acb0699a58bfcf8
- uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # v3.5.2
- uses: angular/dev-infra/github-actions/commit-message-based-labels@1564c4e45db49460f2351cba356311e28062aa2f
with:
angular-robot-key: ${{ secrets.ANGULAR_ROBOT_PRIVATE_KEY }}
post_approval_changes:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0
- uses: angular/dev-infra/github-actions/post-approval-changes@accc3c96df0d40ff639070132acb0699a58bfcf8
- uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # v3.5.2
- uses: angular/dev-infra/github-actions/post-approval-changes@1564c4e45db49460f2351cba356311e28062aa2f
with:
angular-robot-key: ${{ secrets.ANGULAR_ROBOT_PRIVATE_KEY }}
+1 -1
View File
@@ -14,6 +14,6 @@ jobs:
if: github.repository == 'angular/angular'
runs-on: ubuntu-latest
steps:
- uses: angular/dev-infra/github-actions/feature-request@accc3c96df0d40ff639070132acb0699a58bfcf8
- uses: angular/dev-infra/github-actions/feature-request@1564c4e45db49460f2351cba356311e28062aa2f
with:
angular-robot-key: ${{ secrets.ANGULAR_ROBOT_PRIVATE_KEY }}
+2 -2
View File
@@ -12,8 +12,8 @@ jobs:
trigger:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0
- uses: angular/dev-infra/github-actions/google-internal-tests@accc3c96df0d40ff639070132acb0699a58bfcf8
- uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # v3.5.2
- uses: angular/dev-infra/github-actions/google-internal-tests@1564c4e45db49460f2351cba356311e28062aa2f
with:
run-tests-guide-url: http://go/angular/g3sync
github-token: ${{ secrets.GITHUB_TOKEN }}
+1 -1
View File
@@ -14,6 +14,6 @@ jobs:
if: github.repository == 'angular/angular'
runs-on: ubuntu-latest
steps:
- uses: angular/dev-infra/github-actions/lock-closed@accc3c96df0d40ff639070132acb0699a58bfcf8
- uses: angular/dev-infra/github-actions/lock-closed@462f716ef571b2b41fff90aaa5bb10897693efcc
with:
lock-bot-key: ${{ secrets.LOCK_BOT_PRIVATE_KEY }}
+1 -1
View File
@@ -9,6 +9,6 @@ jobs:
status:
runs-on: ubuntu-latest
steps:
- uses: angular/dev-infra/github-actions/unified-status-check@accc3c96df0d40ff639070132acb0699a58bfcf8
- uses: angular/dev-infra/github-actions/unified-status-check@1564c4e45db49460f2351cba356311e28062aa2f
with:
angular-robot-key: ${{ secrets.ANGULAR_ROBOT_PRIVATE_KEY }}
+3 -3
View File
@@ -25,12 +25,12 @@ jobs:
steps:
- name: 'Checkout code'
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0
uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab # v3.5.2
with:
persist-credentials: false
- name: 'Run analysis'
uses: ossf/scorecard-action@e38b1902ae4f44df626f11ba0734b14fb91f8f86 # v2.1.2
uses: ossf/scorecard-action@80e868c13c90f172d68d1f4501dee99e2479f7af # v2.1.3
with:
results_file: results.sarif
results_format: sarif
@@ -47,6 +47,6 @@ jobs:
# Upload the results to GitHub's code scanning dashboard.
- name: 'Upload to code-scanning'
uses: github/codeql-action/upload-sarif@17573ee1cc1b9d061760f3a006fc4aac4f944fd5 # v2.2.4
uses: github/codeql-action/upload-sarif@7df0ce34898d659f95c0c4a09eaa8d4e32ee64db # v2.2.12
with:
sarif_file: results.sarif
+1 -1
View File
@@ -32,7 +32,7 @@ jobs:
env:
ANGULAR_CLI_BUILDS_READONLY_GITHUB_TOKEN: ${{ secrets.ANGULAR_CLI_BUILDS_READONLY_GITHUB_TOKEN }}
- name: Create a PR (if necessary)
uses: angular/dev-infra/github-actions/create-pr-for-changes@accc3c96df0d40ff639070132acb0699a58bfcf8
uses: angular/dev-infra/github-actions/create-pr-for-changes@1564c4e45db49460f2351cba356311e28062aa2f
with:
branch-prefix: update-cli-help
pr-title: 'docs: update Angular CLI help [${{github.ref_name}}]'
+1 -1
View File
@@ -35,7 +35,7 @@ jobs:
- name: Generate `events.json`
run: node aio/scripts/generate-events/index.mjs --ignore-invalid-dates
- name: Create a PR (if necessary)
uses: angular/dev-infra/github-actions/create-pr-for-changes@accc3c96df0d40ff639070132acb0699a58bfcf8
uses: angular/dev-infra/github-actions/create-pr-for-changes@1564c4e45db49460f2351cba356311e28062aa2f
with:
branch-prefix: docs-update-events
pr-title: 'docs: update events'
+1 -1
View File
@@ -14,7 +14,7 @@ export const caretaker: CaretakerConfig = {
},
{
name: 'Initial Triage Queue',
query: `is:open no:milestone`,
query: `is:open no:milestone -draft:true`,
},
],
caretakerGroup: 'angular-caretaker',
+1 -1
View File
@@ -1 +1 @@
16.13.0
16.14.0
+6 -2
View File
@@ -56,8 +56,9 @@
version: 3
# availability:
# users_unavailable:
availability:
users_unavailable:
- devversion
# Meta field that goes unused by PullApprove to allow for defining aliases to be
# used throughout the config.
@@ -350,6 +351,7 @@ groups:
'aio/content/guide/singleton-services.md',
'aio/content/guide/sharing-ngmodules.md',
'aio/content/guide/standalone-components.md',
'aio/content/guide/standalone-migration.md',
'aio/content/guide/structural-directives.md',
'aio/content/examples/structural-directives/**/{*,.*}',
'aio/content/guide/svg-in-templates.md',
@@ -416,6 +418,7 @@ groups:
'aio/content/guide/http-request-data-from-server.md',
'aio/content/guide/http-security-xsrf-protection.md',
'aio/content/guide/http-send-data-to-server.md',
'aio/content/guide/http-server-communication.md',
'aio/content/guide/http-setup-server-communication.md',
'aio/content/guide/http-test-requests.md',
'aio/content/guide/http-track-show-request-progress.md',
@@ -952,6 +955,7 @@ groups:
'aio/content/guide/migration-module-with-providers.md',
'aio/content/guide/static-query-migration.md',
'aio/content/guide/update-to-latest-version.md',
'aio/content/guide/versions.md',
'aio/content/guide/update-to-version-14.md',
'aio/content/guide/update-to-version-15.md'
])
+190 -117
View File
@@ -1,16 +1,149 @@
<a name="15.1.5"></a>
# 15.1.5 (2023-02-15)
### forms
<a name="15.2.8"></a>
# 15.2.8 (2023-04-19)
### core
| Commit | Type | Description |
| -- | -- | -- |
| [5f2a3edcf2](https://github.com/angular/angular/commit/5f2a3edcf27cfe6ffc6ae4d67ca2b47953f26336) | fix | Make radio buttons respect `[attr.disabled]` ([#48864](https://github.com/angular/angular/pull/48864)) |
## Special Thanks
AleksanderBodurri, Alvaro Junqueira, Dylan Hunn, Joey Perrott, Matthieu Riegler, PaloMiklo and Paul Gschwendtner
| [2fff8fadbe](https://github.com/angular/angular/commit/2fff8fadbeff9df3bc09b8847dbf08febbe3b5f8) | fix | handle invalid classes in class array bindings ([#49924](https://github.com/angular/angular/pull/49924)) |
### http
| Commit | Type | Description |
| -- | -- | -- |
| [05a0225deb](https://github.com/angular/angular/commit/05a0225deb126849f3798e828f6dbef7c221ec57) | fix | prevent headers from throwing an error when initializing numerical values ([#49379](https://github.com/angular/angular/pull/49379)) |
### router
| Commit | Type | Description |
| -- | -- | -- |
| [09a42d988e](https://github.com/angular/angular/commit/09a42d988e654825648205c8df90f7ca4d034c74) | fix | canceledNavigationResolution: 'computed' with redirects to the current URL ([#49793](https://github.com/angular/angular/pull/49793)) |
<!-- CHANGELOG SPLIT MARKER -->
<a name="15.2.0-next.4"></a>
# 15.2.0-next.4 (2023-02-08)
<a name="15.2.7"></a>
# 15.2.7 (2023-04-12)
### compiler
| Commit | Type | Description |
| -- | -- | -- |
| [b0c1a90f55](https://github.com/angular/angular/commit/b0c1a90f55ecfafb4fd5c22cdd1b4a5f12573f22) | fix | Produce diagnositc if directive used in host binding is not exported ([#49792](https://github.com/angular/angular/pull/49792)) |
### compiler-cli
| Commit | Type | Description |
| -- | -- | -- |
| [a40529af2e](https://github.com/angular/angular/commit/a40529af2e2923f1dbdae8898a0e94e9e63a3fcf) | fix | Catch FatalDiagnosticError during template type checking ([#49792](https://github.com/angular/angular/pull/49792)) |
### core
| Commit | Type | Description |
| -- | -- | -- |
| [702ec90110](https://github.com/angular/angular/commit/702ec901100b2d84efdf0b16d8347f8b28b94d5d) | fix | When using setInput, mark view dirty in same way as `markForCheck` ([#49747](https://github.com/angular/angular/pull/49747)) |
## Special Thanks
Alan Agius, Andrew Kushnir, Andrew Scott, Kristiyan Kostadinov, Matthieu Riegler and Nikola Kološnjaji
<!-- CHANGELOG SPLIT MARKER -->
<a name="15.2.6"></a>
# 15.2.6 (2023-04-05)
### core
| Commit | Type | Description |
| -- | -- | -- |
| [d9efa1b0d7](https://github.com/angular/angular/commit/d9efa1b0d742217de1164f7904c202b2697348d9) | feat | change the URL sanitization to only block javascript: URLs ([#49659](https://github.com/angular/angular/pull/49659)) |
### router
| Commit | Type | Description |
| -- | -- | -- |
| [cad7274ef9](https://github.com/angular/angular/commit/cad7274ef90914f0c24d071473a6cbae0e5b8250) | fix | create correct URL relative to path with empty child ([#49691](https://github.com/angular/angular/pull/49691)) |
| [9b61379096](https://github.com/angular/angular/commit/9b6137909690d6cbfdd8cbef502e9e2ac0d28c4a) | fix | Ensure initial navigation clears current navigation when blocking ([#49572](https://github.com/angular/angular/pull/49572)) |
## Special Thanks
Andrew Scott, Guillaume Weghsteen, John Manners, Johnny Gérard, Matthieu Riegler, Robin Richtsfeld, Sandra Limacher, Sarthak Thakkar, Vinit Neogi and vikram menon
<!-- CHANGELOG SPLIT MARKER -->
<a name="15.2.5"></a>
# 15.2.5 (2023-03-29)
### common
| Commit | Type | Description |
| -- | -- | -- |
| [ca5acadb78](https://github.com/angular/angular/commit/ca5acadb78c33bf896001a5810cb4be15ff7bc86) | fix | invalid ImageKit transformation ([#49201](https://github.com/angular/angular/pull/49201)) |
### compiler
| Commit | Type | Description |
| -- | -- | -- |
| [077f6b4674](https://github.com/angular/angular/commit/077f6b4674c01bfed083e73a17d848e226e543b4) | fix | do not unquote CSS values ([#49460](https://github.com/angular/angular/pull/49460)) |
| [c3cff35869](https://github.com/angular/angular/commit/c3cff35869648fdf70c9707c3d87bcfdcc84d903) | fix | handle trailing comma in object literal ([#49535](https://github.com/angular/angular/pull/49535)) |
### core
| Commit | Type | Description |
| -- | -- | -- |
| [d201fc2dec](https://github.com/angular/angular/commit/d201fc2dec1a3a9cc6952ebb46cb672200a78236) | fix | set style property value to empty string instead of an invalid value ([#49460](https://github.com/angular/angular/pull/49460)) |
### router
| Commit | Type | Description |
| -- | -- | -- |
| [978d37f324](https://github.com/angular/angular/commit/978d37f324ce4a1fe9b57f3d9430d7c28ecf6131) | fix | Ensure Router preloading works with lazy component and static children ([#49571](https://github.com/angular/angular/pull/49571)) |
| [a844435514](https://github.com/angular/angular/commit/a844435514962c52f4fb480bcfab7ee6519a59cc) | fix | fix [#49457](https://github.com/angular/angular/pull/49457) outlet activating with old info ([#49459](https://github.com/angular/angular/pull/49459)) |
## Special Thanks
Alan Agius, Andrew Scott, Asaf Malin, Jan Cabadaj, Kristiyan Kostadinov, Matthieu Riegler, Paul Gschwendtner, Sid and Tano Abeleyra
<!-- CHANGELOG SPLIT MARKER -->
<a name="15.2.4"></a>
# 15.2.4 (2023-03-22)
### core
| Commit | Type | Description |
| -- | -- | -- |
| [bae6b5ceb1](https://github.com/angular/angular/commit/bae6b5ceb16bd87c8146aa29564a8d29135a6f95) | fix | Allow `TestBed.configureTestingModule` to work with recursive cycle of standalone components. ([#49473](https://github.com/angular/angular/pull/49473)) |
| [087f4412af](https://github.com/angular/angular/commit/087f4412afe9ccdefe7d63012af749b79f3e84d0) | fix | more accurate matching of classes during content projection ([#48888](https://github.com/angular/angular/pull/48888)) |
## Special Thanks
Aditya Srinivasan, Alex Rickabaugh, Andrew Scott, Kristiyan Kostadinov, Masaoki Kobayashi, Matthieu Riegler, Paul Gschwendtner, Peter Götz, Thomas Pischke, Virginia Dooley and avmaxim
<!-- CHANGELOG SPLIT MARKER -->
<a name="15.2.3"></a>
# 15.2.3 (2023-03-16)
## Special Thanks
Alan Agius, Esteban Gehring, Matthieu Riegler and Virginia Dooley
<!-- CHANGELOG SPLIT MARKER -->
<a name="15.2.2"></a>
# 15.2.2 (2023-03-08)
### migrations
| Commit | Type | Description |
| -- | -- | -- |
| [6207d6f1f0](https://github.com/angular/angular/commit/6207d6f1f0771ff3b74379367e65af665ef0e51c) | fix | add protractor support if protractor imports are detected ([#49274](https://github.com/angular/angular/pull/49274)) |
## Special Thanks
Alan Agius, Andrew Kushnir, Andrew Scott, Kristiyan Kostadinov, Matthieu Riegler, Paul Gschwendtner, Sai Kartheek Bommisetty and Vinit Neogi
<!-- CHANGELOG SPLIT MARKER -->
<a name="15.2.1"></a>
# 15.2.1 (2023-03-01)
### common
| Commit | Type | Description |
| -- | -- | -- |
| [f0e926074d](https://github.com/angular/angular/commit/f0e926074df189b3e3ca361a6a3bcd852c05e010) | fix | make Location.normalize() return the correct path when the base path contains characters that interfere with regex syntax. ([#49181](https://github.com/angular/angular/pull/49181)) |
### compiler-cli
| Commit | Type | Description |
| -- | -- | -- |
| [04d8b6c61a](https://github.com/angular/angular/commit/04d8b6c61a0d0a2d61b9202d09774f3ab347e82f) | fix | do not persist component analysis if template/styles are missing ([#49184](https://github.com/angular/angular/pull/49184)) |
### core
| Commit | Type | Description |
| -- | -- | -- |
| [d60ea6ab5a](https://github.com/angular/angular/commit/d60ea6ab5a22cb4f3677e34d0d7f6be0c3fe23fe) | fix | update zone.js peerDependencies ranges ([#49244](https://github.com/angular/angular/pull/49244)) |
### migrations
| Commit | Type | Description |
| -- | -- | -- |
| [44d095a61c](https://github.com/angular/angular/commit/44d095a61cb340ea1f5e0a19370ea839378b02c3) | fix | avoid migrating the same class multiple times in standalone migration ([#49245](https://github.com/angular/angular/pull/49245)) |
| [92b0bda9e4](https://github.com/angular/angular/commit/92b0bda9e4e7117552f929bf86acfc0ae65779a1) | fix | delete barrel exports in standalone migration ([#49176](https://github.com/angular/angular/pull/49176)) |
### router
| Commit | Type | Description |
| -- | -- | -- |
| [3062442728](https://github.com/angular/angular/commit/30624427289ad65bdbabd865d028146753c3a97a) | fix | add error message when using loadComponent with a NgModule ([#49164](https://github.com/angular/angular/pull/49164)) |
## Special Thanks
Alan Agius, Andrew Kushnir, Aristeidis Bampakos, Craig Spence, Doug Parker, Iván Navarro, Joey Perrott, Kristiyan Kostadinov, Matthieu Riegler, Michael Ziluck, Paul Gschwendtner, Stephanie Tuerk, Vincent and Virginia Dooley
<!-- CHANGELOG SPLIT MARKER -->
<a name="15.2.0"></a>
# 15.2.0 (2023-02-22)
## Deprecations
###
- Class and `InjectionToken` guards and resolvers are
deprecated. Instead, write guards as plain JavaScript functions and
inject dependencies with `inject` from `@angular/core`.
###
| Commit | Type | Description |
| -- | -- | -- |
| [926c35f4ac](https://github.com/angular/angular/commit/926c35f4ac70f5e4d142e545d6d056dd67aac97b) | docs | Deprecate class and InjectionToken and resolvers ([#47924](https://github.com/angular/angular/pull/47924)) |
### common
| Commit | Type | Description |
| -- | -- | -- |
@@ -19,27 +152,75 @@ AleksanderBodurri, Alvaro Junqueira, Dylan Hunn, Joey Perrott, Matthieu Riegler,
| Commit | Type | Description |
| -- | -- | -- |
| [0cf11167f1](https://github.com/angular/angular/commit/0cf11167f13108992ec781e88ab2a7d1fc7f5a0d) | fix | incorrectly detecting forward refs when symbol already exists in file ([#48988](https://github.com/angular/angular/pull/48988)) |
### core
| Commit | Type | Description |
| -- | -- | -- |
| [a154db8a81](https://github.com/angular/angular/commit/a154db8a81cbdfed8c3d0db1e2a5bf43aa3e0bbf) | feat | add ng generate schematic to convert declarations to standalone ([#48790](https://github.com/angular/angular/pull/48790)) |
| [345e737daa](https://github.com/angular/angular/commit/345e737daa7b9f635a4c2923358e5e765f716434) | feat | add ng generate schematic to convert to standalone bootstrapping APIs ([#48848](https://github.com/angular/angular/pull/48848)) |
| [e7318fc758](https://github.com/angular/angular/commit/e7318fc758d9e64d1a7f60a2c7071a769b73e7d8) | feat | add ng generate schematic to remove unnecessary modules ([#48832](https://github.com/angular/angular/pull/48832)) |
### language-service
| Commit | Type | Description |
| -- | -- | -- |
| [4ae384fd61](https://github.com/angular/angular/commit/4ae384fd619a13eaadf737d08a97f07e1f6b273c) | feat | Allow auto-imports of a pipe via quick fix when its selector is used, both directly and via reexports. ([#48354](https://github.com/angular/angular/pull/48354)) |
| [141333411e](https://github.com/angular/angular/commit/141333411e67769d752c7162e4cb03376022f5e1) | feat | Introduce a new NgModuleIndex, and use it to suggest re-exports. ([#48354](https://github.com/angular/angular/pull/48354)) |
| [d0145033bd](https://github.com/angular/angular/commit/d0145033bd11eccd16fa8b61ba9170037d0c62b3) | fix | generate forwardRef for same file imports ([#48898](https://github.com/angular/angular/pull/48898)) |
### migrations
| Commit | Type | Description |
| -- | -- | -- |
| [2796230e95](https://github.com/angular/angular/commit/2796230e953eb8c29d6227a1a3858f5f08a8f200) | fix | add `enum` in `mode` option in `standalone` schema ([#48851](https://github.com/angular/angular/pull/48851)) |
| [816e76a578](https://github.com/angular/angular/commit/816e76a5789b041fee78ddd278c0e0d19b9a617a) | fix | automatically prune root module after bootstrap step ([#49030](https://github.com/angular/angular/pull/49030)) |
| [bdbf21d04b](https://github.com/angular/angular/commit/bdbf21d04ba74a6f73469242076d6ce697c57edf) | fix | avoid generating imports with forward slashes ([#48993](https://github.com/angular/angular/pull/48993)) |
| [32cf4e5cb9](https://github.com/angular/angular/commit/32cf4e5cb989f365296d519dddf72fb38ca47c40) | fix | avoid internal modules when generating imports ([#48958](https://github.com/angular/angular/pull/48958)) |
| [521ccfbe6c](https://github.com/angular/angular/commit/521ccfbe6ce9af1a7ddd6ab5e70151b7198f82ef) | fix | avoid interrupting the migration if language service lookup fails ([#49010](https://github.com/angular/angular/pull/49010)) |
| [a40cd47aa7](https://github.com/angular/angular/commit/a40cd47aa7ebccfbeeb26e397e03f1372aa10a55) | fix | avoid modifying testing modules without declarations ([#48921](https://github.com/angular/angular/pull/48921)) |
| [1afa6ed322](https://github.com/angular/angular/commit/1afa6ed3227e784e3fe2b4b31443961589cb6332) | fix | don't add ModuleWithProviders to standalone test components ([#48987](https://github.com/angular/angular/pull/48987)) |
| [c98c6a8452](https://github.com/angular/angular/commit/c98c6a845286b9b89daf275a9c4a2bdbc7ad77a7) | fix | don't copy animations modules into the imports of test components ([#49147](https://github.com/angular/angular/pull/49147)) |
| [8389557848](https://github.com/angular/angular/commit/83895578488bd35c7e47609f092907eb0f53f435) | fix | don't copy unmigrated declarations into imports array ([#48882](https://github.com/angular/angular/pull/48882)) |
| [f82bdc4b01](https://github.com/angular/angular/commit/f82bdc4b01f93a7103870449d37da61cc4c4f179) | fix | don't delete classes that may provide dependencies transitively ([#48866](https://github.com/angular/angular/pull/48866)) |
| [759db12e0b](https://github.com/angular/angular/commit/759db12e0b618fcb51f4cb141adeb49bfa495a60) | fix | duplicated comments on migrated classes ([#48966](https://github.com/angular/angular/pull/48966)) |
| [ba38178d19](https://github.com/angular/angular/commit/ba38178d1918d413f9c2260c40eb6542eadfddba) | fix | generate forwardRef for same file imports ([#48898](https://github.com/angular/angular/pull/48898)) |
| [03fcb36cfd](https://github.com/angular/angular/commit/03fcb36cfd36731028bf288f156e16cb8ac4c758) | fix | migrate HttpClientModule to provideHttpClient() ([#48949](https://github.com/angular/angular/pull/48949)) |
| [2de6dae16d](https://github.com/angular/angular/commit/2de6dae16d4b0b83f0517a3033cda44ba44154ed) | fix | migrate RouterModule.forRoot with a config object to use features ([#48935](https://github.com/angular/angular/pull/48935)) |
| [770191cf1f](https://github.com/angular/angular/commit/770191cf1f1254546625dfa7a882b716c3f0aab3) | fix | migrate tests when switching to standalone bootstrap API ([#48987](https://github.com/angular/angular/pull/48987)) |
| [c7926b5773](https://github.com/angular/angular/commit/c7926b57730c23f765a00d3dd9f92079c95e87e0) | fix | move standalone migrations into imports ([#48987](https://github.com/angular/angular/pull/48987)) |
| [65c74ed93e](https://github.com/angular/angular/commit/65c74ed93e04cb560c27838d440c6aa7a9859a4e) | fix | normalize paths to posix ([#48850](https://github.com/angular/angular/pull/48850)) |
| [6377487b1a](https://github.com/angular/angular/commit/6377487b1ab7679cef9a44f88440fe5e8eb97480) | fix | only exclude bootstrapped declarations from initial standalone migration ([#48987](https://github.com/angular/angular/pull/48987)) |
| [e9e4449a43](https://github.com/angular/angular/commit/e9e4449a43430e026e61b0f05ebd32dd830fa916) | fix | preserve tsconfig in standalone migration ([#48987](https://github.com/angular/angular/pull/48987)) |
| [ffad1b49d9](https://github.com/angular/angular/commit/ffad1b49d95ab90637e7184f92cb5136d490d865) | fix | reduce number of files that need to be checked ([#48987](https://github.com/angular/angular/pull/48987)) |
| [ba7a757cc5](https://github.com/angular/angular/commit/ba7a757cc5a2f3f942adcbabdcd5b7aef33ea493) | fix | return correct alias when conflicting import exists ([#49139](https://github.com/angular/angular/pull/49139)) |
| [49a7c9f94a](https://github.com/angular/angular/commit/49a7c9f94ae8f89907da8b3620242e62f87ec5a4) | fix | standalone migration incorrectly throwing path error for multi app projects ([#48958](https://github.com/angular/angular/pull/48958)) |
| [584976e6c8](https://github.com/angular/angular/commit/584976e6c8a783d40578ab191132673300394a52) | fix | support --defaults in standalone migration ([#48921](https://github.com/angular/angular/pull/48921)) |
| [03f47ac901](https://github.com/angular/angular/commit/03f47ac9019eddbcb373b50c41bc6f523293ece1) | fix | use consistent quotes in generated imports ([#48876](https://github.com/angular/angular/pull/48876)) |
| [ebae506d89](https://github.com/angular/angular/commit/ebae506d894a90c38e0f2dd1e948acabdb0fdf2e) | fix | use import remapper in root component ([#49046](https://github.com/angular/angular/pull/49046)) |
| [40c976c909](https://github.com/angular/angular/commit/40c976c90975878852a87b7722076eb78944098b) | fix | use NgForOf instead of NgFor ([#49022](https://github.com/angular/angular/pull/49022)) |
| [4ac25b2aff](https://github.com/angular/angular/commit/4ac25b2affab4f959ad8c111f1e429a05b435422) | perf | avoid re-traversing nodes when resolving bootstrap call dependencies ([#49010](https://github.com/angular/angular/pull/49010)) |
| [26cb7ab2e6](https://github.com/angular/angular/commit/26cb7ab2e6ac9b61904361a8a544467b69eef3f3) | perf | speed up language service lookups ([#49010](https://github.com/angular/angular/pull/49010)) |
### platform-browser
| Commit | Type | Description |
| -- | -- | -- |
| [bf4ad38117](https://github.com/angular/angular/commit/bf4ad3811762d9ba43d18c3360d014a9ceb06b4d) | fix | remove styles from DOM of destroyed components ([#48298](https://github.com/angular/angular/pull/48298)) |
### platform-server
| Commit | Type | Description |
| -- | -- | -- |
| [25e220a23a](https://github.com/angular/angular/commit/25e220a23ab90520efc65f05cd9b7a22db582b87) | fix | avoid duplicate TransferState info after renderApplication call ([#49094](https://github.com/angular/angular/pull/49094)) |
### router
| Commit | Type | Description |
| -- | -- | -- |
| [31b94c762f](https://github.com/angular/angular/commit/31b94c762fc91ab6cabe08ea6812780fdcf92a64) | feat | Add a withNavigationErrorHandler feature to provideRouter ([#48551](https://github.com/angular/angular/pull/48551)) |
| [dedac8d3f7](https://github.com/angular/angular/commit/dedac8d3f73ebf4f05b773454e2a22ab5fa4bf7c) | feat | Add test helper for trigger navigations in tests ([#48552](https://github.com/angular/angular/pull/48552)) |
## Special Thanks
Alex Castle, Andrew Scott, Dylan Hunn, Jessica Janiuk, Kian Yang Lee, Kristiyan Kostadinov, Matthieu Riegler, Pawel Kozlowski, Redouane Bekkouche, Simona Cotin and Walid Bouguima
Alan Agius, Alex Castle, Alex Rickabaugh, Andrew Kushnir, Andrew Scott, Dylan Hunn, Ikko Eltociear Ashimine, Ilyass, Jessica Janiuk, Joey Perrott, John Manners, Kalbarczyk, Kristiyan Kostadinov, Matthieu Riegler, Paul Gschwendtner, Pawel Kozlowski, Virginia Dooley, Walid Bouguima, cexbrayat and mgechev
<!-- CHANGELOG SPLIT MARKER -->
<a name="15.1.5"></a>
# 15.1.5 (2023-02-15)
### forms
| Commit | Type | Description |
| -- | -- | -- |
| [5f2a3edcf2](https://github.com/angular/angular/commit/5f2a3edcf27cfe6ffc6ae4d67ca2b47953f26336) | fix | Make radio buttons respect `[attr.disabled]` ([#48864](https://github.com/angular/angular/pull/48864)) |
## Special Thanks
AleksanderBodurri, Alvaro Junqueira, Dylan Hunn, Joey Perrott, Matthieu Riegler, PaloMiklo and Paul Gschwendtner
<!-- CHANGELOG SPLIT MARKER -->
@@ -82,73 +263,6 @@ Alan Agius, Besim Gürbüz, Brecht Billiet, Dario Piotrowicz, Dylan Hunn, Iván
<!-- CHANGELOG SPLIT MARKER -->
<a name="15.2.0-next.3"></a>
# 15.2.0-next.3 (2023-02-02)
### animations
| Commit | Type | Description |
| -- | -- | -- |
| [b4187548ca](https://github.com/angular/angular/commit/b4187548cae42f25624bf7ab7ad0cca121242de7) | fix | fix non-animatable warnings for easing ([#48583](https://github.com/angular/angular/pull/48583)) |
### common
| Commit | Type | Description |
| -- | -- | -- |
| [a055196c55](https://github.com/angular/angular/commit/a055196c55c57de281ff7167cd4dfb3df783c337) | fix | warn if using ngSrcset without a configured image loader ([#48804](https://github.com/angular/angular/pull/48804)) |
### compiler
| Commit | Type | Description |
| -- | -- | -- |
| [06e161f2dd](https://github.com/angular/angular/commit/06e161f2dd78b42ad1938578f4d730a41404a24f) | fix | incorrect code when non-null assertion is used after a safe access ([#48801](https://github.com/angular/angular/pull/48801)) |
### core
| Commit | Type | Description |
| -- | -- | -- |
| [345e737daa](https://github.com/angular/angular/commit/345e737daa7b9f635a4c2923358e5e765f716434) | feat | add ng generate schematic to convert to standalone bootstrapping APIs ([#48848](https://github.com/angular/angular/pull/48848)) |
### migrations
| Commit | Type | Description |
| -- | -- | -- |
| [2796230e95](https://github.com/angular/angular/commit/2796230e953eb8c29d6227a1a3858f5f08a8f200) | fix | add `enum` in `mode` option in `standalone` schema ([#48851](https://github.com/angular/angular/pull/48851)) |
| [a40cd47aa7](https://github.com/angular/angular/commit/a40cd47aa7ebccfbeeb26e397e03f1372aa10a55) | fix | avoid modifying testing modules without declarations ([#48921](https://github.com/angular/angular/pull/48921)) |
| [8389557848](https://github.com/angular/angular/commit/83895578488bd35c7e47609f092907eb0f53f435) | fix | don't copy unmigrated declarations into imports array ([#48882](https://github.com/angular/angular/pull/48882)) |
| [f82bdc4b01](https://github.com/angular/angular/commit/f82bdc4b01f93a7103870449d37da61cc4c4f179) | fix | don't delete classes that may provide dependencies transitively ([#48866](https://github.com/angular/angular/pull/48866)) |
| [04e0ac3d7c](https://github.com/angular/angular/commit/04e0ac3d7ca89bf38d4d2a38b7ca120d9b7b96ae) | fix | migration host incorrectly reading empty files ([#48849](https://github.com/angular/angular/pull/48849)) |
| [65c74ed93e](https://github.com/angular/angular/commit/65c74ed93e04cb560c27838d440c6aa7a9859a4e) | fix | normalize paths to posix ([#48850](https://github.com/angular/angular/pull/48850)) |
| [584976e6c8](https://github.com/angular/angular/commit/584976e6c8a783d40578ab191132673300394a52) | fix | support --defaults in standalone migration ([#48921](https://github.com/angular/angular/pull/48921)) |
| [03f47ac901](https://github.com/angular/angular/commit/03f47ac9019eddbcb373b50c41bc6f523293ece1) | fix | use consistent quotes in generated imports ([#48876](https://github.com/angular/angular/pull/48876)) |
### platform-server
| Commit | Type | Description |
| -- | -- | -- |
| [2fc5b70fce](https://github.com/angular/angular/commit/2fc5b70fcedb8ac35b825b245c0ae394dc125244) | fix | insert transfer state `script` before other `script` tags ([#48868](https://github.com/angular/angular/pull/48868)) |
### router
| Commit | Type | Description |
| -- | -- | -- |
| [dedac8d3f7](https://github.com/angular/angular/commit/dedac8d3f73ebf4f05b773454e2a22ab5fa4bf7c) | feat | Add test helper for trigger navigations in tests ([#48552](https://github.com/angular/angular/pull/48552)) |
| [16ef770db8](https://github.com/angular/angular/commit/16ef770db803ce4037a90c72477da412642dfb33) | fix | Handle routerLink directive on svg anchors. ([#48857](https://github.com/angular/angular/pull/48857)) |
## Special Thanks
Alan Agius, Andrew Scott, Besim Gürbüz, Brecht Billiet, Dario Piotrowicz, Dylan Hunn, Iván Navarro, Kristiyan Kostadinov, Matthieu Riegler, Onkar Ruikar, Payam Valadkhan, Santosh Yadav, Virginia Dooley and Walid Bouguima
<!-- CHANGELOG SPLIT MARKER -->
<a name="15.2.0-next.2"></a>
# 15.2.0-next.2 (2023-01-25)
### compiler
| Commit | Type | Description |
| -- | -- | -- |
| [bc8cfa2552](https://github.com/angular/angular/commit/bc8cfa25520c3b8b0a506c69a269e42a63f097d6) | fix | handle css selectors with space after an escaped character. ([#48558](https://github.com/angular/angular/pull/48558)) |
### compiler-cli
| Commit | Type | Description |
| -- | -- | -- |
| [4da1f2948c](https://github.com/angular/angular/commit/4da1f2948cc67b68527a91579ee14bb1a22b0c58) | fix | resolve deprecation warning ([#48812](https://github.com/angular/angular/pull/48812)) |
### core
| Commit | Type | Description |
| -- | -- | -- |
| [a154db8a81](https://github.com/angular/angular/commit/a154db8a81cbdfed8c3d0db1e2a5bf43aa3e0bbf) | feat | add ng generate schematic to convert declarations to standalone ([#48790](https://github.com/angular/angular/pull/48790)) |
| [e7318fc758](https://github.com/angular/angular/commit/e7318fc758d9e64d1a7f60a2c7071a769b73e7d8) | feat | add ng generate schematic to remove unnecessary modules ([#48832](https://github.com/angular/angular/pull/48832)) |
### router
| Commit | Type | Description |
| -- | -- | -- |
| [4dcab333ae](https://github.com/angular/angular/commit/4dcab333ae009f923cf3864e20ee47e43d32dfe6) | fix | 'createUrlTreeFromSnapshot' with empty paths and named outlets ([#48734](https://github.com/angular/angular/pull/48734)) |
## Special Thanks
Alan Agius, AleksanderBodurri, Andrew Kushnir, Andrew Scott, Charles Lyding, Dylan Hunn, Jessica Janiuk, JoostK, Kristiyan Kostadinov, Matthieu Riegler, Paul Gschwendtner, Payam Valadkhan, Virginia Dooley, Yann Thomas LE MOIGNE and dario-piotrowicz
<!-- CHANGELOG SPLIT MARKER -->
<a name="15.1.2"></a>
# 15.1.2 (2023-01-25)
### compiler
@@ -168,36 +282,6 @@ Alan Agius, AleksanderBodurri, Andrew Kushnir, Andrew Scott, Charles Lyding, Dyl
<!-- CHANGELOG SPLIT MARKER -->
<a name="15.2.0-next.1"></a>
# 15.2.0-next.1 (2023-01-18)
## Deprecations
###
- Class and `InjectionToken` guards and resolvers are
deprecated. Instead, write guards as plain JavaScript functions and
inject dependencies with `inject` from `@angular/core`.
###
| Commit | Type | Description |
| -- | -- | -- |
| [926c35f4ac](https://github.com/angular/angular/commit/926c35f4ac70f5e4d142e545d6d056dd67aac97b) | docs | Deprecate class and InjectionToken and resolvers ([#47924](https://github.com/angular/angular/pull/47924)) |
### common
| Commit | Type | Description |
| -- | -- | -- |
| [8802b4aab9](https://github.com/angular/angular/commit/8802b4aab9600870f3e09f198c993845587e9622) | fix | Update `Location` to get a normalized URL valid in case a represented URL starts with the substring equals `APP_BASE_HREF` ([#48489](https://github.com/angular/angular/pull/48489)) |
| [5f21c6d627](https://github.com/angular/angular/commit/5f21c6d627892dfad942b55f13861c213f9c0afb) | perf | avoid excessive DOM mutation in NgClass ([#48433](https://github.com/angular/angular/pull/48433)) |
### core
| Commit | Type | Description |
| -- | -- | -- |
| [f00bf71411](https://github.com/angular/angular/commit/f00bf714110100549111bd27345943ab8830128c) | fix | makeEnvironmentProviders should accept EnvironmentProviders ([#48720](https://github.com/angular/angular/pull/48720)) |
### language-service
| Commit | Type | Description |
| -- | -- | -- |
| [4ae384fd61](https://github.com/angular/angular/commit/4ae384fd619a13eaadf737d08a97f07e1f6b273c) | feat | Allow auto-imports of a pipe via quick fix when its selector is used, both directly and via reexports. ([#48354](https://github.com/angular/angular/pull/48354)) |
| [141333411e](https://github.com/angular/angular/commit/141333411e67769d752c7162e4cb03376022f5e1) | feat | Introduce a new NgModuleIndex, and use it to suggest re-exports. ([#48354](https://github.com/angular/angular/pull/48354)) |
## Special Thanks
Alex Rickabaugh, Andrew Kushnir, Andrew Scott, Aristeidis Bampakos, Bob Watson, Dylan Hunn, Jens, Konstantin Kharitonov, Kristiyan Kostadinov, Matthieu Riegler, Paul Gschwendtner, Pawel Kozlowski, Vladyslav Slipchenko, ced, dario-piotrowicz, mgechev and ノウラ
<!-- CHANGELOG SPLIT MARKER -->
<a name="15.1.1"></a>
# 15.1.1 (2023-01-18)
### common
@@ -214,17 +298,6 @@ Alan Agius, Alex Rickabaugh, Andrew Scott, Aristeidis Bampakos, Bob Watson, Jens
<!-- CHANGELOG SPLIT MARKER -->
<a name="15.2.0-next.0"></a>
# 15.2.0-next.0 (2023-01-11)
### router
| Commit | Type | Description |
| -- | -- | -- |
| [31b94c762f](https://github.com/angular/angular/commit/31b94c762fc91ab6cabe08ea6812780fdcf92a64) | feat | Add a withNavigationErrorHandler feature to provideRouter ([#48551](https://github.com/angular/angular/pull/48551)) |
## Special Thanks
Alan Agius, Alex Rickabaugh, Andrew Scott, Paul Gschwendtner and angular-robot[bot]
<!-- CHANGELOG SPLIT MARKER -->
<a name="15.1.0"></a>
# 15.1.0 (2023-01-10)
## Deprecations
+2 -2
View File
@@ -1,10 +1,10 @@
<h1 align="center">Angular - The modern web developer's platform.</h1>
<h1 align="center">Angular - The modern web developer's platform</h1>
<p align="center">
<img src="aio/src/assets/images/logos/angular/angular.png" alt="angular-logo" width="120px" height="120px"/>
<br>
<i>Angular is a development platform for building mobile and desktop web applications
<br> using Typescript/JavaScript and other languages.</i>
<br> using TypeScript/JavaScript and other languages.</i>
<br>
</p>
+6 -8
View File
@@ -26,12 +26,10 @@ http_archive(
http_archive(
name = "build_bazel_rules_nodejs",
patches = [
# TODO(devversion): remove when https://github.com/bazelbuild/rules_nodejs/pull/3605 is available.
"//tools:bazel-repo-patches/rules_nodejs__#3605.patch",
"//tools/esm-interop:patches/bazel/nodejs_binary_esm_support.patch",
],
sha256 = "c29944ba9b0b430aadcaf3bf2570fece6fc5ebfb76df145c6cdad40d65c20811",
urls = ["https://github.com/bazelbuild/rules_nodejs/releases/download/5.7.0/rules_nodejs-5.7.0.tar.gz"],
sha256 = "94070eff79305be05b7699207fbac5d2608054dd53e6109f7d00d923919ff45a",
urls = ["https://github.com/bazelbuild/rules_nodejs/releases/download/5.8.2/rules_nodejs-5.8.2.tar.gz"],
)
load("@build_bazel_rules_nodejs//:repositories.bzl", "build_bazel_rules_nodejs_dependencies")
@@ -62,7 +60,7 @@ load("@rules_nodejs//nodejs:repositories.bzl", "nodejs_register_toolchains")
nodejs_register_toolchains(
name = "nodejs",
node_version = "16.13.0",
node_version = "16.14.0",
)
# Download npm dependencies.
@@ -192,10 +190,10 @@ cldr_xml_data_repository(
# sass rules
http_archive(
name = "io_bazel_rules_sass",
sha256 = "38442f09a6f6f4e932e86ed29b86d5026b41d9ebbe9d017fe8a5684e1826b821",
strip_prefix = "rules_sass-b603e6f0daf73d5aa9dca768b45dde30e5b288bc",
sha256 = "de516110be32fcce328cb93ec4bf06f7a6e978e60bfd9d628fb5571c4a0afade",
strip_prefix = "rules_sass-898e4dd048584152bfbd77abd9ed0c3fe28c86ac",
urls = [
"https://github.com/bazelbuild/rules_sass/archive/b603e6f0daf73d5aa9dca768b45dde30e5b288bc.zip",
"https://github.com/bazelbuild/rules_sass/archive/898e4dd048584152bfbd77abd9ed0c3fe28c86ac.zip",
],
)
+11 -11
View File
@@ -3,12 +3,12 @@
"version": "0.0.0",
"private": true,
"dependencies": {
"@angular/animations": "15.1.0-next.2",
"@angular/common": "15.1.0-next.2",
"@angular/compiler": "15.1.0-next.2",
"@angular/core": "15.1.0-next.2",
"@angular/platform-browser": "15.1.0-next.2",
"@angular/platform-browser-dynamic": "15.1.0-next.2",
"@angular/animations": "~15.2.0",
"@angular/common": "~15.2.0",
"@angular/compiler": "~15.2.0",
"@angular/core": "~15.2.0",
"@angular/platform-browser": "~15.2.0",
"@angular/platform-browser-dynamic": "~15.2.0",
"rxjs": "^7.5.2",
"tslib": "^2.3.1",
"zone.js": "^0.12.0"
@@ -22,9 +22,9 @@
"e2e": "ng e2e"
},
"devDependencies": {
"@angular-devkit/build-angular": "~15.0.1",
"@angular/cli": "~15.0.1",
"@angular/compiler-cli": "~15.0.1",
"@angular-devkit/build-angular": "~15.2.0",
"@angular/cli": "~15.2.0",
"@angular/compiler-cli": "~15.2.0",
"@types/jasmine": "~4.3.0",
"@types/node": "^12.11.1",
"codelyzer": "^6.0.0",
@@ -38,6 +38,6 @@
"protractor": "~7.0.0",
"ts-node": "~10.9.0",
"tslint": "~6.1.0",
"typescript": "~4.8.4"
"typescript": "~4.9.3"
}
}
}
File diff suppressed because it is too large Load Diff
@@ -6,24 +6,22 @@ import { Component, OnDestroy } from '@angular/core';
template: '<p>{{message}}</p>'
})
export class CountdownTimerComponent implements OnDestroy {
intervalId = 0;
message = '';
seconds = 11;
ngOnDestroy() { this.clearTimer(); }
ngOnDestroy() { this.clearTimer?.(); }
start() { this.countDown(); }
stop() {
this.clearTimer();
this.clearTimer?.();
this.message = `Holding at T-${this.seconds} seconds`;
}
private clearTimer() { clearInterval(this.intervalId); }
private clearTimer: VoidFunction | undefined;
private countDown() {
this.clearTimer();
this.intervalId = window.setInterval(() => {
this.clearTimer?.();
const interval = setInterval(() => {
this.seconds -= 1;
if (this.seconds === 0) {
this.message = 'Blast off!';
@@ -32,5 +30,6 @@ export class CountdownTimerComponent implements OnDestroy {
this.message = `T-${this.seconds} seconds and counting`;
}
}, 1000);
this.clearTimer = () => clearInterval(interval);
}
}
@@ -23,7 +23,8 @@ export class AdBannerComponent implements OnInit, OnDestroy {
currentAdIndex = -1;
@ViewChild(AdDirective, {static: true}) adHost!: AdDirective;
interval: number|undefined;
private clearTimer: VoidFunction | undefined;
ngOnInit(): void {
this.loadComponent();
@@ -31,7 +32,7 @@ export class AdBannerComponent implements OnInit, OnDestroy {
}
ngOnDestroy() {
clearInterval(this.interval);
this.clearTimer?.();
}
loadComponent() {
@@ -46,9 +47,10 @@ export class AdBannerComponent implements OnInit, OnDestroy {
}
getAds() {
this.interval = setInterval(() => {
const interval = setInterval(() => {
this.loadComponent();
}, 3000);
this.clearTimer = () => clearInterval(interval);
}
}
// #enddocregion class
@@ -1,14 +1,13 @@
import { ApplicationRef, ComponentFactoryResolver, Injectable, Injector } from '@angular/core';
import { ApplicationRef, createComponent, EnvironmentInjector, Injectable } from '@angular/core';
import { NgElement, WithProperties } from '@angular/elements';
import { PopupComponent } from './popup.component';
@Injectable()
export class PopupService {
constructor(private injector: Injector,
private applicationRef: ApplicationRef,
private componentFactoryResolver: ComponentFactoryResolver) {}
constructor(private injector: EnvironmentInjector,
private applicationRef: ApplicationRef) {}
// Previous dynamic-loading method required you to set up infrastructure
// before adding the popup to the DOM.
@@ -17,8 +16,7 @@ export class PopupService {
const popup = document.createElement('popup-component');
// Create the component and wire it up with the element
const factory = this.componentFactoryResolver.resolveComponentFactory(PopupComponent);
const popupComponentRef = factory.create(this.injector, [], popup);
const popupComponentRef = createComponent(PopupComponent, {environmentInjector: this.injector, hostElement: popup});
// Attach to the view so that the change detector knows to run
this.applicationRef.attachView(popupComponentRef.hostView);
@@ -1,6 +1,6 @@
{
"tests": [
{"cmd": "yarn", "args": ["test", "--browsers=ChromeHeadless", "--no-watch"]},
{"cmd": "yarn", "args": ["test", "--browsers=ChromeHeadlessNoSandbox", "--no-watch"]},
{"cmd": "yarn", "args": ["e2e", "--configuration=production", "--protractor-config=e2e/protractor-bazel.conf.js", "--no-webdriver-update", "--port=0"]}
]
}
@@ -1,7 +1,7 @@
{
"projectType": "testing",
"tests": [
{"cmd": "yarn", "args": ["test", "--browsers=ChromeHeadless", "--no-watch"]},
{"cmd": "yarn", "args": ["test", "--browsers=ChromeHeadlessNoSandbox", "--no-watch"]},
{"cmd": "yarn", "args": ["e2e", "--configuration=production", "--protractor-config=e2e/protractor-bazel.conf.js", "--no-webdriver-update", "--port=0"]}
]
}
@@ -6,12 +6,12 @@ export function docRegionDelaySequence(console: Console) {
// #docregion delay_sequence
function sequenceSubscriber(observer: Observer<number>) {
const seq = [1, 2, 3];
let timeoutId: any;
let clearTimer: VoidFunction | undefined;
// Will run through an array of numbers, emitting one value
// per second until it gets to the end of the array.
function doInSequence(arr: number[], idx: number) {
timeoutId = setTimeout(() => {
const timeout = setTimeout(() => {
observer.next(arr[idx]);
if (idx === arr.length - 1) {
observer.complete();
@@ -19,6 +19,7 @@ export function docRegionDelaySequence(console: Console) {
doInSequence(arr, ++idx);
}
}, 1000);
clearTimer = () => clearTimeout(timeout);
}
doInSequence(seq, 0);
@@ -26,7 +27,7 @@ export function docRegionDelaySequence(console: Console) {
// Unsubscribe should clear the timeout to stop execution
return {
unsubscribe() {
clearTimeout(timeoutId);
clearTimer?.();
}
};
}
@@ -85,9 +86,9 @@ export function docRegionMulticastSequence(console: Console, runSequence: boolea
const seq = [1, 2, 3];
// Keep track of each observer (one for every active subscription)
const observers: Observer<unknown>[] = [];
// Still a single timeoutId because there will only ever be one
// Still a single timer because there will only ever be one
// set of values being generated, multicasted to each subscriber
let timeoutId: any;
let clearTimer: VoidFunction | undefined;
// Return the subscriber function (runs when subscribe()
// function is invoked)
@@ -115,7 +116,7 @@ export function docRegionMulticastSequence(console: Console, runSequence: boolea
observers.splice(observers.indexOf(observer), 1);
// If there's no more listeners, do cleanup
if (observers.length === 0) {
clearTimeout(timeoutId);
clearTimer?.();
}
}
};
@@ -123,7 +124,7 @@ export function docRegionMulticastSequence(console: Console, runSequence: boolea
// Run through an array of numbers, emitting one value
// per second until it gets to the end of the array.
function doSequence(sequenceObserver: Observer<number>, arr: number[], idx: number) {
timeoutId = setTimeout(() => {
const timeout = setTimeout(() => {
console.log('Emitting ' + arr[idx]);
sequenceObserver.next(arr[idx]);
if (idx === arr.length - 1) {
@@ -132,6 +133,7 @@ export function docRegionMulticastSequence(console: Console, runSequence: boolea
doSequence(sequenceObserver, arr, ++idx);
}
}, 1000);
clearTimer = () => clearTimeout(timeout);
}
};
}
@@ -1,20 +1,15 @@
// #docplaster
// #docregion
import { of, pipe, range, throwError, timer, zip } from 'rxjs';
import { timer } from 'rxjs';
import { ajax } from 'rxjs/ajax';
import { map, mergeMap, retryWhen } from 'rxjs/operators';
import { retry } from 'rxjs/operators';
export function backoff(maxTries: number, delay: number) {
return pipe(
retryWhen(attempts =>
zip(range(1, maxTries + 1), attempts).pipe(
mergeMap(([i, err]) => (i > maxTries) ? throwError(err) : of(i)),
map(i => i * i),
mergeMap(v => timer(v * delay)),
),
),
);
}
export function backoff(maxTries: number, initialDelay: number) {
return retry({
count: maxTries,
delay: (error, retryCount) => timer(initialDelay * retryCount ** 2),
});
}
// #enddocregion
/*
@@ -1,5 +1,3 @@
/// <reference types="node" />
import { of } from 'rxjs';
import { docRegionTypeahead } from './typeahead';
@@ -71,7 +69,7 @@ describe('typeahead', () => {
// Helpers
interface MockTask {
id: NodeJS.Timeout;
id: ReturnType<typeof setTimeout>;
fn: () => unknown;
delay: number;
recurring: boolean;
@@ -86,12 +84,12 @@ describe('typeahead', () => {
static install(mockTime = 0): MockClock['tick'] {
const mocked = new this(mockTime);
spyOn(global, 'clearInterval').and.callFake(id => mocked.clearTask(id as MockTask['id']));
spyOn(global, 'clearTimeout').and.callFake(id => mocked.clearTask(id as MockTask['id']));
spyOn(global, 'setInterval').and.callFake(
spyOn(globalThis, 'clearInterval').and.callFake(id => mocked.clearTask(id as MockTask['id']));
spyOn(globalThis, 'clearTimeout').and.callFake(id => mocked.clearTask(id as MockTask['id']));
spyOn(globalThis, 'setInterval').and.callFake(
((fn: () => unknown, delay: number, ...args: any[]) =>
mocked.createTask(fn, delay, true, ...args)) as typeof setInterval);
spyOn(global, 'setTimeout').and.callFake(
spyOn(globalThis, 'setTimeout').and.callFake(
((fn: () => unknown, delay: number, ...args: any[]) =>
mocked.createTask(fn, delay, false, ...args)) as typeof setTimeout);
@@ -1,6 +1,6 @@
{
"tests": [
{"cmd": "yarn", "args": ["test", "--browsers=ChromeHeadless", "--no-watch"]},
{"cmd": "yarn", "args": ["test", "--browsers=ChromeHeadlessNoSandbox", "--no-watch"]},
{"cmd": "yarn", "args": ["e2e", "--configuration=production", "--protractor-config=e2e/protractor-bazel.conf.js", "--no-webdriver-update", "--port=0"]}
]
}
@@ -20,7 +20,7 @@ export class ToastComponent implements OnInit {
// private methods
private hide() {
this.toastElement.style.opacity = 0;
window.setTimeout(() => this.toastElement.style.zIndex = 0, 400);
setTimeout(() => this.toastElement.style.zIndex = 0, 400);
}
activate(message = this.defaults.message, title = this.defaults.title) {
@@ -34,7 +34,7 @@ export class ToastComponent implements OnInit {
this.toastElement.style.opacity = 1;
this.toastElement.style.zIndex = 9999;
window.setTimeout(() => this.hide(), 2500);
setTimeout(() => this.hide(), 2500);
}
}
// #enddocregion example
@@ -32,14 +32,14 @@ export class ToastComponent implements OnInit {
// private methods
private hide() {
this.toastElement.style.opacity = 0;
window.setTimeout(() => this.toastElement.style.zIndex = 0, 400);
setTimeout(() => this.toastElement.style.zIndex = 0, 400);
}
private show() {
console.log(this.message);
this.toastElement.style.opacity = 1;
this.toastElement.style.zIndex = 9999;
window.setTimeout(() => this.hide(), 2500);
setTimeout(() => this.hide(), 2500);
}
}
// #enddocregion example
@@ -1,7 +1,7 @@
{
"projectType": "testing",
"tests": [
{"cmd": "yarn", "args": ["test", "--browsers=ChromeHeadless", "--no-watch"]},
{"cmd": "yarn", "args": ["test", "--browsers=ChromeHeadlessNoSandbox", "--no-watch"]},
{"cmd": "yarn", "args": ["e2e", "--configuration=production", "--protractor-config=e2e/protractor-bazel.conf.js", "--no-webdriver-update", "--port=0"]}
]
}
@@ -1,11 +1,10 @@
// #docplaster
import { Component, DebugElement, NO_ERRORS_SCHEMA } from '@angular/core';
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import {Component, DebugElement, NO_ERRORS_SCHEMA} from '@angular/core';
import {ComponentFixture, fakeAsync, TestBed, tick, waitForAsync} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {provideRouter, Router, RouterLink} from '@angular/router';
import { RouterLinkDirectiveStub } from '../testing';
import { AppComponent } from './app.component';
import {AppComponent} from './app.component';
// #docregion component-stubs
@Component({selector: 'app-banner', template: ''})
@@ -29,10 +28,10 @@ describe('AppComponent & TestModule', () => {
// #docregion testbed-stubs
TestBed
.configureTestingModule({
declarations: [
AppComponent, RouterLinkDirectiveStub, BannerStubComponent, RouterOutletStubComponent,
WelcomeStubComponent
]
imports: [RouterLink],
providers: [provideRouter([])],
declarations:
[AppComponent, BannerStubComponent, RouterOutletStubComponent, WelcomeStubComponent]
})
// #enddocregion testbed-stubs
.compileComponents()
@@ -55,8 +54,9 @@ describe('AppComponent & NO_ERRORS_SCHEMA', () => {
// #enddocregion no-errors-schema
BannerStubComponent,
// #docregion no-errors-schema
RouterLinkDirectiveStub
],
providers: [provideRouter([])],
imports: [RouterLink],
schemas: [NO_ERRORS_SCHEMA]
})
// #enddocregion no-errors-schema, mixed-setup
@@ -70,21 +70,25 @@ describe('AppComponent & NO_ERRORS_SCHEMA', () => {
});
//////// Testing w/ real root module //////
// Tricky because we are disabling the router and its configuration
// Better to use RouterTestingModule
import { AppModule } from './app.module';
import { AppRoutingModule } from './app-routing.module';
import {AppModule} from './app.module';
import {AppRoutingModule} from './app-routing.module';
describe('AppComponent & AppModule', () => {
beforeEach(waitForAsync(() => {
TestBed
.configureTestingModule({imports: [AppModule]})
.configureTestingModule({
imports: [AppModule],
})
// Get rid of app's Router configuration otherwise many failures.
// Doing so removes Router declarations; add the Router stubs
.overrideModule(AppModule, {
remove: {imports: [AppRoutingModule]},
add: {declarations: [RouterLinkDirectiveStub, RouterOutletStubComponent]}
add: {
declarations: [RouterOutletStubComponent],
imports: [RouterLink],
providers: [provideRouter([])],
}
})
.compileComponents()
@@ -99,7 +103,7 @@ describe('AppComponent & AppModule', () => {
});
function tests() {
let routerLinks: RouterLinkDirectiveStub[];
let routerLinks: RouterLink[];
let linkDes: DebugElement[];
// #docregion test-setup
@@ -107,11 +111,11 @@ function tests() {
fixture.detectChanges(); // trigger initial data binding
// find DebugElements with an attached RouterLinkStubDirective
linkDes = fixture.debugElement.queryAll(By.directive(RouterLinkDirectiveStub));
linkDes = fixture.debugElement.queryAll(By.directive(RouterLink));
// get attached link directive instances
// using each DebugElement's injector
routerLinks = linkDes.map(de => de.injector.get(RouterLinkDirectiveStub));
routerLinks = linkDes.map(de => de.injector.get(RouterLink));
});
// #enddocregion test-setup
@@ -121,26 +125,21 @@ function tests() {
// #docregion tests
it('can get RouterLinks from template', () => {
expect(routerLinks.length)
.withContext('should have 3 routerLinks')
.toBe(3);
expect(routerLinks[0].linkParams).toBe('/dashboard');
expect(routerLinks[1].linkParams).toBe('/heroes');
expect(routerLinks[2].linkParams).toBe('/about');
expect(routerLinks.length).withContext('should have 3 routerLinks').toBe(3);
expect(routerLinks[0].href).toBe('/dashboard');
expect(routerLinks[1].href).toBe('/heroes');
expect(routerLinks[2].href).toBe('/about');
});
it('can click Heroes link in template', () => {
const heroesLinkDe = linkDes[1]; // heroes link DebugElement
const heroesLink = routerLinks[1]; // heroes link directive
it('can click Heroes link in template', fakeAsync(() => {
const heroesLinkDe = linkDes[1]; // heroes link DebugElement
expect(heroesLink.navigatedTo)
.withContext('should not have navigated yet')
.toBeNull();
TestBed.inject(Router).resetConfig([{path: '**', children: []}]);
heroesLinkDe.triggerEventHandler('click', {button: 0});
tick();
fixture.detectChanges();
heroesLinkDe.triggerEventHandler('click');
fixture.detectChanges();
expect(heroesLink.navigatedTo).toBe('/heroes');
});
expect(TestBed.inject(Router).url).toBe('/heroes');
}));
// #enddocregion tests
}
@@ -1,20 +1,24 @@
// #docplaster
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import {provideHttpClient} from '@angular/common/http';
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing';
import {NO_ERRORS_SCHEMA} from '@angular/core';
import {TestBed, waitForAsync} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {NavigationEnd, provideRouter, Router} from '@angular/router';
import {RouterTestingHarness} from '@angular/router/testing';
import {firstValueFrom} from 'rxjs';
import {filter} from 'rxjs/operators';
import { addMatchers, asyncData, click } from '../../testing';
import { HeroService } from '../model/hero.service';
import { getTestHeroes } from '../model/testing/test-heroes';
import {addMatchers, click} from '../../testing';
import {HeroService} from '../model/hero.service';
import {getTestHeroes} from '../model/testing/test-heroes';
import { By } from '@angular/platform-browser';
import { Router } from '@angular/router';
import { DashboardComponent } from './dashboard.component';
import { DashboardModule } from './dashboard.module';
import {DashboardComponent} from './dashboard.component';
import {DashboardModule} from './dashboard.module';
beforeEach(addMatchers);
let comp: DashboardComponent;
let fixture: ComponentFixture<DashboardComponent>;
let harness: RouterTestingHarness;
//////// Deep ////////////////
@@ -29,15 +33,15 @@ describe('DashboardComponent (deep)', () => {
function clickForDeep() {
// get first <div class="hero">
const heroEl: HTMLElement = fixture.nativeElement.querySelector('.hero');
const heroEl: HTMLElement = harness.routeNativeElement!.querySelector('.hero')!;
click(heroEl);
return firstValueFrom(
TestBed.inject(Router).events.pipe(filter(e => e instanceof NavigationEnd)));
}
});
//////// Shallow ////////////////
import { NO_ERRORS_SCHEMA } from '@angular/core';
describe('DashboardComponent (shallow)', () => {
beforeEach(() => {
TestBed.configureTestingModule(
@@ -50,33 +54,32 @@ describe('DashboardComponent (shallow)', () => {
function clickForShallow() {
// get first <dashboard-hero> DebugElement
const heroDe = fixture.debugElement.query(By.css('dashboard-hero'));
const heroDe = harness.routeDebugElement!.query(By.css('dashboard-hero'));
heroDe.triggerEventHandler('selected', comp.heroes[0]);
return Promise.resolve();
}
});
/** Add TestBed providers, compile, and create DashboardComponent */
function compileAndCreate() {
beforeEach(waitForAsync(() => {
// #docregion router-spy
const routerSpy = jasmine.createSpyObj('Router', ['navigateByUrl']);
const heroServiceSpy = jasmine.createSpyObj('HeroService', ['getHeroes']);
// #docregion router-harness
TestBed
.configureTestingModule({
providers: [
{provide: HeroService, useValue: heroServiceSpy}, {provide: Router, useValue: routerSpy}
provideRouter([{path: '**', component: DashboardComponent}]),
provideHttpClient(),
provideHttpClientTesting(),
HeroService,
]
})
// #enddocregion router-spy
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(DashboardComponent);
comp = fixture.componentInstance;
// getHeroes spy returns observable of test heroes
heroServiceSpy.getHeroes.and.returnValue(asyncData(getTestHeroes()));
.then(async () => {
harness = await RouterTestingHarness.create();
comp = await harness.navigateByUrl('/', DashboardComponent);
TestBed.inject(HttpTestingController).expectOne('api/heroes').flush(getTestHeroes());
});
// #enddocregion router-harness
}));
}
@@ -84,61 +87,38 @@ function compileAndCreate() {
* The (almost) same tests for both.
* Only change: the way that the first hero is clicked
*/
function tests(heroClick: () => void) {
it('should NOT have heroes before ngOnInit', () => {
expect(comp.heroes.length)
.withContext('should not have heroes before ngOnInit')
.toBe(0);
});
it('should NOT have heroes immediately after ngOnInit', () => {
fixture.detectChanges(); // runs initial lifecycle hooks
expect(comp.heroes.length)
.withContext('should not have heroes until service promise resolves')
.toBe(0);
});
function tests(heroClick: () => Promise<unknown>) {
describe('after get dashboard heroes', () => {
let router: Router;
// Trigger component so it gets heroes and binds to them
// Trigger component so it gets heroes and binds to them
beforeEach(waitForAsync(() => {
router = fixture.debugElement.injector.get(Router);
fixture.detectChanges(); // runs ngOnInit -> getHeroes
fixture.whenStable() // No need for the `lastPromise` hack!
.then(() => fixture.detectChanges()); // bind to heroes
router = TestBed.inject(Router);
harness.detectChanges(); // runs ngOnInit -> getHeroes
}));
it('should HAVE heroes', () => {
expect(comp.heroes.length)
.withContext('should have heroes after service promise resolves')
.toBeGreaterThan(0);
.withContext('should have heroes after service promise resolves')
.toBeGreaterThan(0);
});
it('should DISPLAY heroes', () => {
// Find and examine the displayed heroes
// Look for them in the DOM by css class
const heroes = fixture.nativeElement.querySelectorAll('dashboard-hero');
expect(heroes.length)
.withContext('should display 4 heroes')
.toBe(4);
const heroes = harness.routeNativeElement!.querySelectorAll('dashboard-hero');
expect(heroes.length).withContext('should display 4 heroes').toBe(4);
});
// #docregion navigate-test
it('should tell ROUTER to navigate when hero clicked', () => {
heroClick(); // trigger click on first inner <div class="hero">
// args passed to router.navigateByUrl() spy
const spy = router.navigateByUrl as jasmine.Spy;
const navArgs = spy.calls.first().args[0];
it('should tell navigate when hero clicked', async () => {
await heroClick(); // trigger click on first inner <div class="hero">
// expecting to navigate to id of the component's first hero
const id = comp.heroes[0].id;
expect(navArgs)
.withContext('should nav to HeroDetail for first hero')
.toBe('/heroes/' + id);
expect(TestBed.inject(Router).url)
.withContext('should nav to HeroDetail for first hero')
.toEqual(`/heroes/${id}`);
});
// #enddocregion navigate-test
});
@@ -1,29 +1,24 @@
// #docregion
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import { Hero } from '../model/hero';
import { HeroService } from '../model/hero.service';
import {Hero} from '../model/hero';
import {HeroService} from '../model/hero.service';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: [ './dashboard.component.css' ]
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
heroes: Hero[] = [];
// #docregion ctor
constructor(
private router: Router,
private heroService: HeroService) {
}
constructor(private router: Router, private heroService: HeroService) {}
// #enddocregion ctor
ngOnInit() {
this.heroService.getHeroes()
.subscribe(heroes => this.heroes = heroes.slice(1, 5));
this.heroService.getHeroes().subscribe(heroes => this.heroes = heroes.slice(1, 5));
}
// #docregion goto-detail
@@ -35,7 +30,6 @@ export class DashboardComponent implements OnInit {
get title() {
const cnt = this.heroes.length;
return cnt === 0 ? 'No Heroes' :
cnt === 1 ? 'Top Hero' : `Top ${cnt} Heroes`;
return cnt === 0 ? 'No Heroes' : cnt === 1 ? 'Top Hero' : `Top ${cnt} Heroes`;
}
}
@@ -1,66 +0,0 @@
import { Router } from '@angular/router';
import { asyncData, ActivatedRouteStub } from '../../testing';
import { HeroDetailComponent } from './hero-detail.component';
import { HeroDetailService } from './hero-detail.service';
import { Hero } from '../model/hero';
////////// Tests ////////////////////
describe('HeroDetailComponent - no TestBed', () => {
let comp: HeroDetailComponent;
let expectedHero: Hero;
let hds: jasmine.SpyObj<HeroDetailService>;
let router: jasmine.SpyObj<Router>;
beforeEach((done: DoneFn) => {
expectedHero = { id: 42, name: 'Bubba' };
const activatedRoute = new ActivatedRouteStub({ id: expectedHero.id });
router = jasmine.createSpyObj('Router', ['navigate']);
hds = jasmine.createSpyObj('HeroDetailService', ['getHero', 'saveHero']);
hds.getHero.and.returnValue(asyncData(expectedHero));
hds.saveHero.and.returnValue(asyncData(expectedHero));
comp = new HeroDetailComponent(hds, activatedRoute as any, router);
comp.ngOnInit();
// OnInit calls HDS.getHero; wait for it to get the fake hero
hds.getHero.calls.first().returnValue.subscribe(() => done());
});
it('should expose the hero retrieved from the service', () => {
expect(comp.hero).toBe(expectedHero);
});
it('should navigate when click cancel', () => {
comp.cancel();
expect(router.navigate.calls.any())
.withContext('router.navigate called')
.toBe(true);
});
it('should save when click save', () => {
comp.save();
expect(hds.saveHero.calls.any())
.withContext('HeroDetailService.save called')
.toBe(true);
expect(router.navigate.calls.any())
.withContext('router.navigate not called yet')
.toBe(false);
});
it('should navigate when click save resolves', (done: DoneFn) => {
comp.save();
// waits for async save to complete before navigating
hds.saveHero.calls.first().returnValue
.subscribe(() => {
expect(router.navigate.calls.any())
.withContext('router.navigate called')
.toBe(true);
done();
});
});
});
@@ -1,27 +1,26 @@
// #docplaster
import { ComponentFixture, fakeAsync, inject, TestBed, tick, waitForAsync } from '@angular/core/testing';
import { Router } from '@angular/router';
import {provideHttpClient} from '@angular/common/http';
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing';
import {fakeAsync, TestBed, tick} from '@angular/core/testing';
import {provideRouter, Router} from '@angular/router';
import {RouterTestingHarness} from '@angular/router/testing';
import {
ActivatedRoute, ActivatedRouteStub, asyncData, click
} from '../../testing';
import {asyncData, click} from '../../testing';
import {Hero} from '../model/hero';
import {SharedModule} from '../shared/shared.module';
import { Hero } from '../model/hero';
import { HeroDetailComponent } from './hero-detail.component';
import { HeroDetailService } from './hero-detail.service';
import { HeroModule } from './hero.module';
import {HeroDetailComponent} from './hero-detail.component';
import {HeroDetailService} from './hero-detail.service';
import {HeroListComponent} from './hero-list.component';
import {HeroModule} from './hero.module';
////// Testing Vars //////
let activatedRoute: ActivatedRouteStub;
let component: HeroDetailComponent;
let fixture: ComponentFixture<HeroDetailComponent>;
let harness: RouterTestingHarness;
let page: Page;
////// Tests //////
describe('HeroDetailComponent', () => {
beforeEach(() => {
activatedRoute = new ActivatedRouteStub();
});
describe('with HeroModule setup', heroModuleSetup);
describe('when override its provided HeroDetailService', overrideSetup);
describe('with FormsModule setup', formsModuleSetup);
@@ -30,10 +29,11 @@ describe('HeroDetailComponent', () => {
///////////////////
const testHero = getTestHeroes()[0];
function overrideSetup() {
// #docregion hds-spy
class HeroDetailServiceSpy {
testHero: Hero = {id: 42, name: 'Test Hero'};
testHero: Hero = {...testHero};
/* emit cloned test hero */
getHero = jasmine.createSpy('getHero').and.callFake(
@@ -46,33 +46,22 @@ function overrideSetup() {
// #enddocregion hds-spy
// the `id` value is irrelevant because ignored by service stub
beforeEach(() => activatedRoute.setParamMap({id: 99999}));
// #docregion setup-override
beforeEach(async () => {
const routerSpy = createRouterSpy();
await TestBed
.configureTestingModule({
imports: [HeroModule],
providers: [
{provide: ActivatedRoute, useValue: activatedRoute},
{provide: Router, useValue: routerSpy},
// #enddocregion setup-override
provideRouter([{path: 'heroes/:id', component: HeroDetailComponent}]),
// HeroDetailService at this level is IRRELEVANT!
{provide: HeroDetailService, useValue: {}}
// #docregion setup-override
]
})
// Override component's own provider
// #docregion override-component-method
.overrideComponent(
HeroDetailComponent,
{set: {providers: [{provide: HeroDetailService, useClass: HeroDetailServiceSpy}]}})
// #enddocregion override-component-method
.compileComponents();
});
// #enddocregion setup-override
@@ -81,18 +70,22 @@ function overrideSetup() {
let hdsSpy: HeroDetailServiceSpy;
beforeEach(async () => {
await createComponent();
harness = await RouterTestingHarness.create();
component = await harness.navigateByUrl(`/heroes/${testHero.id}`, HeroDetailComponent);
page = new Page();
// get the component's injected HeroDetailServiceSpy
hdsSpy = fixture.debugElement.injector.get(HeroDetailService) as any;
hdsSpy = harness.routeDebugElement!.injector.get(HeroDetailService) as any;
harness.detectChanges();
});
it('should have called `getHero`', () => {
expect(hdsSpy.getHero.calls.count())
.withContext('getHero called once')
.toBe(1, 'getHero called once');
.withContext('getHero called once')
.toBe(1, 'getHero called once');
});
it("should display stub hero's name", () => {
it('should display stub hero\'s name', () => {
expect(page.nameDisplay.textContent).toBe(hdsSpy.testHero.name);
});
@@ -102,62 +95,43 @@ function overrideSetup() {
page.nameInput.value = newName;
page.nameInput.dispatchEvent(new Event('input')); // tell Angular
page.nameInput.dispatchEvent(new Event('input')); // tell Angular
expect(component.hero.name)
.withContext('component hero has new name')
.toBe(newName);
expect(component.hero.name).withContext('component hero has new name').toBe(newName);
expect(hdsSpy.testHero.name)
.withContext('service hero unchanged before save')
.toBe(origName);
.withContext('service hero unchanged before save')
.toBe(origName);
click(page.saveBtn);
expect(hdsSpy.saveHero.calls.count())
.withContext('saveHero called once')
.toBe(1);
expect(hdsSpy.saveHero.calls.count()).withContext('saveHero called once').toBe(1);
tick(); // wait for async save to complete
expect(hdsSpy.testHero.name)
.withContext('service hero has new name after save')
.toBe(newName);
expect(page.navigateSpy.calls.any())
.withContext('router.navigate called')
.toBe(true);
}));
// #enddocregion override-tests
it('fixture injected service is not the component injected service',
// inject gets the service from the fixture
inject([HeroDetailService], (fixtureService: HeroDetailService) => {
// use `fixture.debugElement.injector` to get service from component
const componentService = fixture.debugElement.injector.get(HeroDetailService);
expect(fixtureService)
.withContext('service injected from fixture')
.not.toBe(componentService);
.withContext('service hero has new name after save')
.toBe(newName);
expect(TestBed.inject(Router).url).toEqual('/heroes');
}));
}
////////////////////
import { getTestHeroes, TestHeroService, HeroService } from '../model/testing/test-hero.service';
import {getTestHeroes} from '../model/testing/test-hero.service';
const firstHero = getTestHeroes()[0];
function heroModuleSetup() {
// #docregion setup-hero-module
beforeEach(async () => {
const routerSpy = createRouterSpy();
await TestBed
.configureTestingModule({
imports: [HeroModule],
// #enddocregion setup-hero-module
// declarations: [ HeroDetailComponent ], // NO! DOUBLE DECLARATION
// #docregion setup-hero-module
providers: [
{provide: ActivatedRoute, useValue: activatedRoute},
{provide: HeroService, useClass: TestHeroService},
{provide: Router, useValue: routerSpy},
provideRouter([
{path: 'heroes/:id', component: HeroDetailComponent},
{path: 'heroes', component: HeroListComponent},
]),
provideHttpClient(),
provideHttpClientTesting(),
]
})
.compileComponents();
@@ -170,50 +144,35 @@ function heroModuleSetup() {
beforeEach(async () => {
expectedHero = firstHero;
activatedRoute.setParamMap({id: expectedHero.id});
await createComponent();
await createComponent(expectedHero.id);
});
// #docregion selected-tests
it("should display that hero's name", () => {
it('should display that hero\'s name', () => {
expect(page.nameDisplay.textContent).toBe(expectedHero.name);
});
// #enddocregion route-good-id
it('should navigate when click cancel', () => {
click(page.cancelBtn);
expect(page.navigateSpy.calls.any())
.withContext('router.navigate called')
.toBe(true);
expect(TestBed.inject(Router).url).toEqual(`/heroes/${expectedHero.id}`);
});
it('should save when click save but not navigate immediately', () => {
// Get service injected into component and spy on its`saveHero` method.
// It delegates to fake `HeroService.updateHero` which delivers a safe test result.
const hds = fixture.debugElement.injector.get(HeroDetailService);
const saveSpy = spyOn(hds, 'saveHero').and.callThrough();
click(page.saveBtn);
expect(saveSpy.calls.any())
.withContext('HeroDetailService.save called')
.toBe(true);
expect(page.navigateSpy.calls.any())
.withContext('router.navigate not called')
.toBe(false);
expect(TestBed.inject(HttpTestingController).expectOne({method: 'PUT', url: 'api/heroes'}));
expect(TestBed.inject(Router).url).toEqual('/heroes/41');
});
it('should navigate when click save and save resolves', fakeAsync(() => {
click(page.saveBtn);
tick(); // wait for async save to complete
expect(page.navigateSpy.calls.any())
.withContext('router.navigate called')
.toBe(true);
expect(TestBed.inject(Router).url).toEqual('/heroes/41');
}));
// #docregion title-case-pipe
it('should convert hero name to Title Case', () => {
// get the name's input and display elements from the DOM
const hostElement: HTMLElement = fixture.nativeElement;
const hostElement: HTMLElement = harness.routeNativeElement!;
const nameInput: HTMLInputElement = hostElement.querySelector('input')!;
const nameDisplay: HTMLElement = hostElement.querySelector('span')!;
@@ -224,146 +183,97 @@ function heroModuleSetup() {
nameInput.dispatchEvent(new Event('input'));
// Tell Angular to update the display binding through the title pipe
fixture.detectChanges();
harness.detectChanges();
expect(nameDisplay.textContent).toBe('Quick Brown Fox');
});
// #enddocregion title-case-pipe
// #enddocregion selected-tests
// #docregion route-good-id
// #enddocregion title-case-pipe
});
// #enddocregion route-good-id
// #docregion route-no-id
describe('when navigate with no hero id', () => {
beforeEach(async () => {
await createComponent();
});
it('should have hero.id === 0', () => {
expect(component.hero.id).toBe(0);
});
it('should display empty hero name', () => {
expect(page.nameDisplay.textContent).toBe('');
});
});
// #enddocregion route-no-id
// #docregion route-bad-id
describe('when navigate to non-existent hero id', () => {
beforeEach(async () => {
activatedRoute.setParamMap({id: 99999});
await createComponent();
await createComponent(999);
});
it('should try to navigate back to hero list', () => {
expect(page.gotoListSpy.calls.any())
.withContext('comp.gotoList called')
.toBe(true);
expect(page.navigateSpy.calls.any())
.withContext('router.navigate called')
.toBe(true);
expect(TestBed.inject(Router).url).toEqual('/heroes');
});
});
// #enddocregion route-bad-id
// Why we must use `fixture.debugElement.injector` in `Page()`
it("cannot use `inject` to get component's provided HeroDetailService", () => {
let service: HeroDetailService;
fixture = TestBed.createComponent(HeroDetailComponent);
expect(
// Throws because `inject` only has access to TestBed's injector
// which is an ancestor of the component's injector
inject([HeroDetailService], (hds: HeroDetailService) => service = hds))
.toThrowError(/No provider for HeroDetailService/);
// get `HeroDetailService` with component's own injector
service = fixture.debugElement.injector.get(HeroDetailService);
expect(service)
.withContext('debugElement.injector')
.toBeDefined();
});
}
/////////////////////
import { FormsModule } from '@angular/forms';
import { TitleCasePipe } from '../shared/title-case.pipe';
import {FormsModule} from '@angular/forms';
import {TitleCasePipe} from '../shared/title-case.pipe';
function formsModuleSetup() {
// #docregion setup-forms-module
beforeEach(async () => {
const routerSpy = createRouterSpy();
await TestBed
.configureTestingModule({
imports: [FormsModule],
declarations: [HeroDetailComponent, TitleCasePipe],
providers: [
{provide: ActivatedRoute, useValue: activatedRoute},
{provide: HeroService, useClass: TestHeroService},
{provide: Router, useValue: routerSpy},
provideHttpClient(),
provideHttpClientTesting(),
provideRouter([{path: 'heroes/:id', component: HeroDetailComponent}]),
]
})
.compileComponents();
});
// #enddocregion setup-forms-module
it("should display 1st hero's name", waitForAsync(() => {
const expectedHero = firstHero;
activatedRoute.setParamMap({id: expectedHero.id});
createComponent().then(() => {
expect(page.nameDisplay.textContent).toBe(expectedHero.name);
});
}));
it('should display 1st hero\'s name', async () => {
const expectedHero = firstHero;
await createComponent(expectedHero.id).then(() => {
expect(page.nameDisplay.textContent).toBe(expectedHero.name);
});
});
}
///////////////////////
import { SharedModule } from '../shared/shared.module';
function sharedModuleSetup() {
// #docregion setup-shared-module
beforeEach(async () => {
const routerSpy = createRouterSpy();
await TestBed
.configureTestingModule({
imports: [SharedModule],
declarations: [HeroDetailComponent],
providers: [
{provide: ActivatedRoute, useValue: activatedRoute},
{provide: HeroService, useClass: TestHeroService},
{provide: Router, useValue: routerSpy},
provideRouter([{path: 'heroes/:id', component: HeroDetailComponent}]),
provideHttpClient(),
provideHttpClientTesting(),
]
})
.compileComponents();
});
// #enddocregion setup-shared-module
it("should display 1st hero's name", waitForAsync(() => {
const expectedHero = firstHero;
activatedRoute.setParamMap({id: expectedHero.id});
createComponent().then(() => {
expect(page.nameDisplay.textContent).toBe(expectedHero.name);
});
}));
it('should display 1st hero\'s name', async () => {
const expectedHero = firstHero;
await createComponent(expectedHero.id).then(() => {
expect(page.nameDisplay.textContent).toBe(expectedHero.name);
});
});
}
/////////// Helpers /////
// #docregion create-component
/** Create the HeroDetailComponent, initialize it, set test variables */
function createComponent() {
fixture = TestBed.createComponent(HeroDetailComponent);
component = fixture.componentInstance;
page = new Page(fixture);
// #docregion create-component
async function createComponent(id: number) {
harness = await RouterTestingHarness.create();
component = await harness.navigateByUrl(`/heroes/${id}`, HeroDetailComponent);
page = new Page();
// 1st change detection triggers ngOnInit which gets a hero
fixture.detectChanges();
return fixture.whenStable().then(() => {
// 2nd change detection displays the async-fetched hero
fixture.detectChanges();
});
const request = TestBed.inject(HttpTestingController).expectOne(`api/heroes/?id=${id}`);
const hero = getTestHeroes().find(h => h.id === Number(id));
request.flush(hero ? [hero] : []);
harness.detectChanges();
}
// #enddocregion create-component
@@ -386,30 +296,13 @@ class Page {
return this.query<HTMLInputElement>('input');
}
gotoListSpy: jasmine.Spy;
navigateSpy: jasmine.Spy;
constructor(someFixture: ComponentFixture<HeroDetailComponent>) {
// get the navigate spy from the injected router spy object
const routerSpy = someFixture.debugElement.injector.get(Router) as any;
this.navigateSpy = routerSpy.navigate;
// spy on component's `gotoList()` method
const someComponent = someFixture.componentInstance;
this.gotoListSpy = spyOn(someComponent, 'gotoList').and.callThrough();
}
//// query helpers ////
private query<T>(selector: string): T {
return fixture.nativeElement.querySelector(selector);
return harness.routeNativeElement!.querySelector(selector)! as T;
}
private queryAll<T>(selector: string): T[] {
return fixture.nativeElement.querySelectorAll(selector);
return harness.routeNativeElement!.querySelectorAll(selector) as any as T[];
}
}
// #enddocregion page
function createRouterSpy() {
return jasmine.createSpyObj('Router', ['navigate']);
}
@@ -1,30 +1,29 @@
import { Injectable } from '@angular/core';
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Hero } from '../model/hero';
import { HeroService } from '../model/hero.service';
import {Hero} from '../model/hero';
import {HeroService} from '../model/hero.service';
// #docregion prototype
@Injectable()
@Injectable({providedIn: 'root'})
export class HeroDetailService {
constructor(private heroService: HeroService) { }
// #enddocregion prototype
constructor(private heroService: HeroService) {}
// #enddocregion prototype
// Returns a clone which caller may modify safely
getHero(id: number | string): Observable<Hero | null> {
getHero(id: number|string): Observable<Hero|null> {
if (typeof id === 'string') {
id = parseInt(id, 10);
}
return this.heroService.getHero(id).pipe(
map(hero => hero ? Object.assign({}, hero) : null) // clone or null
map(hero => hero ? Object.assign({}, hero) : null) // clone or null
);
}
saveHero(hero: Hero) {
return this.heroService.updateHero(hero);
}
// #docregion prototype
// #docregion prototype
}
// #enddocregion prototype
@@ -1,74 +1,69 @@
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import {HttpClient, HttpErrorResponse, HttpHeaders} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {catchError, map, tap} from 'rxjs/operators';
import { Observable } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
import { Hero } from './hero';
import {Hero} from './hero';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
headers: new HttpHeaders({'Content-Type': 'application/json'})
};
@Injectable()
@Injectable({providedIn: 'root'})
export class HeroService {
readonly heroesUrl = 'api/heroes'; // URL to web api
constructor(private http: HttpClient) { }
constructor(private http: HttpClient) {}
/** GET heroes from the server */
getHeroes(): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
.pipe(
tap(heroes => this.log('fetched heroes')),
catchError(this.handleError('getHeroes'))
) as Observable<Hero[]>;
.pipe(
tap(heroes => this.log('fetched heroes')),
catchError(this.handleError('getHeroes'))) as Observable<Hero[]>;
}
/** GET hero by id. Return `undefined` when id not found */
getHero<Data>(id: number | string): Observable<Hero> {
getHero<Data>(id: number|string): Observable<Hero> {
if (typeof id === 'string') {
id = parseInt(id, 10);
}
const url = `${this.heroesUrl}/?id=${id}`;
return this.http.get<Hero[]>(url)
.pipe(
map(heroes => heroes[0]), // returns a {0|1} element array
return this.http.get<Hero[]>(url).pipe(
map(heroes => heroes[0]), // returns a {0|1} element array
tap(h => {
const outcome = h ? 'fetched' : 'did not find';
this.log(`${outcome} hero id=${id}`);
}),
catchError(this.handleError<Hero>(`getHero id=${id}`))
);
catchError(this.handleError<Hero>(`getHero id=${id}`)));
}
//////// Save methods //////////
/** POST: add a new hero to the server */
addHero(hero: Hero): Observable<Hero> {
return this.http.post<Hero>(this.heroesUrl, hero, httpOptions).pipe(
tap((addedHero) => this.log(`added hero w/ id=${addedHero.id}`)),
catchError(this.handleError<Hero>('addHero'))
);
return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)
.pipe(
tap((addedHero) => this.log(`added hero w/ id=${addedHero.id}`)),
catchError(this.handleError<Hero>('addHero')));
}
/** DELETE: delete the hero from the server */
deleteHero(hero: Hero | number): Observable<Hero> {
deleteHero(hero: Hero|number): Observable<Hero> {
const id = typeof hero === 'number' ? hero : hero.id;
const url = `${this.heroesUrl}/${id}`;
return this.http.delete<Hero>(url, httpOptions).pipe(
tap(_ => this.log(`deleted hero id=${id}`)),
catchError(this.handleError<Hero>('deleteHero'))
);
return this.http.delete<Hero>(url, httpOptions)
.pipe(
tap(_ => this.log(`deleted hero id=${id}`)),
catchError(this.handleError<Hero>('deleteHero')));
}
/** PUT: update the hero on the server */
updateHero(hero: Hero): Observable<any> {
return this.http.put(this.heroesUrl, hero, httpOptions).pipe(
tap(_ => this.log(`updated hero id=${hero.id}`)),
catchError(this.handleError<any>('updateHero'))
);
return this.http.put(this.heroesUrl, hero, httpOptions)
.pipe(
tap(_ => this.log(`updated hero id=${hero.id}`)),
catchError(this.handleError<any>('updateHero')));
}
/**
* Returns a function that handles Http operation failures.
@@ -78,9 +73,8 @@ export class HeroService {
*/
private handleError<T>(operation = 'operation') {
return (error: HttpErrorResponse): Observable<T> => {
// TODO: send the error to remote logging infrastructure
console.error(error); // log to console instead
console.error(error); // log to console instead
// If a native error is caught, do not transform it. We only want to
// transform response errors that are not wrapped in an `Error`.
@@ -92,7 +86,6 @@ export class HeroService {
// TODO: better job of transforming error for user consumption
throw new Error(`${operation} failed: ${message}`);
};
}
private log(message: string) {
@@ -1,29 +0,0 @@
// export for convenience.
export { ActivatedRoute } from '@angular/router';
// #docregion activated-route-stub
import { convertToParamMap, ParamMap, Params } from '@angular/router';
import { ReplaySubject } from 'rxjs';
/**
* An ActivateRoute test double with a `paramMap` observable.
* Use the `setParamMap()` method to add the next `paramMap` value.
*/
export class ActivatedRouteStub {
// Use a ReplaySubject to share previous values with subscribers
// and pump new values into the `paramMap` observable
private subject = new ReplaySubject<ParamMap>();
constructor(initialParams?: Params) {
this.setParamMap(initialParams);
}
/** The mock paramMap observable */
readonly paramMap = this.subject.asObservable();
/** Set the paramMap observable's next value */
setParamMap(params: Params = {}) {
this.subject.next(convertToParamMap(params));
}
}
// #enddocregion activated-route-stub
@@ -1,10 +1,8 @@
import { DebugElement } from '@angular/core';
import { tick, ComponentFixture } from '@angular/core/testing';
import {DebugElement} from '@angular/core';
import {ComponentFixture, tick} from '@angular/core/testing';
export * from './async-observable-helpers';
export * from './activated-route-stub';
export * from './jasmine-matchers';
export * from './router-link-directive-stub';
///// Short utilities /////
@@ -18,12 +16,12 @@ export function advance(f: ComponentFixture<any>): void {
// #docregion click-event
/** Button events to pass to `DebugElement.triggerEventHandler` for RouterLink event handler */
export const ButtonClickEvents = {
left: { button: 0 },
right: { button: 2 }
left: {button: 0},
right: {button: 2}
};
/** Simulate element click. Defaults to mouse left-button click event. */
export function click(el: DebugElement | HTMLElement, eventObj: any = ButtonClickEvents.left): void {
export function click(el: DebugElement|HTMLElement, eventObj: any = ButtonClickEvents.left): void {
if (el instanceof HTMLElement) {
el.click();
} else {
@@ -1,30 +0,0 @@
import { Directive, Input, HostListener } from '@angular/core';
// export for convenience.
export { RouterLink} from '@angular/router';
/* eslint-disable @angular-eslint/directive-class-suffix, @angular-eslint/directive-selector */
// #docregion router-link
@Directive({
selector: '[routerLink]'
})
export class RouterLinkDirectiveStub {
@Input('routerLink') linkParams: any;
navigatedTo: any = null;
@HostListener('click')
onClick() {
this.navigatedTo = this.linkParams;
}
}
// #enddocregion router-link
/// Dummy module to satisfy Angular Language service. Never used.
import { NgModule } from '@angular/core';
@NgModule({
declarations: [
RouterLinkDirectiveStub
]
})
export class RouterStubsModule {}
@@ -1,6 +1,6 @@
{
"tests": [
{"cmd": "yarn", "args": ["test", "--browsers=ChromeHeadless", "--no-watch"]},
{"cmd": "yarn", "args": ["test", "--browsers=ChromeHeadlessNoSandbox", "--no-watch"]},
{"cmd": "yarn", "args": ["e2e", "--configuration=production", "--protractor-config=e2e/protractor-bazel.conf.js", "--no-webdriver-update", "--port=0"]}
]
}
@@ -0,0 +1,86 @@
@name Optional chain not nullable
@description
This diagnostic detects when the left side of an optional chain operation (`.?`) does not include `null` or `undefined` in its type in Angular templates.
<code-example format="typescript" language="typescript">
import {Component} from '&commat;angular/core';
&commat;Component({
template: `<div>{{ foo?.bar }}</div>`,
// &hellip;
})
class MyComponent {
// `foo` is declared as an object which *cannot* be `null` or `undefined`.
foo: { bar: string} = { bar: 'bar'};
}
</code-example>
## What should I do instead?
Update the template and declared type to be in sync. Double-check the type of the input and confirm whether it is actually expected to be nullable.
If the input should be nullable, add `null` or `undefined` to its type to indicate this.
<code-example format="typescript" language="typescript">
import {Component} from '&commat;angular/core';
&commat;Component({
// If `foo` is nullish, `bar` won't be evaluated and the express will return the nullish value (`null` or `undefined`).
template: `<div>{{ foo?.bar }}</div>`,
// &hellip;
})
class MyComponent {
foo: { bar: string} | null = { bar: 'bar'};
}
</code-example>
If the input should not be nullable, delete the `?` operator.
<code-example format="typescript" language="typescript">
import {Component} from '&commat;angular/core';
&commat;Component({
// Template always displays `bar` as `foo` is guaranteed to never be `null` or `undefined`
template: `<div>{{ foo.bar }}</div>`,
// &hellip;
})
class MyComponent {
foo: { bar: string} = { bar: 'bar'};
}
</code-example>
## What if I can't avoid this?
This diagnostic can be disabled by editing the project's `tsconfig.json` file:
<code-example format="json" language="json">
{
"angularCompilerOptions": {
"extendedDiagnostics": {
"checks": {
"optionalChainNotNullable": "suppress"
}
}
}
}
</code-example>
See [extended diagnostic configuration](extended-diagnostics#configuration) for more info.
<!-- links -->
<!-- external links -->
<!-- end links -->
@reviewed 2023-03-02
+2 -1
View File
@@ -11,9 +11,10 @@ Currently, Angular supports the following extended diagnostics:
* [NG8101 - `invalidBananaInBox`](extended-diagnostics/NG8101)
* [NG8102 - `nullishCoalescingNotNullable`](extended-diagnostics/NG8102)
* [NG8103 - `missingControlFlowDirective`](extended-diagnostics/NG8103)
* [NG8104 - `textAttributeNotBinding`](extended-diagnostics/NG8104)
* [NG8105 - `missingNgForOfLet`](extended-diagnostics/NG8105)
* [NG8106 - `suffixNotSupported`](extended-diagnostics/NG8106)
* [NG8104 - `textAttributeNotBinding`](extended-diagnostics/NG8104)
* [NG8107 - `optionalChainNotNullable`](extended-diagnostics/NG8107)
## Configuration
+1 -1
View File
@@ -84,7 +84,7 @@ The following are some of the key AngularJS built-in directives and their equiva
| AngularJS | Angular |
|:--- |:--- |
| <header><code>ng-model</code></header> <code-example hideCopy format="html" language="html"> &lt;input ng-model="vm.favoriteHero" /&gt; </code-example> In AngularJS, the `ng-model` directive binds a form control to a property in the controller associated with the template. This provides **two-way binding** whereby changes result in the value in the view and the model being synchronized. | <header><code>ngModel</code></header> <code-example hideCopy path="ajs-quick-reference/src/app/movie-list.component.html" region="ngModel"></code-example> In Angular, **two-way binding** is indicatedr5t by `[()]`, descriptively referred to as a "banana in a box." This syntax is a shortcut for defining both:<ul><li>property binding, from the component to the view</li><li>event binding, from the view to the component</li></ul> thereby providing two-way binding. <br /> For more information on two-way binding with `ngModel`, see the [Displaying and updating properties with `ngModel`][AioGuideBuiltInDirectivesDisplayingAndUpdatingPropertiesWithNgmodel] section of [Built-in directives][AioGuideBuiltInDirectives]. |
| <header><code>ng-model</code></header> <code-example hideCopy format="html" language="html"> &lt;input ng-model="vm.favoriteHero" /&gt; </code-example> In AngularJS, the `ng-model` directive binds a form control to a property in the controller associated with the template. This provides **two-way binding** whereby changes result in the value in the view and the model being synchronized. | <header><code>ngModel</code></header> <code-example hideCopy path="ajs-quick-reference/src/app/movie-list.component.html" region="ngModel"></code-example> In Angular, **two-way binding** is indicated by `[()]`, descriptively referred to as a "banana in a box." This syntax is a shortcut for defining both:<ul><li>property binding, from the component to the view</li><li>event binding, from the view to the component</li></ul> thereby providing two-way binding. <br /> For more information on two-way binding with `ngModel`, see the [Displaying and updating properties with `ngModel`][AioGuideBuiltInDirectivesDisplayingAndUpdatingPropertiesWithNgmodel] section of [Built-in directives][AioGuideBuiltInDirectives]. |
### `ng-repeat` &rarr; `*ngFor`
@@ -220,7 +220,7 @@ When you use the Angular CLI command `ng new --strict`, it is set to `true` in t
When `true`, enables [strict template type checking](guide/template-typecheck#strict-mode).
The strictness flags that this open enables allow you to turn on and off specific types of strict template type checking.
The strictness flags that this option enables allow you to turn on and off specific types of strict template type checking.
See [troubleshooting template errors](guide/template-typecheck#troubleshooting-template-errors).
When you use the Angular CLI command `ng new --strict`, it is set to `true` in the new project's configuration.
@@ -1,6 +1,6 @@
# Resolving zone pollution
**Zone.js** is a signaling mechanism that Angular uses to detect when an application state might have changed. It captures asynchronous operations like `setTimeout`, network requests, and event listeners. Angular schedules change detection based on signals from Zone.js
**Zone.js** is a signaling mechanism that Angular uses to detect when an application state might have changed. It captures asynchronous operations like `setTimeout`, network requests, and event listeners. Angular schedules change detection based on signals from Zone.js.
In some cases scheduled [tasks](https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide#tasks) or [microtasks](https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide#microtasks) don’t make any changes in the data model, which makes running change detection unnecessary. Common examples are:
* `requestAnimationFrame`, `setTimeout` or `setInterval`
+1 -1
View File
@@ -2,7 +2,7 @@
**Change detection** is the process through which Angular checks to see whether your application state has changed, and if any DOM needs to be updated. At a high level, Angular walks your components from top to bottom, looking for changes. Angular runs its change detection mechanism periodically so that changes to the data model are reflected in an application’s view. Change detection can be triggered either manually or through an asynchronous event (for example, a user interaction or an XMLHttpRequest completion).
Change detection is a highly optimized performant, but it can still cause slowdowns if the application runs it too frequently.
Change detection is highly optimized and performant, but it can still cause slowdowns if the application runs it too frequently.
In this guide, you’ll learn how to control and optimize the change detection mechanism by skipping parts of your application and running change detection only when necessary.
+10 -13
View File
@@ -247,7 +247,7 @@ The `production` configuration engages the following build optimization features
| Features | Details |
|:--- |:--- |
| [Ahead-of-Time (AOT) Compilation](guide/aot-compiler) | Pre-compiles Angular component templates. |
| [Production mode](#enable-prod-mode) | Deploys the production environment which enables *production mode*. |
| [Production mode](#prod-mode) | Optimizes the application for the best runtime performance |
| Bundling | Concatenates your many application and library files into a few bundles. |
| Minification | Removes excess whitespace, comments, and optional tokens. |
| Uglification | Rewrites code to use short, cryptic variable and function names. |
@@ -255,23 +255,20 @@ The `production` configuration engages the following build optimization features
See [`ng build`](cli/build) for more about CLI build options and what they do.
<a id="enable-prod-mode"></a>
<a id="prod-mode"></a>
### Enable runtime production mode
### Production mode at runtime
In addition to build optimizations, Angular also has a runtime production mode.
Angular applications run in development mode by default, as you can see by the following message on the browser console:
When you run an application locally using `ng serve`, Angular uses the development mode configuration
at runtime. The development mode at runtime enables extra safety checks, more detailed error messages
and debugging utilities, such as the [expression-changed-after-checked](errors/NG0100) detection. Angular outputs
a message in the browser console to indicate that the development mode is enabled.
<code-example format="output" hideCopy language="shell">
Those extra checks are helpful during the development, but they require an extra code in a bundle, which is
undesirable in production. To ensure that there are no implications on the bundle size, the build optimizer
removes the development-only code from the bundle when building in production mode.
Angular is running in development mode.
Call `enableProdMode()` to enable production mode.
</code-example>
*Production mode* improves application performance by disabling development-only safety checks and debugging utilities, such as the expression-changed-after-checked detection.
Building your application with the production configuration automatically enables Angular's runtime production mode.
<a id="lazy-loading"></a>
### Lazy loading
-9
View File
@@ -45,7 +45,6 @@ v15 - v18
| `@angular/common` | [`ReflectiveInjector`](#reflectiveinjector) | v8 | v11 |
| `@angular/core` | [`DefaultIterableDiffer`](#core) | v7 | v11 |
| `@angular/core` | [`ReflectiveKey`](#core) | v8 | v11 |
| `@angular/core` | [`RenderComponentType`](#core) | v7 | v11 |
| `@angular/core` | [`defineInjectable`](#core) | v8 | v11 |
| `@angular/core` | [`entryComponents`](api/core/NgModule#entryComponents) | v9 | v11 |
| `@angular/core` | [`ANALYZE_FOR_ENTRY_COMPONENTS`](api/core/ANALYZE_FOR_ENTRY_COMPONENTS) | v9 | v11 |
@@ -274,14 +273,6 @@ In the [API reference section](api) of this site, deprecated APIs are indicated
This section lists all deprecated features, which includes template syntax, configuration options, and any other deprecations not listed in the [Deprecated APIs](#deprecated-apis) section.
It also includes deprecated API usage scenarios or API combinations, to augment the information above.
<a id="bazelbuilder"></a>
### Bazel builder and schematics
Bazel builder and schematics were introduced in Angular Labs to let users try out Bazel without having to manage Bazel version and BUILD files.
This feature has been deprecated.
For more information, please refer to the [migration doc](https://github.com/angular/angular/blob/main/packages/bazel/docs/BAZEL_SCHEMATICS.md).
<a id="wtf"></a>
### Web Tracing Framework integration
+1 -1
View File
@@ -1,7 +1,7 @@
# DevTools Overview
Angular DevTools is a browser extension that provides debugging and profiling capabilities for Angular applications.
Angular DevTools supports Angular v12 and later.
Angular DevTools supports Angular v12 and later when compiled with the [optimization configuration option](guide/workspace-config#optimization-configuration) disabled (<code>{optimization:false}</code>).
<div class="video-container">
+1 -1
View File
@@ -929,7 +929,7 @@ View Engine was deprecated in version 9 and removed in version 13.
## view hierarchy
A tree of related views that can be acted on as a unit.
The root view referenced as the *host view* of a component.
The root view is referenced as the *host view* of a component.
A host view is the root of a tree of *embedded views*, collected in a `ViewContainerRef` view container attached to an anchor element in the hosting component.
The view hierarchy is a key part of Angular [change detection][AioGuideGlossaryChangeDetection].
@@ -741,7 +741,7 @@ The example application uses `@Optional()` so the application does not throw an
The `<app-child>` currently provides the `AnimalService` in the `viewProviders` array with the value of dog <code>&#x1F436;</code>.
Because the injector has only to look at the `ElementInjector` of the `<app-child>` for the `AnimalService`, it never sees the whale <code>&#x1F433;</code>.
As in the `FlowerService` example, if you add `@SkipSelf()` to the constructor for the `AnimalService`, the injector won't look in the `ElementInjector` or the current `<app-child>` for the `AnimalService`.
As in the `FlowerService` example, if you add `@SkipSelf()` to the constructor for the `AnimalService`, the injector won't look in the `ElementInjector` of the current `<app-child>` for the `AnimalService`.
<code-example format="typescript" language="typescript">
@@ -1,3 +1,37 @@
# Configure HTTP URL parameters
# HTTP - Configure URL parameters
@reviewed 2022-10-06
Use the `HttpParams` class with the `params` request option to add URL query strings in your `HttpRequest`.
## Create URL parameter using the search method
The following example, the `searchHeroes()` method queries for heroes whose names contain the search term.
Start by importing `HttpParams` class.
<code-example hideCopy language="typescript">
import {HttpParams} from "&commat;angular/common/http";
</code-example>
<code-example linenums="false" path="http/src/app/heroes/heroes.service.ts" region="searchHeroes"></code-example>
If there is a search term, the code constructs an options object with an HTML URL-encoded search parameter.
If the term is "cat", for example, the GET request URL would be `api/heroes?name=cat`.
The `HttpParams` object is immutable.
If you need to update the options, save the returned value of the `.set()` method.
## Create URL parameters from a query
You can also create HTTP parameters directly from a query string by using the `fromString` variable:
<code-example hideCopy language="typescript">
const params = new HttpParams({fromString: 'name=foo'});
</code-example>
<a id="intercepting-requests-and-responses"></a>
@reviewed 2022-11-08
@@ -1,3 +1,60 @@
# Handle request errors
# HTTP client - Handle request errors
@reviewed 2022-10-06
If the request fails on the server, `HttpClient` returns an *error* object instead of a successful response.
The same service that performs your server transactions should also perform error inspection, interpretation, and resolution.
When an error occurs, you can obtain details of what failed to inform your user.
In some cases, you might also automatically [retry the request](#retry).
<a id="error-details"></a>
## Getting error details
An app should give the user useful feedback when data access fails.
A raw error object is not particularly useful as feedback.
In addition to detecting that an error has occurred, you need to get error details and use those details to compose a user-friendly response.
Two types of errors can occur.
* The server backend might reject the request, returning an HTTP response with a status code such as 404 or 500.
These are error *responses*.
* Something could go wrong on the client-side such as a network error that prevents the request from completing successfully or an exception thrown in an RxJS operator.
These errors have `status` set to `0` and the `error` property contains a `ProgressEvent` object, whose `type` might provide further information.
`HttpClient` captures both kinds of errors in its `HttpErrorResponse`.
Inspect that response to identify the error's cause.
The following example defines an error handler in the previously defined ConfigService.
<code-example header="app/config/config.service.ts (handleError)" path="http/src/app/config/config.service.ts" region="handleError"></code-example>
The handler returns an RxJS `ErrorObservable` with a user-friendly error message.
The following code updates the `getConfig()` method, using a [pipe](guide/pipes "Pipes guide") to send all observables returned by the `HttpClient.get()` call to the error handler.
<code-example header="app/config/config.service.ts (getConfig v.3 with error handler)" path="http/src/app/config/config.service.ts" region="getConfig_3"></code-example>
<a id="retry"></a>
## Retrying a failed request
Sometimes the error is transient and goes away automatically if you try again.
For example, network interruptions are common in mobile scenarios, and trying again can produce a successful result.
The [RxJS library](guide/rx-library) offers several *retry* operators.
For example, the `retry()` operator automatically re-subscribes to a failed `Observable` a specified number of times.
*Re-subscribing* to the result of an `HttpClient` method call has the effect of reissuing the HTTP request.
The following example shows how to pipe a failed request to the `retry()` operator before passing it to the error handler.
<code-example header="app/config/config.service.ts (getConfig with retry)" path="http/src/app/config/config.service.ts" region="getConfig"></code-example>
## Sending data to a server
In addition to fetching data from a server, `HttpClient` supports other HTTP methods such as PUT, POST, and DELETE, which you can use to modify the remote data.
The sample app for this guide includes an abridged version of the "Tour of Heroes" example that fetches heroes and enables users to add, delete, and update them.
The following sections show examples of the data-update methods from the sample's `HeroesService`.
@reviewed 2023-02-27
@@ -1,3 +1,189 @@
# Intercept requests and responses
# HTTP - Intercept requests and responses
@reviewed 2022-10-06
With interception, you declare *interceptors* that inspect and transform HTTP requests from your application to a server.
The same interceptors can also inspect and transform a server's responses on their way back to the application.
Multiple interceptors form a *forward-and-backward* chain of request/response handlers.
Interceptors can perform a variety of *implicit* tasks, from authentication to logging, in a routine, standard way, for every HTTP request/response.
Without interception, developers would have to implement these tasks *explicitly* for each `HttpClient` method call.
## Write an interceptor
To implement an interceptor, declare a class that implements the `intercept()` method of the `HttpInterceptor` interface.
Here is a do-nothing `noop` interceptor that passes the request through without touching it:
<code-example header="app/http-interceptors/noop-interceptor.ts" path="http/src/app/http-interceptors/noop-interceptor.ts"></code-example>
The `intercept` method transforms a request into an `Observable` that eventually returns the HTTP response.
In this sense, each interceptor is fully capable of handling the request entirely by itself.
Most interceptors inspect the request on the way in and forward the potentially altered request to the `handle()` method of the `next` object which implements the [`HttpHandler`](api/common/http/HttpHandler) interface.
<code-example format="javascript" language="javascript">
export abstract class HttpHandler {
abstract handle(req: HttpRequest&lt;any&gt;): Observable&lt;HttpEvent&lt;any&gt;&gt;;
}
</code-example>
Like `intercept()`, the `handle()` method transforms an HTTP request into an `Observable` of [`HttpEvents`](#interceptor-events) which ultimately include the server's response.
The `intercept()` method could inspect that observable and alter it before returning it to the caller.
This `no-op` interceptor calls `next.handle()` with the original request and returns the observable without doing a thing.
## The `next` object
The `next` object represents the next interceptor in the chain of interceptors.
The final `next` in the chain is the `HttpClient` backend handler that sends the request to the server and receives the server's response.
Most interceptors call `next.handle()` so that the request flows through to the next interceptor and, eventually, the backend handler.
An interceptor *could* skip calling `next.handle()`, short-circuit the chain, and [return its own `Observable`](guide/http-interceptor-use-cases#caching) with an artificial server response.
This is a common middleware pattern found in frameworks such as Express.js.
## Provide the interceptor
The `NoopInterceptor` is a service managed by Angular's [dependency injection (DI)](guide/dependency-injection) system.
Like other services, you must provide the interceptor class before the app can use it.
Because interceptors are optional dependencies of the `HttpClient` service, you must provide them in the same injector or a parent of the injector that provides `HttpClient`.
Interceptors provided *after* DI creates the `HttpClient` are ignored.
This app provides `HttpClient` in the app's root injector, as a side-effect of importing the `HttpClientModule` in `AppModule`.
You should provide interceptors in `AppModule` as well.
After importing the `HTTP_INTERCEPTORS` injection token from `@angular/common/http`, write the `NoopInterceptor` provider like this:
<code-example path="http/src/app/http-interceptors/index.ts" region="noop-provider"></code-example>
Notice the `multi: true` option.
This required setting tells Angular that `HTTP_INTERCEPTORS` is a token for a *multiprovider* that injects an array of values, rather than a single value.
You *could* add this provider directly to the providers array of the `AppModule`.
However, it's rather verbose and there's a good chance that you'll create more interceptors and provide them in the same way.
You must also pay [close attention to the order](#interceptor-order) in which you provide these interceptors.
Consider creating a "barrel" file that gathers all the interceptor providers into an `httpInterceptorProviders` array, starting with this first one, the `NoopInterceptor`.
<code-example header="app/http-interceptors/index.ts" path="http/src/app/http-interceptors/index.ts" region="interceptor-providers"></code-example>
Then import and add it to the `AppModule` `providers array` like this:
<code-example header="app/app.module.ts (interceptor providers)" path="http/src/app/app.module.ts" region="interceptor-providers"></code-example>
As you create new interceptors, add them to the `httpInterceptorProviders` array and you won't have to revisit the `AppModule`.
<div class="alert is-helpful">
There are many more interceptors in the complete sample code.
</div>
## Interceptor order
Angular applies interceptors in the order that you provide them.
For example, consider a situation in which you want to handle the authentication of your HTTP requests and log them before sending them to a server.
To accomplish this task, you could provide an `AuthInterceptor` service and then a `LoggingInterceptor` service.
Outgoing requests would flow from the `AuthInterceptor` to the `LoggingInterceptor`.
Responses from these requests would flow in the other direction, from `LoggingInterceptor` back to `AuthInterceptor`.
The following is a visual representation of the process:
<div class="lightbox">
<img alt="Interceptor in order of HttpClient, AuthInterceptor, AuthInterceptor, HttpBackend, Server, and back in opposite order to show the two-way flow" src="generated/images/guide/http/interceptor-order.svg">
</div>
<div class="alert is-helpful">
The last interceptor in the process is always the `HttpBackend` that handles communication with the server.
</div>
You cannot change the order or remove interceptors later.
If you need to enable and disable an interceptor dynamically, you'll have to build that capability into the interceptor itself.
<a id="interceptor-events"></a>
## Handle interceptor events
Most `HttpClient` methods return observables of `HttpResponse<any>`.
The `HttpResponse` class itself is actually an event, whose type is `HttpEventType.Response`.
A single HTTP request can, however, generate multiple events of other types, including upload and download progress events.
The methods `HttpInterceptor.intercept()` and `HttpHandler.handle()` return observables of `HttpEvent<any>`.
Many interceptors are only concerned with the outgoing request and return the event stream from `next.handle()` without modifying it.
Some interceptors, however, need to examine and modify the response from `next.handle()`; these operations can see all of these events in the stream.
<a id="immutability"></a>
Although interceptors are capable of modifying requests and responses, the `HttpRequest` and `HttpResponse` instance properties are `readonly`, rendering them largely immutable.
They are immutable for a good reason:
An app might retry a request several times before it succeeds, which means that the interceptor chain can re-process the same request multiple times.
If an interceptor could modify the original request object, the re-tried operation would start from the modified request rather than the original.
Immutability ensures that interceptors see the same request for each try.
<div class="alert is-helpful">
Your interceptor should return every event without modification unless it has a compelling reason to do otherwise.
</div>
TypeScript prevents you from setting `HttpRequest` read-only properties.
<code-example format="javascript" language="javascript">
// Typescript disallows the following assignment because req.url is readonly
req.url = req.url.replace('http://', 'https://');
</code-example>
If you must alter a request, clone it first and modify the clone before passing it to `next.handle()`.
You can clone and modify the request in a single step, as shown in the following example.
<code-example header="app/http-interceptors/ensure-https-interceptor.ts (excerpt)" path="http/src/app/http-interceptors/ensure-https-interceptor.ts" region="excerpt"></code-example>
The `clone()` method's hash argument lets you mutate specific properties of the request while copying the others.
### Modify a request body
The `readonly` assignment guard can't prevent deep updates and, in particular, it can't prevent you from modifying a property of a request body object.
<code-example format="javascript" language="javascript">
req.body.name = req.body.name.trim(); // bad idea!
</code-example>
If you must modify the request body, follow these steps.
1. Copy the body and make your change in the copy.
1. Clone the request object, using its `clone()` method.
1. Replace the clone's body with the modified copy.
<code-example header="app/http-interceptors/trim-name-interceptor.ts (excerpt)" path="http/src/app/http-interceptors/trim-name-interceptor.ts" region="excerpt"></code-example>
### Clear the request body in a clone
Sometimes you need to clear the request body rather than replace it.
To do this, set the cloned request body to `null`.
<div class="alert is-helpful">
**TIP**: <br />
If you set the cloned request body to `undefined`, Angular assumes you intend to leave the body as is.
</div>
<code-example format="javascript" language="javascript">
newReq = req.clone({ &hellip; }); // body not mentioned =&gt; preserve original body
newReq = req.clone({ body: undefined }); // preserve original body
newReq = req.clone({ body: null }); // clear the body
</code-example>
@reviewed 2023-03-16
+126 -2
View File
@@ -1,3 +1,127 @@
# HTTP interceptor use-cases
# HTTP - interceptor use-cases
@reviewed 2022-10-06
Following are a number of common uses for interceptors.
## Set default headers
Apps often use an interceptor to set default headers on outgoing requests.
The sample app has an `AuthService` that produces an authorization token.
Here is its `AuthInterceptor` that injects that service to get the token and adds an authorization header with that token to every outgoing request:
<code-example header="app/http-interceptors/auth-interceptor.ts" path="http/src/app/http-interceptors/auth-interceptor.ts"></code-example>
The practice of cloning a request to set new headers is so common that there's a `setHeaders` shortcut for it:
<code-example path="http/src/app/http-interceptors/auth-interceptor.ts" region="set-header-shortcut"></code-example>
An interceptor that alters headers can be used for a number of different operations, including:
* Authentication/authorization
* Caching behavior; for example, `If-Modified-Since`
* XSRF protection
## Log request and response pairs
Because interceptors can process the request and response *together*, they can perform tasks such as timing and logging an entire HTTP operation.
Consider the following `LoggingInterceptor`, which captures the time of the request,
the time of the response, and logs the outcome with the elapsed time
with the injected `MessageService`.
<code-example header="app/http-interceptors/logging-interceptor.ts)" path="http/src/app/http-interceptors/logging-interceptor.ts" region="excerpt"></code-example>
The RxJS `tap` operator captures whether the request succeeded or failed.
The RxJS `finalize` operator is called when the response observable either returns an error or completes and reports the outcome to the `MessageService`.
Neither `tap` nor `finalize` touch the values of the observable stream returned to the caller.
<a id="custom-json-parser"></a>
## Custom JSON parsing
Interceptors can be used to replace the built-in JSON parsing with a custom implementation.
The `CustomJsonInterceptor` in the following example demonstrates how to achieve this.
If the intercepted request expects a `'json'` response, the `responseType` is changed to `'text'` to disable the built-in JSON parsing.
Then the response is parsed via the injected `JsonParser`.
<code-example header="app/http-interceptors/custom-json-interceptor.ts" path="http/src/app/http-interceptors/custom-json-interceptor.ts" region="custom-json-interceptor"></code-example>
You can then implement your own custom `JsonParser`.
Here is a custom JsonParser that has a special date reviver.
<code-example header="app/http-interceptors/custom-json-interceptor.ts" path="http/src/app/http-interceptors/custom-json-interceptor.ts" region="custom-json-parser"></code-example>
You provide the `CustomParser` along with the `CustomJsonInterceptor`.
<code-example header="app/http-interceptors/index.ts" path="http/src/app/http-interceptors/index.ts" region="custom-json-interceptor"></code-example>
<a id="caching"></a>
## Cache requests
Interceptors can handle requests by themselves, without forwarding to `next.handle()`.
For example, you might decide to cache certain requests and responses to improve performance.
You can delegate caching to an interceptor without disturbing your existing data services.
The `CachingInterceptor` in the following example demonstrates this approach.
<code-example header="app/http-interceptors/caching-interceptor.ts)" path="http/src/app/http-interceptors/caching-interceptor.ts" region="v1"></code-example>
* The `isCacheable()` function determines if the request is cacheable.
In this sample, only GET requests to the package search API are cacheable.
* If the request is not cacheable, the interceptor forwards the request to the next handler in the chain
* If a cacheable request is found in the cache, the interceptor returns an `of()` *observable* with the cached response, by-passing the `next` handler and all other interceptors downstream
* If a cacheable request is not in cache, the code calls `sendRequest()`.
This function forwards the request to `next.handle()` which ultimately calls the server and returns the server's response.
<a id="send-request"></a>
<code-example path="http/src/app/http-interceptors/caching-interceptor.ts" region="send-request"></code-example>
<div class="alert is-helpful">
Notice how `sendRequest()` intercepts the response on its way back to the application.
This method pipes the response through the `tap()` operator, whose callback adds the response to the cache.
The original response continues untouched back up through the chain of interceptors to the application caller.
Data services, such as `PackageSearchService`, are unaware that some of their `HttpClient` requests actually return cached responses.
</div>
<a id="cache-refresh"></a>
## Use interceptors to request multiple values
The `HttpClient.get()` method normally returns an observable that emits a single value, either the data or an error.
An interceptor can change this to an observable that emits [multiple values](guide/observables).
The following revised version of the `CachingInterceptor` optionally returns an observable that immediately emits the cached response, sends the request on to the package search API, and emits again later with the updated search results.
<code-example path="http/src/app/http-interceptors/caching-interceptor.ts" region="intercept-refresh"></code-example>
<div class="alert is-helpful">
The *cache-then-refresh* option is triggered by the presence of a custom `x-refresh` header.
A checkbox on the `PackageSearchComponent` toggles a `withRefresh` flag, which is one of the arguments to `PackageSearchService.search()`.
That `search()` method creates the custom `x-refresh` header and adds it to the request before calling `HttpClient.get()`.
</div>
The revised `CachingInterceptor` sets up a server request whether there's a cached value or not, using the same `sendRequest()` method described [above](#send-request).
The `results$` observable makes the request when subscribed.
* If there's no cached value, the interceptor returns `results$`.
* If there is a cached value, the code *pipes* the cached response onto `results$`. This produces a recomposed observable that emits two responses, so subscribers will see a sequence of these two responses:
* The cached response that's emitted immediately
* The response from the server, that's emitted later
<a id="report-progress"></a>
@reviewed 2022-11-08
+46 -2
View File
@@ -1,3 +1,47 @@
# Make a JSON with Padding request
# HTTP: Make a JSONP request
@reviewed 2022-10-06
“JSON with Padding” (JSONP) is a method to deceive a web browser into carrying out requests with a `<script>` tag that uses the SRC attribute to make a special API request.
Apps can use the `HttpClient` to make [JSONP](https://en.wikipedia.org/wiki/JSONP) requests across domains when a server doesn't support [CORS protocol](https://developer.mozilla.org/docs/Web/HTTP/CORS).
Angular JSONP requests return an `Observable`.
Follow the pattern for subscribing to observables and use the RxJS `map` operator to transform the response before using the [async pipe](api/common/AsyncPipe) to manage the results.
In Angular, use JSONP by including `HttpClientJsonpModule` in the `NgModule` imports.
In the following example, the `searchHeroes()` method uses a JSONP request to query for heroes whose names contain the search term.
<code-example format="typescript" language="typescript">
/* GET heroes whose name contains search term */
searchHeroes(term: string): Observable {
term = term.trim();
const heroesURL = `&dollar;{this.heroesURL}?&dollar;{term}`;
return this.http.jsonp(heroesUrl, 'callback').pipe(
catchError(this.handleError('searchHeroes', [])) // then handle the error
);
}
</code-example>
This request passes the `heroesURL` as the first parameter and the callback function name as the second parameter.
The response is wrapped in the callback function, which takes the observables returned by the JSONP method and pipes them through to the error handler.
## Request non-JSON data
Not all APIs return JSON data.
In this next example, a `DownloaderService` method reads a text file from the server and logs the file contents, before returning those contents to the caller as an `Observable<string>`.
<code-example header="app/downloader/downloader.service.ts (getTextFile)" linenums="false" path="http/src/app/downloader/downloader.service.ts" region="getTextFile"></code-example>
`HttpClient.get()` returns a string rather than the default JSON because of the `responseType` option.
The RxJS `tap` operator lets the code inspect both success and error values passing through the observable without disturbing them.
A `download()` method in the `DownloaderComponent` initiates the request by subscribing to the service method.
<code-example header="app/downloader/downloader.component.ts (download)" linenums="false" path="http/src/app/downloader/downloader.component.ts" region="download"></code-example>
<a id="error-handling"></a>
@reviewed 2022-11-03
@@ -1,3 +1,65 @@
# Optimize server interaction with debouncing
# HTTP - Optimize server interaction with debouncing
@reviewed 2022-10-06
If you need to make an HTTP request in response to user input, it's not efficient to send a request for every keystroke. It's better to wait until the user stops typing and then send a request. This technique is known as debouncing.
## Implement debouncing
Consider the following template, which lets a user enter a search term to find a package by name. When the user enters a name in a search-box, the `PackageSearchComponent` sends a search request for a package with that name to the package search API.
<code-example header="app/package-search/package-search.component.html (search)" path="http/src/app/package-search/package-search.component.html" region="search"></code-example>
Here, the `keyup` event binding sends every keystroke to the component's `search()` method.
<div class="alert is-helpful">
The type of `$event.target` is only `EventTarget` in the template.
In the `getValue()` method, the target is cast to an `HTMLInputElement` to let type-safe have access to its `value` property.
<code-example path="http/src/app/package-search/package-search.component.ts" region="getValue"></code-example>
</div>
The following snippet implements debouncing for this input using RxJS operators.
<code-example header="app/package-search/package-search.component.ts (excerpt)" path="http/src/app/package-search/package-search.component.ts" region="debounce"></code-example>
The `searchText$` is the sequence of search-box values coming from the user.
It's defined as an RxJS `Subject`, which means it is a multicasting `Observable` that can also emit values for itself by calling `next(value)`, as happens in the `search()` method.
Rather than forward every `searchText` value directly to the injected `PackageSearchService`, the code in `ngOnInit()` pipes search values through three operators, so that a search value reaches the service only if it's a new value and the user stopped typing.
| RxJS operators | Details |
|:--- |:--- |
| `debounceTime(500)`⁠ | Wait for the user to stop typing, which is 1/2 second in this case. |
| `distinctUntilChanged()` | Wait until the search text changes. |
| `switchMap()`⁠ | Send the search request to the service. |
The code sets `packages$` to this re-composed `Observable` of search results.
The template subscribes to `packages$` with the [AsyncPipe](api/common/AsyncPipe) and displays search results as they arrive.
<div class="alert is-helpful">
See [Using interceptors to request multiple values](guide/http-interceptor-use-cases#cache-refresh) for more about the `withRefresh` option.
</div>
## Using the `switchMap()` operator
The `switchMap()` operator takes a function argument that returns an `Observable`.
In the example, `PackageSearchService.search` returns an `Observable`, as other data service methods do.
If a previous search request is still in-flight, such as when the network connection is poor, the operator cancels that request and sends a new one.
<div class="alert is-helpful">
**NOTE**: <br />
`switchMap()` returns service responses in their original request order, even if the server returns them out of order.
</div>
<div class="alert is-helpful">
If you think you'll reuse this debouncing logic, consider moving it to a utility function or into the `PackageSearchService` itself.
</div>
@reviewed 2023-02-27
@@ -1,3 +1,49 @@
# Pass metadata to interceptors
# HTTP - Pass metadata to interceptors
@reviewed 2022-10-06
Many interceptors require or benefit from configuration.
Consider an interceptor that retries failed requests.
By default, the interceptor might retry a request three times, but you might want to override this retry count for particularly error-prone or sensitive requests.
`HttpClient` requests contain a *context* that can carry metadata about the request.
This context is available for interceptors to read or modify, though it is not transmitted to the backend server when the request is sent.
This lets applications or other interceptors tag requests with configuration parameters, such as how many times to retry a request.
## Create a context token
Angular stores and retrieves a value in the context using an `HttpContextToken`.
You can create a context token using the `new` operator, as in the following example:
<code-example header="creating a context token" path="http/src/app/http-interceptors/retry-interceptor.ts" region="context-token"></code-example>
The lambda function `() => 3` passed during the creation of the `HttpContextToken` serves two purposes:
1. It lets TypeScript infer the type of this token:
`HttpContextToken<number>`
The request context is type-safe &mdash;reading a token from a request's context returns a value of the appropriate type.
1. It sets the default value for the token.
This is the value that the request context returns if no other value was set for this token.
Using a default value avoids the need to check if a particular value is set.
## Set context values when making a request
When making a request, you can provide an `HttpContext` instance, in which you have already set the context values.
<code-example header="setting context values" path="http/src/app/http-interceptors/retry-interceptor.ts" region="set-context"></code-example>
## Read context values in an interceptor
Within an interceptor, you can read the value of a token in a given request's context with `HttpContext.get()`.
If you have not explicitly set a value for the token, Angular returns the default value specified in the token.
<code-example header="reading context values in an interceptor" path="http/src/app/http-interceptors/retry-interceptor.ts" region="reading-context"></code-example>
## Contexts are mutable
Unlike most other aspects of `HttpRequest` instances, the request context is mutable and persists across other immutable transformations of the request.
This lets interceptors coordinate operations through the context.
For instance, the `RetryInterceptor` example could use a second context token to track how many errors occur during the execution of a given request:
<code-example header="coordinating operations through the context" path="http/src/app/http-interceptors/retry-interceptor.ts" region="mutable-context"></code-example>
@reviewed 2022-11-15
@@ -1,3 +1,221 @@
# Request data from a server
# HTTP: Request data from a server
@reviewed 2022-10-06
Use the [`HttpClient.get()`](api/common/http/HttpClient#get) method to fetch data from a server.
The asynchronous method sends an HTTP request, and returns an Observable that emits the requested data when the response is received.
The return type varies based on the `observe` and `responseType` values that you pass to the call.
The `get()` method takes two arguments; the endpoint URL from which to fetch, and an *options* object that is used to configure the request.
<code-example format="typescript" language="typescript">
options: {
headers?: HttpHeaders &verbar; {[header: string]: string &verbar; string[]},
observe?: 'body' &verbar; 'events' &verbar; 'response',
params?: HttpParams&verbar;{[param: string]: string &verbar; number &verbar; boolean &verbar; ReadonlyArray&lt;string &verbar; number &verbar; boolean&gt;},
reportProgress?: boolean,
responseType?: 'arraybuffer'&verbar;'blob'&verbar;'json'&verbar;'text',
withCredentials?: boolean,
}
</code-example>
Important options include the *observe* and *responseType* properties.
* The *observe* option specifies how much of the response to return
* The *responseType* option specifies the format in which to return data
<div class="alert is-helpful">
Use the `options` object to configure various other aspects of an outgoing request.
In adding headers, for example, the service set the default headers using the `headers` option property.
Use the `params` property to configure a request with HTTP URL parameters, and the `reportProgress` option to listen for progress events when transferring large amounts of data.
</div>
Applications often request JSON data from a server.
In the `ConfigService` example, the app needs a configuration file on the server, `config.json`, that specifies resource URLs.
<code-example header="assets/config.json" path="http/src/assets/config.json"></code-example>
To fetch this kind of data, the `get()` call needs the following options: `{observe: 'body', responseType: 'json'}`.
These are the default values for those options, so the following examples do not pass the options object.
Later sections show some of the additional option possibilities.
<a id="config-service"></a>
The example conforms to the best practices for creating scalable solutions by defining a re-usable [injectable service](guide/glossary#service "service definition") to perform the data-handling functionality.
In addition to fetching data, the service can post-process the data, add error handling, and add retry logic.
The `ConfigService` fetches this file using the `HttpClient.get()` method.
<code-example header="app/config/config.service.ts (getConfig v.1)" path="http/src/app/config/config.service.ts" region="getConfig_1"></code-example>
The `ConfigComponent` injects the `ConfigService` and calls the `getConfig` service method.
Because the service method returns an `Observable` of configuration data, the component *subscribes* to the method's return value.
The subscription callback performs minimal post-processing.
It copies the data fields into the component's `config` object, which is data-bound in the component template for display.
<code-example header="app/config/config.component.ts (showConfig v.1)" path="http/src/app/config/config.component.ts" region="v1"></code-example>
<a id="always-subscribe"></a>
## Starting the request
For all `HttpClient` methods, the method doesn't begin its HTTP request until you call `subscribe()` on the observable the method returns.
This is true for *all* `HttpClient` *methods*.
<div class="alert is-helpful">
You should always unsubscribe from an observable when a component is destroyed.
</div>
All observables returned from `HttpClient` methods are *cold* by design.
Execution of the HTTP request is *deferred*, letting you extend the observable with additional operations such as `tap` and `catchError` before anything actually happens.
Calling `subscribe()` triggers execution of the observable and causes `HttpClient` to compose and send the HTTP request to the server.
Think of these observables as *blueprints* for actual HTTP requests.
<div class="alert is-helpful">
In fact, each `subscribe()` initiates a separate, independent execution of the observable.
Subscribing twice results in two HTTP requests.
<code-example format="javascript" language="javascript">
const req = http.get&lt;Heroes&gt;('/api/heroes');
// 0 requests made - .subscribe() not called.
req.subscribe();
// 1 request made.
req.subscribe();
// 2 requests made.
</code-example>
</div>
<a id="typed-response"></a>
## Requesting a typed response
Structure your `HttpClient` request to declare the type of the response object, to make consuming the output easier and more obvious.
Specifying the response type acts as a type assertion at compile time.
<div class="alert is-important">
Specifying the response type is a declaration to TypeScript that it should treat your response as being of the given type.
This is a build-time check and doesn't guarantee that the server actually responds with an object of this type.
It is up to the server to ensure that the type specified by the server API is returned.
</div>
To specify the response object type, first define an interface with the required properties.
Use an interface rather than a class, because the response is a plain object that cannot be automatically converted to an instance of a class.
<code-example path="http/src/app/config/config.service.ts" region="config-interface"></code-example>
Next, specify that interface as the `HttpClient.get()` call's type parameter in the service.
<code-example header="app/config/config.service.ts (getConfig v.2)" path="http/src/app/config/config.service.ts" region="getConfig_2"></code-example>
<div class="alert is-helpful">
When you pass an interface as a type parameter to the `HttpClient.get()` method, use the [RxJS `map` operator](guide/rx-library#operators) to transform the response data as needed by the UI.
You can then pass the transformed data to the [async pipe](api/common/AsyncPipe).
</div>
The callback in the updated component method receives a typed data object, which is easier and safer to consume:
<code-example header="app/config/config.component.ts (showConfig v.2)" path="http/src/app/config/config.component.ts" region="v2"></code-example>
To access properties that are defined in an interface, you must explicitly convert the plain object you get from the JSON to the required response type.
For example, the following `subscribe` callback receives `data` as an Object, and then type-casts it in order to access the properties.
<code-example format="typescript" language="typescript">
.subscribe(data =&gt; this.config = {
heroesUrl: (data as any).heroesUrl,
textfile: (data as any).textfile,
});
</code-example>
<a id="string-union-types"></a>
<div class="callout is-important">
<header><code>observe</code> and <code>response</code> types</header>
The types of the `observe` and `response` options are *string unions*, rather than plain strings.
<code-example format="typescript" language="typescript">
options: {
&hellip;
observe?: 'body' &verbar; 'events' &verbar; 'response',
&hellip;
responseType?: 'arraybuffer'&verbar;'blob'&verbar;'json'&verbar;'text',
&hellip;
}
</code-example>
This can cause confusion.
For example:
<code-example format="typescript" language="typescript">
// this works
client.get('/foo', {responseType: 'text'})
// but this does NOT work
const options = {
responseType: 'text',
};
client.get('/foo', options)
</code-example>
In the second case, TypeScript infers the type of `options` to be `{responseType: string}`.
The type is too wide to pass to `HttpClient.get` which is expecting the type of `responseType` to be one of the *specific* strings.
`HttpClient` is typed explicitly this way so that the compiler can report the correct return type based on the options you provided.
Use `as const` to let TypeScript know that you really do mean to use a constant string type:
<code-example format="typescript" language="typescript">
const options = {
responseType: 'text' as const,
};
client.get('/foo', options);
</code-example>
</div>
## Reading the full response
In the previous example, the call to `HttpClient.get()` did not specify any options.
By default, it returned the JSON data contained in the response body.
You might need more information about the transaction than is contained in the response body.
Sometimes servers return special headers or status codes to indicate certain conditions that are important to the application workflow.
Tell `HttpClient` that you want the full response with the `observe` option of the `get()` method:
<code-example path="http/src/app/config/config.service.ts" region="getConfigResponse"></code-example>
Now `HttpClient.get()` returns an `Observable` of type `HttpResponse` rather than just the JSON data contained in the body.
The component's `showConfigResponse()` method displays the response headers as well as the configuration:
<code-example header="app/config/config.component.ts (showConfigResponse)" path="http/src/app/config/config.component.ts" region="showConfigResponse"></code-example>
As you can see, the response object has a `body` property of the correct type.
@reviewed 2023-02-27
@@ -1,3 +1,35 @@
# Security: Cross-site request forgery (XSRF) protection
# HTTP client - Security: Cross-Site Request Forgery (XSRF) protection
@reviewed 2022-10-06
[Cross-Site Request Forgery (XSRF or CSRF)](https://en.wikipedia.org/wiki/Cross-site_request_forgery) is an attack technique by which the attacker can trick an authenticated user into unknowingly executing actions on your website.
`HttpClient` supports a [common mechanism](https://en.wikipedia.org/wiki/Cross-site_request_forgery#Cookie-to-header_token) used to prevent XSRF attacks.
When performing HTTP requests, an interceptor reads a token from a cookie, by default `XSRF-TOKEN`, and sets it as an HTTP header, `X-XSRF-TOKEN`.
Because only code that runs on your domain could read the cookie, the backend can be certain that the HTTP request came from your client application and not an attacker.
By default, an interceptor sends this header on all mutating requests \(such as POST\)
to relative URLs, but not on GET/HEAD requests or on requests with an absolute URL.
To take advantage of this, your server needs to set a token in a JavaScript readable session cookie called `XSRF-TOKEN` on either the page load or the first GET request.
On subsequent requests the server can verify that the cookie matches the `X-XSRF-TOKEN` HTTP header, and therefore be sure that only code running on your domain could have sent the request.
The token must be unique for each user and must be verifiable by the server; this prevents the client from making up its own tokens.
Set the token to a digest of your site's authentication cookie with a salt for added security.
To prevent collisions in environments where multiple Angular apps share the same domain or subdomain, give each application a unique cookie name.
<div class="alert is-important">
*`HttpClient` supports only the client half of the XSRF protection scheme.*
Your backend service must be configured to set the cookie for your page, and to verify that the header is present on all eligible requests.
Failing to do so renders Angular's default protection ineffective.
</div>
## Configure custom cookie/header names
If your backend service uses different names for the XSRF token cookie or header, use `HttpClientXsrfModule.withOptions()` to override the defaults.
<code-example path="http/src/app/app.module.ts" region="xsrf"></code-example>
<a id="testing-requests"></a>
@reviewed 2022-11-14
+86 -2
View File
@@ -1,3 +1,87 @@
# Send data to a server
# HTTP: Send data to a server
@reviewed 2022-10-06
In addition to fetching data from a server, `HttpClient` supports other HTTP methods such as PUT, POST, and DELETE, which you can use to modify the remote data.
The sample app for this guide includes an abridged version of the "Tour of Heroes" example that fetches heroes and enables users to add, delete, and update them.
The following sections show examples of the data-update methods from the sample's `HeroesService`.
## Make a POST request
Apps often send data to a server with a POST request when submitting a form.
In the following example, the `HeroesService` makes an HTTP POST request when adding a hero to the database.
<code-example header="app/heroes/heroes.service.ts (addHero)" path="http/src/app/heroes/heroes.service.ts" region="addHero"></code-example>
The `HttpClient.post()` method is similar to `get()` in that it has a type parameter, which you can use to specify that you expect the server to return data of a given type.
The method takes a resource URL and two additional parameters:
| Parameter | Details |
|:--- |:--- |
| body | The data to POST in the body of the request. |
| options | An object containing method options which, in this case, specify required headers. |
The example catches errors as [described above](guide/http-handle-request-errors#error-details).
The `HeroesComponent` initiates the actual POST operation by subscribing to the `Observable` returned by this service method.
<code-example header="app/heroes/heroes.component.ts (addHero)" path="http/src/app/heroes/heroes.component.ts" region="add-hero-subscribe"></code-example>
When the server responds successfully with the newly added hero, the component adds that hero to the displayed `heroes` list.
## Make a DELETE request
This application deletes a hero with the `HttpClient.delete` method by passing the hero's ID in the request URL.
<code-example header="app/heroes/heroes.service.ts (deleteHero)" path="http/src/app/heroes/heroes.service.ts" region="deleteHero"></code-example>
The `HeroesComponent` initiates the actual DELETE operation by subscribing to the `Observable` returned by this service method.
<code-example header="app/heroes/heroes.component.ts (deleteHero)" path="http/src/app/heroes/heroes.component.ts" region="delete-hero-subscribe"></code-example>
The component isn't expecting a result from the delete operation, so it subscribes without a callback.
Even though you are not using the result, you still have to subscribe.
Calling the `subscribe()` method *executes* the observable, which is what initiates the DELETE request.
<div class="alert is-important">
You must call `subscribe()` or nothing happens.
Just calling `HeroesService.deleteHero()` does not initiate the DELETE request.
</div>
<code-example path="http/src/app/heroes/heroes.component.ts" region="delete-hero-no-subscribe"></code-example>
## Make a PUT request
An app can send PUT requests using the HTTP client service.
The following `HeroesService` example, like the POST example, replaces a resource with updated data.
<code-example header="app/heroes/heroes.service.ts (updateHero)" path="http/src/app/heroes/heroes.service.ts" region="updateHero"></code-example>
As for any of the HTTP methods that return an observable, the caller, `HeroesComponent.update()` [must `subscribe()`](guide/http-request-data-from-server#always-subscribe "Why you must always subscribe.") to the observable returned from the `HttpClient.put()` in order to initiate the request.
## Add and updating headers
Many servers require extra headers for save operations.
For example, a server might require an authorization token, or "Content-Type" header to explicitly declare the MIME type of the request body.
### Add headers
The `HeroesService` defines such headers in an `httpOptions` object that are passed to every `HttpClient` save method.
<code-example header="app/heroes/heroes.service.ts (httpOptions)" path="http/src/app/heroes/heroes.service.ts" region="http-options"></code-example>
### Update headers
You can't directly modify the existing headers within the previous options
object because instances of the `HttpHeaders` class are immutable.
Use the `set()` method instead, to return a clone of the current instance with the new changes applied.
The following example shows how, when an old token expires, you can update the authorization header before making the next request.
<code-example linenums="false" path="http/src/app/heroes/heroes.service.ts" region="update-headers"></code-example>
<a id="url-params"></a>
@reviewed 2023-03-16
@@ -0,0 +1,254 @@
# HTTP Server communication
Most front-end applications need to communicate with a server over the HTTP protocol, to download or upload data and access other back-end services.
## Setup for server communication
Before you can use `HttpClient`, you need to import the Angular `HttpClientModule`.
Most apps do so in the root `AppModule`.
<code-example header="app/app.module.ts (excerpt)" path="http/src/app/app.module.ts" region="sketch"></code-example>
You can then inject the `HttpClient` service as a dependency of an application class, as shown in the following `ConfigService` example.
<code-example header="app/config/config.service.ts (excerpt)" path="http/src/app/config/config.service.ts" region="proto"></code-example>
The `HttpClient` service makes use of [observables](guide/glossary#observable "Observable definition") for all transactions.
You must import the RxJS observable and operator symbols that appear in the example snippets.
These `ConfigService` imports are typical.
<code-example header="app/config/config.service.ts (RxJS imports)" path="http/src/app/config/config.service.ts" region="rxjs-imports"></code-example>
<div class="alert is-helpful">
You can run the <live-example></live-example> that accompanies this guide.
The sample app does not require a data server.
It relies on the [Angular *in-memory-web-api*](https://github.com/angular/angular/tree/main/packages/misc/angular-in-memory-web-api), which replaces the *HttpClient* module's `HttpBackend`.
The replacement service simulates the behavior of a REST-like backend.
Look at the `AppModule` *imports* to see how it is configured.
</div>
## Requesting data from a server
Use the [`HttpClient.get()`](api/common/http/HttpClient#get) method to fetch data from a server.
The asynchronous method sends an HTTP request, and returns an Observable that emits the requested data when the response is received.
The return type varies based on the `observe` and `responseType` values that you pass to the call.
The `get()` method takes two arguments; the endpoint URL from which to fetch, and an *options* object that is used to configure the request.
<code-example format="typescript" language="typescript">
options: {
headers?: HttpHeaders &verbar; {[header: string]: string &verbar; string[]},
observe?: 'body' &verbar; 'events' &verbar; 'response',
params?: HttpParams&verbar;{[param: string]: string &verbar; number &verbar; boolean &verbar; ReadonlyArray&lt;string &verbar; number &verbar; boolean&gt;},
reportProgress?: boolean,
responseType?: 'arraybuffer'&verbar;'blob'&verbar;'json'&verbar;'text',
withCredentials?: boolean,
}
</code-example>
Important options include the *observe* and *responseType* properties.
* The *observe* option specifies how much of the response to return
* The *responseType* option specifies the format in which to return data
<div class="alert is-helpful">
Use the `options` object to configure various other aspects of an outgoing request.
In adding headers, for example, the service set the default headers using the `headers` option property.
Use the `params` property to configure a request with [TTP URL parameters, and the `reportProgress` option to listen for progress events when transferring large amounts of data.
</div>
Applications often request JSON data from a server.
In the `ConfigService` example, the app needs a configuration file on the server, `config.json`, that specifies resource URLs.
<code-example header="assets/config.json" path="http/src/assets/config.json"></code-example>
To fetch this kind of data, the `get()` call needs the following options: `{observe: 'body', responseType: 'json'}`.
These are the default values for those options, so the following examples do not pass the options object.
Later sections show some of the additional option possibilities.
<a id="config-service"></a>
The example conforms to the best practices for creating scalable solutions by defining a re-usable [injectable service](guide/glossary#service "service definition") to perform the data-handling functionality.
In addition to fetching data, the service can post-process the data, add error handling, and add retry logic.
The `ConfigService` fetches this file using the `HttpClient.get()` method.
<code-example header="app/config/config.service.ts (getConfig v.1)" path="http/src/app/config/config.service.ts" region="getConfig_1"></code-example>
The `ConfigComponent` injects the `ConfigService` and calls the `getConfig` service method.
Because the service method returns an `Observable` of configuration data, the component *subscribes* to the method's return value.
The subscription callback performs minimal post-processing.
It copies the data fields into the component's `config` object, which is data-bound in the component template for display.
<code-example header="app/config/config.component.ts (showConfig v.1)" path="http/src/app/config/config.component.ts" region="v1"></code-example>
<a id="always-subscribe"></a>
### Starting the request
For all `HttpClient` methods, the method doesn't begin its HTTP request until you call `subscribe()` on the observable the method returns.
This is true for *all* `HttpClient` *methods*.
<div class="alert is-helpful">
You should always unsubscribe from an observable when a component is destroyed.
</div>
All observables returned from `HttpClient` methods are *cold* by design.
Execution of the HTTP request is *deferred*, letting you extend the observable with additional operations such as `tap` and `catchError` before anything actually happens.
Calling `subscribe()` triggers execution of the observable and causes `HttpClient` to compose and send the HTTP request to the server.
Think of these observables as *blueprints* for actual HTTP requests.
<div class="alert is-helpful">
In fact, each `subscribe()` initiates a separate, independent execution of the observable.
Subscribing twice results in two HTTP requests.
<code-example format="javascript" language="javascript">
const req = http.get&lt;Heroes&gt;('/api/heroes');
// 0 requests made - .subscribe() not called.
req.subscribe();
// 1 request made.
req.subscribe();
// 2 requests made.
</code-example>
</div>
<a id="typed-response"></a>
### Requesting a typed response
Structure your `HttpClient` request to declare the type of the response object, to make consuming the output easier and more obvious.
Specifying the response type acts as a type assertion at compile time.
<div class="alert is-important">
Specifying the response type is a declaration to TypeScript that it should treat your response as being of the given type.
This is a build-time check and doesn't guarantee that the server actually responds with an object of this type.
It is up to the server to ensure that the type specified by the server API is returned.
</div>
To specify the response object type, first define an interface with the required properties.
Use an interface rather than a class, because the response is a plain object that cannot be automatically converted to an instance of a class.
<code-example path="http/src/app/config/config.service.ts" region="config-interface"></code-example>
Next, specify that interface as the `HttpClient.get()` call's type parameter in the service.
<code-example header="app/config/config.service.ts (getConfig v.2)" path="http/src/app/config/config.service.ts" region="getConfig_2"></code-example>
<div class="alert is-helpful">
When you pass an interface as a type parameter to the `HttpClient.get()` method, use the [RxJS `map` operator](guide/rx-library#operators) to transform the response data as needed by the UI.
You can then pass the transformed data to the [async pipe](api/common/AsyncPipe).
</div>
The callback in the updated component method receives a typed data object, which is easier and safer to consume:
<code-example header="app/config/config.component.ts (showConfig v.2)" path="http/src/app/config/config.component.ts" region="v2"></code-example>
To access properties that are defined in an interface, you must explicitly convert the plain object you get from the JSON to the required response type.
For example, the following `subscribe` callback receives `data` as an Object, and then type-casts it in order to access the properties.
<code-example format="typescript" language="typescript">
.subscribe(data =&gt; this.config = {
heroesUrl: (data as any).heroesUrl,
textfile: (data as any).textfile,
});
</code-example>
<a id="string-union-types"></a>
<div class="callout is-important">
<header><code>observe</code> and <code>response</code> types</header>
The types of the `observe` and `response` options are *string unions*, rather than plain strings.
<code-example format="typescript" language="typescript">
options: {
&hellip;
observe?: 'body' &verbar; 'events' &verbar; 'response',
&hellip;
responseType?: 'arraybuffer'&verbar;'blob'&verbar;'json'&verbar;'text',
&hellip;
}
</code-example>
This can cause confusion.
For example:
<code-example format="typescript" language="typescript">
// this works
client.get('/foo', {responseType: 'text'})
// but this does NOT work
const options = {
responseType: 'text',
};
client.get('/foo', options)
</code-example>
In the second case, TypeScript infers the type of `options` to be `{responseType: string}`.
The type is too wide to pass to `HttpClient.get` which is expecting the type of `responseType` to be one of the *specific* strings.
`HttpClient` is typed explicitly this way so that the compiler can report the correct return type based on the options you provided.
Use `as const` to let TypeScript know that you really do mean to use a constant string type:
<code-example format="typescript" language="typescript">
const options = {
responseType: 'text' as const,
};
client.get('/foo', options);
</code-example>
</div>
### Reading the full response
In the previous example, the call to `HttpClient.get()` did not specify any options.
By default, it returned the JSON data contained in the response body.
You might need more information about the transaction than is contained in the response body.
Sometimes servers return special headers or status codes to indicate certain conditions that are important to the application workflow.
Tell `HttpClient` that you want the full response with the `observe` option of the `get()` method:
<code-example path="http/src/app/config/config.service.ts" region="getConfigResponse"></code-example>
Now `HttpClient.get()` returns an `Observable` of type `HttpResponse` rather than just the JSON data contained in the body.
The component's `showConfigResponse()` method displays the response headers as well as the configuration:
<code-example header="app/config/config.component.ts (showConfigResponse)" path="http/src/app/config/config.component.ts" region="showConfigResponse"></code-example>
As you can see, the response object has a `body` property of the correct type.
@reviewed 2023-02-27
@@ -1,3 +1,30 @@
# Setup for server communication
# HTTP: Setup for server communication
@reviewed 2022-10-06
Before you can use `HttpClient`, you need to import the Angular `HttpClientModule`.
Most apps do so in the root `AppModule`.
<code-example header="app/app.module.ts (excerpt)" path="http/src/app/app.module.ts" region="sketch"></code-example>
You can then inject the `HttpClient` service as a dependency of an application class, as shown in the following `ConfigService` example.
<code-example header="app/config/config.service.ts (excerpt)" path="http/src/app/config/config.service.ts" region="proto"></code-example>
The `HttpClient` service makes use of [observables](guide/glossary#observable "Observable definition") for all transactions.
You must import the RxJS observable and operator symbols that appear in the example snippets.
These `ConfigService` imports are typical.
<code-example header="app/config/config.service.ts (RxJS imports)" path="http/src/app/config/config.service.ts" region="rxjs-imports"></code-example>
<div class="alert is-helpful">
You can run the <live-example></live-example> that accompanies this guide.
The sample app does not require a data server.
It relies on the [Angular *in-memory-web-api*](https://github.com/angular/angular/tree/main/packages/misc/angular-in-memory-web-api), which replaces the *HttpClient* module's `HttpBackend`.
The replacement service simulates the behavior of a REST-like backend.
Look at the `AppModule` *imports* to see how it is configured.
</div>
@reviewed 2022-11-03
+74 -2
View File
@@ -1,3 +1,75 @@
# Test HTTP requests
# HTTP client - Test requests
@reviewed 2022-10-06
As for any external dependency, you must mock the HTTP backend so your tests can simulate interaction with a remote server.
The `@angular/common/http/testing` library makes it straightforward to set up such mocking.
## HTTP testing library
Angular's HTTP testing library is designed for a pattern of testing in which the app executes code and makes requests first.
The test then expects that certain requests have or have not been made, performs assertions against those requests, and finally provides responses by "flushing" each expected request.
At the end, tests can verify that the app made no unexpected requests.
<div class="alert is-helpful">
You can run <live-example stackblitz="specs">these sample tests</live-example> in a live coding environment.
The tests described in this guide are in `src/testing/http-client.spec.ts`.
There are also tests of an application data service that call `HttpClient` in `src/app/heroes/heroes.service.spec.ts`.
</div>
## Setup for testing
To begin testing calls to `HttpClient`, import the `HttpClientTestingModule` and the mocking controller, `HttpTestingController`, along with the other symbols your tests require.
<code-example header="app/testing/http-client.spec.ts (imports)" path="http/src/testing/http-client.spec.ts" region="imports"></code-example>
Then add the `HttpClientTestingModule` to the `TestBed` and continue with the setup of the *service-under-test*.
<code-example header="app/testing/http-client.spec.ts(setup)" path="http/src/testing/http-client.spec.ts" region="setup"></code-example>
Now requests made in the course of your tests hit the testing backend instead of the normal backend.
This setup also calls `TestBed.inject()` to inject the `HttpClient` service and the mocking controller so they can be referenced during the tests.
## Expect and answer requests
Now you can write a test that expects a GET Request to occur and provides a mock response.
<code-example header="app/testing/http-client.spec.ts (HttpClient.get)" path="http/src/testing/http-client.spec.ts" region="get-test"></code-example>
The last step, verifying that no requests remain outstanding, is common enough for you to move it into an `afterEach()` step:
<code-example path="http/src/testing/http-client.spec.ts" region="afterEach"></code-example>
### Custom request expectations
If matching by URL isn't sufficient, it's possible to implement your own matching function.
For example, you could look for an outgoing request that has an authorization header:
<code-example path="http/src/testing/http-client.spec.ts" region="predicate"></code-example>
As with the previous `expectOne()`, the test fails if 0 or 2+ requests satisfy this predicate.
### Handle more than one request
If you need to respond to duplicate requests in your test, use the `match()` API instead of `expectOne()`.
It takes the same arguments but returns an array of matching requests.
Once returned, these requests are removed from future matching and you are responsible for flushing and verifying them.
<code-example path="http/src/testing/http-client.spec.ts" region="multi-request"></code-example>
## Test for errors
You should test the app's defenses against HTTP requests that fail.
Call `request.flush()` with an error message, as seen in the following example.
<code-example path="http/src/testing/http-client.spec.ts" region="404"></code-example>
Alternatively, call `request.error()` with a `ProgressEvent`.
<code-example path="http/src/testing/http-client.spec.ts" region="network-error"></code-example>
@reviewed 2022-11-14
@@ -1,3 +1,37 @@
# Track and show request progress
# HTTP - Track and show request progress
@reviewed 2022-10-06
Sometimes applications transfer large amounts of data and those transfers can take a long time. File uploads are a typical example. You can give the users a better experience by providing feedback on the progress of such transfers.
## Make a request
To make a request with progress events enabled, create an instance of `HttpRequest` with the `reportProgress` option set true to enable tracking of progress events.
<code-example header="app/uploader/uploader.service.ts (upload request)" path="http/src/app/uploader/uploader.service.ts" region="upload-request"></code-example>
<div class="alert is-important">
**TIP**: <br />
Every progress event triggers change detection, so only turn them on if you need to report progress in the UI.
When using `HttpClient.request()` with an HTTP method, configure the method with `observe: 'events'` to see all events, including the progress of transfers.
</div>
## Track request progress
Next, pass this request object to the `HttpClient.request()` method, which returns an `Observable` of `HttpEvents` \(the same events processed by [interceptors](guide/http-intercept-requests-and-responses#interceptor-events)\).
<code-example header="app/uploader/uploader.service.ts (upload body)" path="http/src/app/uploader/uploader.service.ts" region="upload-body"></code-example>
The `getEventMessage` method interprets each type of `HttpEvent` in the event stream.
<code-example header="app/uploader/uploader.service.ts (getEventMessage)" path="http/src/app/uploader/uploader.service.ts" region="getEventMessage"></code-example>
<div class="alert is-helpful">
The sample app for this guide doesn't have a server that accepts uploaded files.
The `UploadInterceptor` in `app/http-interceptors/upload-interceptor.ts` intercepts and short-circuits upload requests by returning an observable of simulated events.
</div>
@reviewed 2023-02-27
+20 -5
View File
@@ -2,22 +2,31 @@
To take advantage of the localization features of Angular, use the [Angular CLI][AioCliMain] to add the `@angular/localize` package to your project.
To add the `@angular/localize` package, use the following command to update the `package.json` and `polyfills.ts` files in your project.
To add the `@angular/localize` package, use the following command to update the `package.json` and TypeScript configuration files in your project.
<code-example path="i18n/doc-files/commands.sh" region="add-localize"></code-example>
It adds `types: ["@angular/localize"]` in the TypeScript configuration files as well as the reference to the type definition of `@angular/localize` at the top of the `main.ts` file.
<div class="alert is-helpful">
For more information about `package.json` and `polyfill.ts` files, see [Workspace npm dependencies][AioGuideNpmPackages].
For more information about `package.json` and `tsconfig.json` files, see [Workspace npm dependencies][AioGuideNpmPackages] and [TypeScript Configuration][AioGuideTsConfig].
</div>
If `@angular/localize` is not installed and you try to build a localized version of your project, the [Angular CLI][AioCliMain] generates an error.
If `@angular/localize` is not installed and you try to build a localized version of your project (for example, while using the `i18n` attributes in templates), the [Angular CLI][AioCliMain] will generate an error, which would contain the steps that you can take to enable i18n for your project.
<!--todo: add example error -->
## Options
| OPTION | DESCRIPTION | VALUE TYPE | DEFAULT VALUE
|:--- |:--- |:------ |:------
| `--project` | The name of the project. | `string` |
| `--use-at-runtime` | If set, then `$localize` can be used at runtime. Also `@angular/localize` gets included in the `dependencies` section of `package.json`, rather than `devDependencies`, which is the default. | `boolean` | `false`
For more available options, see [ng add][AioCliAdd] in [Angular CLI][AioCliMain].
## What's next
* [@angular/localize API][AioApiLocalize]
* [Refer to locales by ID][AioGuideI18nCommonLocaleId]
<!-- links -->
@@ -28,8 +37,14 @@ If `@angular/localize` is not installed and you try to build a localized version
[AioGuideNpmPackages]: guide/npm-packages "Workspace npm dependencies | Angular"
[AioGuideTsConfig]: guide/typescript-configuration "TypeScript Configuration | Angular"
[AioCliAdd]: cli/add "ng add | CLI | Angular"
[AioApiLocalize]: api/localize "$localize | @angular/localize - API | Angular"
<!-- external links -->
<!-- end links -->
@reviewed 2021-10-07
@reviewed 2023-03-10
@@ -92,7 +92,7 @@ To create a translation file for a locale or language, complete the following ac
<code-example language="file">
messages.xlf --&gt; message.{locale}.xlf
messages.xlf --&gt; messages.{locale}.xlf
</code-example>
+1 -1
View File
@@ -81,7 +81,7 @@ If you choose this option, make sure to turn off the `guessRoutes` option.
<code-example format="shell" language="shell">
ng run &lt;app-name&gt;:prerender --no-guess-routes --routes /product/1 /product/1
ng run &lt;app-name&gt;:prerender --no-guess-routes --routes /product/1 /product/2
</code-example>
@@ -58,7 +58,7 @@ In the `ItemListComponent` the `@Input()`, `items`, has a type of `Item[]`.
<code-example header="src/app/item-list.component.ts" path="property-binding/src/app/item-list/item-list.component.ts" region="item-input"></code-example>
Notice that `Item` is an object that it has two properties, an `id` and a `name`.
Notice that `Item` is an object and it has two properties, an `id` and a `name`.
<code-example header="src/app/item.ts" path="property-binding/src/app/item.ts" region="item-class"></code-example>
+1 -1
View File
@@ -257,7 +257,7 @@ Because a wildcard route is the least specific route, place it last in the route
</div>
To test this feature, add a button with a `RouterLink` to the `HeroListComponent` template and set the link to a non-existant route called `"/sidekicks"`.
To test this feature, add a button with a `RouterLink` to the `HeroListComponent` template and set the link to a non-existent route called `"/sidekicks"`.
<code-example header="src/app/hero-list/hero-list.component.html (excerpt)" path="router/src/app/hero-list/hero-list.component.1.html"></code-example>
+1 -1
View File
@@ -134,7 +134,7 @@ To get information from a route:
* [`ActivatedRoute`](api/router/ActivatedRoute)
* [`ParamMap`](api/router/ParamMap)
1. Inject an instance of `ActivatedRoute` by adding it to your application's constructor:
1. Inject an instance of `ActivatedRoute` by adding it to your component's constructor:
<code-example header="In the component class (excerpt)" path="router/src/app/heroes/hero-detail/hero-detail.component.ts" region="activated-route"></code-example>
+1 -1
View File
@@ -37,7 +37,7 @@ To install Angular on your local system, you need the following:
## Install the Angular CLI
You use the Angular CLI to create projects, generate application and library code, and perform a variety of ongoing development tasks such as testing, bundling, and deployment.
You can use the Angular CLI to create projects, generate application and library code, and perform a variety of ongoing development tasks such as testing, bundling, and deployment.
To install the Angular CLI, open a terminal window and run the following command:
+204
View File
@@ -0,0 +1,204 @@
# Migrate an existing Angular project to standalone
As of version 15.2.0, Angular offers a [schematic](guide/schematics) to help project authors convert existing projects to [the new standalone APIs](guide/standalone-components). The schematic aims to transform as much code as possible automatically, but it may require some manual fixes by the project author. Run the schematic with the following command:
<code-example format="shell" language="shell">
ng generate @angular/core:standalone
</code-example>
## Prerequisites
Before using the schematic, please ensure that the project:
1. Is using Angular 15.2.0 or later.
2. Builds without any compilation errors.
3. Is on a clean Git branch and all work is saved.
## Schematic options
| Option | Details |
|:--- |:--- |
| `mode` | The transformation to perform. See [Migration modes](#migration-modes) below for details on the available options. |
| `path` | The path to migrate, relative to the project root. You can use this option to migrate sections of your project incrementally. |
## Migrations steps
The migration process is composed of three steps. You'll have to run it multiple times and check manually that the project builds and behaves as expected.
<div class="callout is-helpful">
<header>Note</header>
While the schematic can automatically update most code, some edge cases require developer intervention.
You should plan to apply manual fixes after each step of the migration. Additionally, the new code generated by the schematic may not match your code's formatting rules.
</div>
Run the migration in the order listed below, verifying that your code builds and runs between each step:
1. Run `ng g @angular/core:standalone` and select "Convert all components, directives and pipes to standalone"
2. Run `ng g @angular/core:standalone` and select "Remove unnecessary NgModule classes"
3. Run `ng g @angular/core:standalone` and select "Bootstrap the project using standalone APIs"
4. Run any linting and formatting checks, fix any failures, and commit the result
## After the migration
Congratulations, your application has been converted to standalone 🎉. These are some optional follow-up steps you may want to take now:
* Find and remove any remaining `NgModule` declarations: since the ["Remove unnecessary NgModules" step](#remove-unnecessary-ngmodules) cannot remove all modules automatically, you may have to remove the remaining declarations manually.
* Run the project's unit tests and fix any failures.
* Run any code formatters, if the project uses automatic formatting.
* Run any linters in your project and fix new warnings. Some linters support a `--fix` flag that may resolve so warnings automatically.
## Migration modes
The migration has the following modes:
1. Convert declarations to standalone.
2. Remove unnecessary NgModules.
3. Switch to standalone bootstrapping API.
You should run these migrations in the order given.
### Convert declarations to standalone
In this mode, the migration converts all components, directives and pipes to standalone by setting `standalone: true` and adding dependencies to their `imports` array.
<div class="callout is-helpful">
The schematic ignores NgModules which bootstrap a component during this step because they are likely root modules used by `bootstrapModule` rather than the standalone-compatible `bootstrapApplication`. The schematic converts these declarations automatically as a part of the ["Switch to standalone bootstrapping API"](#switch-to-standalone-bootstrapping-api) step.
</div>
**Before:**
```typescript
// shared.module.ts
@NgModule({
imports: [CommonModule],
declarations: [GreeterComponent],
exports: [GreeterComponent]
})
export class SharedModule {}
```
```typescript
// greeter.component.ts
@Component({
selector: 'greeter',
template: '<div *ngIf="showGreeting">Hello</div>',
})
export class GreeterComponent {
showGreeting = true;
}
```
**After:**
```typescript
// shared.module.ts
@NgModule({
imports: [CommonModule, GreeterComponent],
exports: [GreeterComponent]
})
export class SharedModule {}
```
```typescript
// greeter.component.ts
@Component({
selector: 'greeter',
template: '<div *ngIf="showGreeting">Hello</div>',
standalone: true,
imports: [NgIf]
})
export class GreeterComponent {
showGreeting = true;
}
```
### Remove unnecessary NgModules
After converting all declarations to standalone, many NgModules can be safely removed. This step deletes such module declarations and as many corresponding references as possible. If the migration cannot delete a reference automatically, it leaves the following TODO comment so that you can delete the NgModule manually:
```typescript
/* TODO(standalone-migration): clean up removed NgModule reference manually */
```
The migration considers a module safe to remove if that module:
* Has no `declarations`.
* Has no `providers`.
* Has no `bootstrap` components.
* Has no `imports` that reference a `ModuleWithProviders` symbol or a module that can't be removed.
* Has no class members. Empty constructors are ignored.
**Before:**
```typescript
// importer.module.ts
@NgModule({
imports: [FooComponent, BarPipe],
exports: [FooComponent, BarPipe]
})
export class ImporterModule {}
```
**After:**
```typescript
// importer.module.ts
// Does not exist!
```
### Switch to standalone bootstrapping API
This step converts any usages of `bootstrapModule` to the new, standalone-based `bootstrapApplication`. It also switches the root component to `standalone: true` and deletes the root NgModule. If the root module has any `providers` or `imports`, the migration attempts to copy as much of this configuration as possible into the new bootstrap call.
**Before:**
```typescript
// ./app/app.module.ts
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule {}
```
```typescript
// ./app/app.component.ts
@Component({ selector: 'app', template: 'hello' })
export class AppComponent {}
```
```typescript
// ./main.ts
import { platformBrowser } from '@angular/platform-browser';
import { AppModule } from './app/app.module';
platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e));
```
**After:**
```typescript
// ./app/app.module.ts
// Does not exist!
```
```typescript
// ./app/app.component.ts
@Component({ selector: 'app', template: 'hello', standalone: true })
export class AppComponent {}
```
```typescript
// ./main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent).catch(e => console.error(e));
```
## Common problems
Some common problems that may prevent the schematic from working correctly include:
* Compilation errors - if the project has compilation errors, Angular cannot analyze and migrate it correctly.
* Files not included in a tsconfig - the schematic determines which files to migrate by analyzing your project's `tsconfig.json` files. The schematic excludes any files not captured by a tsconfig.
* Code that cannot be statically analyzed - the schematic uses static analysis to understand your code and determine where to make changes. The migration may skip any classes with metadata that cannot be statically analyzed at build time.
## Limitations
Due to the size and complexity of the migration, there are some cases that the schematic cannot handle:
* Because unit tests are not ahead-of-time (AoT) compiled, `imports` added to components in unit tests might not be entirely correct.
* The schematic relies on direct calls to Angular APIs. The schematic cannot recognize custom wrappers around Angular APIs. For example, if there you define a custom `customConfigureTestModule` function that wraps `TestBed.configureTestingModule`, components it declares may not be recognized.
@reviewed 2023-02-15
+2 -2
View File
@@ -20,7 +20,7 @@ For the example application that this page describes, see the <live-example name
When structural directives are applied they generally are prefixed by an asterisk, `*`, such as `*ngIf`. This convention is shorthand that Angular interprets and converts into a longer form.
Angular transforms the asterisk in front of a structural directive into an `<ng-template>` that surrounds the host element and its descendants.
For example, let's take the following code which uses an `*ngIf` to displays the hero's name if `hero` exists:
For example, let's take the following code which uses an `*ngIf` to display the hero's name if `hero` exists:
<code-example path="structural-directives/src/app/app.component.html" header="src/app/app.component.html (asterisk)" region="asterisk"></code-example>
@@ -59,7 +59,7 @@ named `$implicit`.
Angular sets `let-hero` to the value of the context's `$implicit` property, which `NgFor` has initialized with the hero for the current iteration.
For more information, see the [NgFor API](api/common/NgForOf "API: NgFor") and [NgForOf API](api/common/NgForOf) documentation.
For more information, see the [NgFor API](api/common/NgFor "API: NgFor") and [NgForOf API](api/common/NgForOf) documentation.
<div class="alert is-helpful">
+10 -120
View File
@@ -812,22 +812,13 @@ Testing the `DashboardComponent` seemed daunting in part because it involves the
<code-example header="app/dashboard/dashboard.component.ts (constructor)" path="testing/src/app/dashboard/dashboard.component.ts" region="ctor"></code-example>
Mocking the `HeroService` with a spy is a [familiar story](#component-with-async-service).
But the `Router` has a complicated API and is entwined with other services and application preconditions.
Might it be difficult to mock?
Fortunately, not in this case because the `DashboardComponent` isn't doing much with the `Router`
<code-example header="app/dashboard/dashboard.component.ts (goToDetail)" path="testing/src/app/dashboard/dashboard.component.ts" region="goto-detail" ></code-example>
This is often the case with *routing components*.
As a rule you test the component, not the router, and care only if the component navigates with the right address under the given conditions.
Angular provides test helpers to reduce boilerplate and more effectively test code which depends on the Router and HttpClient.
Providing a router spy for *this component* test suite happens to be as easy as providing a `HeroService` spy.
<code-example header="app/dashboard/dashboard.component.spec.ts" path="testing/src/app/dashboard/dashboard.component.spec.ts" region="router-harness"></code-example>
<code-example header="app/dashboard/dashboard.component.spec.ts (spies)" path="testing/src/app/dashboard/dashboard.component.spec.ts" region="router-spy"></code-example>
The following test clicks the displayed hero and confirms that `Router.navigateByUrl` is called with the expected url.
The following test clicks the displayed hero and confirms that we navigate to the expected URL.
<code-example header="app/dashboard/dashboard.component.spec.ts (navigate test)" path="testing/src/app/dashboard/dashboard.component.spec.ts" region="navigate-test"></code-example>
@@ -863,36 +854,9 @@ The [ActivatedRoute in action](guide/router-tutorial-toh#activated-route-in-acti
</div>
Tests can explore how the `HeroDetailComponent` responds to different `id` parameter values by manipulating the `ActivatedRoute` injected into the component's constructor.
Tests can explore how the `HeroDetailComponent` responds to different `id` parameter values by navigating to different routes.
You know how to spy on the `Router` and a data service.
You'll take a different approach with `ActivatedRoute` because
* `paramMap` returns an `Observable` that can emit more than one value during a test
* You need the router helper function, `convertToParamMap()`, to create a `ParamMap`
* Other *routed component* tests need a test double for `ActivatedRoute`
These differences argue for a re-usable stub class.
#### `ActivatedRouteStub`
The following `ActivatedRouteStub` class serves as a test double for `ActivatedRoute`.
<code-example header="testing/activated-route-stub.ts (ActivatedRouteStub)" path="testing/src/testing/activated-route-stub.ts" region="activated-route-stub"></code-example>
Consider placing such helpers in a `testing` folder sibling to the `app` folder.
This sample puts `ActivatedRouteStub` in `testing/activated-route-stub.ts`.
<div class="alert is-helpful">
Consider writing a more capable version of this stub class with the [*marble testing library*](#marble-testing).
</div>
<a id="tests-w-test-double"></a>
#### Testing with `ActivatedRouteStub`
#### Testing with the `RouterTestingHarness`
Here's a test demonstrating the component's behavior when the observed `id` refers to an existing hero:
@@ -907,21 +871,12 @@ Rely on your intuition for now.
When the `id` cannot be found, the component should re-route to the `HeroListComponent`.
The test suite setup provided the same router spy [described above](#routing-component) which spies on the router without actually navigating.
The test suite setup provided the same router harness [described above](#routing-component).
This test expects the component to try to navigate to the `HeroListComponent`.
<code-example header="app/hero/hero-detail.component.spec.ts (bad id)" path="testing/src/app/hero/hero-detail.component.spec.ts" region="route-bad-id"></code-example>
While this application doesn't have a route to the `HeroDetailComponent` that omits the `id` parameter, it might add such a route someday.
The component should do something reasonable when there is no `id`.
In this implementation, the component should create and display a new hero.
New heroes have `id=0` and a blank `name`.
This test confirms that the component behaves as expected:
<code-example header="app/hero/hero-detail.component.spec.ts (no id)" path="testing/src/app/hero/hero-detail.component.spec.ts" region="route-no-id" ></code-example>
## Nested component tests
Component templates often have nested components, whose templates might contain more components.
@@ -932,8 +887,6 @@ The `AppComponent`, for example, displays a navigation bar with anchors and thei
<code-example header="app/app.component.html" path="testing/src/app/app.component.html"></code-example>
While the `AppComponent` *class* is empty, you might want to write unit tests to confirm that the links are wired properly to the `RouterLink` directives, perhaps for the reasons as explained in the [following section](#why-stubbed-routerlink-tests).
To validate the links, you don't need the `Router` to navigate and you don't need the `<router-outlet>` to mark where the `Router` inserts *routed components*.
The `BannerComponent` and `WelcomeComponent` \(indicated by `<app-banner>` and `<app-welcome>`\) are also irrelevant.
@@ -966,8 +919,6 @@ Then declare them in the `TestBed` configuration next to the components, directi
The `AppComponent` is the test subject, so of course you declare the real version.
The `RouterLinkDirectiveStub`, [described later](#routerlink), is a test version of the real `RouterLink` that helps with the link tests.
The rest are stubs.
<a id="no-errors-schema"></a>
@@ -980,7 +931,7 @@ In the second approach, add `NO_ERRORS_SCHEMA` to the `TestBed.schemas` metadata
The `NO_ERRORS_SCHEMA` tells the Angular compiler to ignore unrecognized elements and attributes.
The compiler recognizes the `<app-root>` element and the `routerLink` attribute because you declared a corresponding `AppComponent` and `RouterLinkDirectiveStub` in the `TestBed` configuration.
The compiler recognizes the `<app-root>` element and the `routerLink` attribute because you declared a corresponding `AppComponent` and `RouterLink` in the `TestBed` configuration.
But the compiler won't throw an error when it encounters `<app-banner>`, `<app-welcome>`, or `<router-outlet>`.
It simply renders them as empty tags and the browser ignores them.
@@ -1003,31 +954,7 @@ In practice you will combine the two techniques in the same setup, as seen in th
<code-example header="app/app.component.spec.ts (mixed setup)" path="testing/src/app/app.component.spec.ts" region="mixed-setup"></code-example>
The Angular compiler creates the `BannerStubComponent` for the `<app-banner>` element and applies the `RouterLinkStubDirective` to the anchors with the `routerLink` attribute, but it ignores the `<app-welcome>` and `<router-outlet>` tags.
<a id="routerlink"></a>
## Components with `RouterLink`
The real `RouterLinkDirective` is quite complicated and entangled with other components and directives of the `RouterModule`.
It requires challenging setup to mock and use in tests.
The `RouterLinkDirectiveStub` in this sample code replaces the real directive with an alternative version designed to validate the kind of anchor tag wiring seen in the `AppComponent` template.
<code-example header="testing/router-link-directive-stub.ts (RouterLinkDirectiveStub)" path="testing/src/testing/router-link-directive-stub.ts" region="router-link"></code-example>
The URL bound to the `[routerLink]` attribute flows in to the directive's `linkParams` property.
The `HostListener` wires the click event of the host element \(the `<a>` anchor elements in `AppComponent`\) to the stub directive's `onClick` method.
Clicking the anchor should trigger the `onClick()` method, which sets the stub's telltale `navigatedTo` property.
Tests inspect `navigatedTo` to confirm that clicking the anchor sets the expected route definition.
<div class="alert is-helpful">
Whether the router is configured properly to navigate with that route definition is a question for a separate set of tests.
</div>
The Angular compiler creates the `BannerStubComponent` for the `<app-banner>` element and applies the `RouterLink` to the anchors with the `routerLink` attribute, but it ignores the `<app-welcome>` and `<router-outlet>` tags.
<a id="by-directive"></a>
<a id="inject-directive"></a>
@@ -1054,39 +981,6 @@ Here are some tests that confirm those links are wired to the `routerLink` direc
<code-example header="app/app.component.spec.ts (selected tests)" path="testing/src/app/app.component.spec.ts" region="tests"></code-example>
<div class="alert is-helpful">
The "click" test *in this example* is misleading.
It tests the `RouterLinkDirectiveStub` rather than the *component*.
This is a common failing of directive stubs.
It has a legitimate purpose in this guide.
It demonstrates how to find a `RouterLink` element, click it, and inspect a result, without engaging the full router machinery.
This is a skill you might need to test a more sophisticated component, one that changes the display, re-calculates parameters, or re-arranges navigation options when the user clicks the link.
</div>
<a id="why-stubbed-routerlink-tests"></a>
#### What good are these tests?
Stubbed `RouterLink` tests can confirm that a component with links and an outlet is set up properly, that the component has the links it should have, and that they are all pointing in the expected direction.
These tests do not concern whether the application will succeed in navigating to the target component when the user clicks a link.
Stubbing the RouterLink and RouterOutlet is the best option for such limited testing goals.
Relying on the real router would make them brittle.
They could fail for reasons unrelated to the component.
For example, a navigation guard could prevent an unauthorized user from visiting the `HeroListComponent`.
That's not the fault of the `AppComponent` and no change to that component could cure the failed test.
A *different* battery of tests can explore whether the application navigates as expected in the presence of conditions that influence guards such as whether the user is authenticated and authorized.
<div class="alert is-helpful">
A future guide update explains how to write such tests with the `RouterTestingModule`.
</div>
<a id="page-object"></a>
## Use a `page` object
@@ -1126,9 +1020,6 @@ A `createComponent` method creates a `page` object and fills in the blanks once
<code-example header="app/hero/hero-detail.component.spec.ts (createComponent)" path="testing/src/app/hero/hero-detail.component.spec.ts" region="create-component"></code-example>
The [`HeroDetailComponent` tests](#tests-w-test-double) in an earlier section demonstrate how `createComponent` and `page` keep the tests short and *on message*.
There are no distractions: no waiting for promises to resolve and no searching the DOM for element values to compare.
Here are a few more `HeroDetailComponent` tests to reinforce the point.
<code-example header="app/hero/hero-detail.component.spec.ts (selected tests)" path="testing/src/app/hero/hero-detail.component.spec.ts" region="selected-tests"></code-example>
@@ -1263,8 +1154,8 @@ In addition to the support it receives from the default testing module `CommonMo
* `NgModel` and friends in the `FormsModule` to enable two-way data binding
* The `TitleCasePipe` from the `shared` folder
* The Router services that these tests are stubbing out
* The Hero data access services that are also stubbed out
* The Router services
* The Hero data access services
One approach is to configure the testing module from the individual pieces as in this example:
@@ -1297,7 +1188,6 @@ Try a test configuration that imports the `HeroModule` like this one:
<code-example header="app/hero/hero-detail.component.spec.ts (HeroModule setup)" path="testing/src/app/hero/hero-detail.component.spec.ts" region="setup-hero-module"></code-example>
That's *really* crisp.
Only the *test doubles* in the `providers` remain.
Even the `HeroDetailComponent` declaration is gone.
@@ -1,3 +1,28 @@
# Understanding communicating with backend services using HTTP
@reviewed 2022-10-06
Most front-end applications need to communicate with a server over the HTTP protocol, to download or upload data and access other back-end services. Angular provides a client HTTP API for Angular applications, the `HttpClient` service class in `@angular/common/http`.
## Prerequisites
Before working with the `HttpClientModule`, you should have a basic understanding of the following:
* TypeScript programming
* Usage of the HTTP protocol
* Angular application-design fundamentals, as described in [Angular Concepts](guide/architecture)
* Observable techniques and operators.
See the [Observables guide](guide/observables).
## HTTP client service features
The HTTP client service offers the following major features.
* The ability to request [typed response objects](guide/http-request-data-from-server)
* Streamlined [error handling](guide/http-handle-request-errors)
* [Testability](guide/http-test-requests) features
* Request and response [interception](guide/http-intercept-requests-and-responses)
## What's next
* [Setup for server communication](guide/http-server-communication)
@reviewed 2023-03-14
-3
View File
@@ -112,9 +112,6 @@ If you throttle your network speed so that the client-side scripts take longer t
* The search box on the Dashboard page is ignored
* The *Back* and *Save* buttons on the Details page don't work
User events other than `routerLink` clicks aren't supported.
You must wait for the full client application to bootstrap and run, or buffer the events using libraries like [preboot](https://github.com/angular/preboot), which lets you replay these events once the client-side scripts load.
The transition from the server-rendered application to the client application happens quickly on a development machine, but you should always test your applications in real-world scenarios.
You can simulate a slower network to see the transition more clearly as follows:
+57
View File
@@ -0,0 +1,57 @@
# Version compatibility
The following tables describe the versions of Node.js, TypeScript, and RxJS that each version of Angular requires. This information is collected from Angular's [package.json](https://unpkg.com/browse/@angular/core/package.json) file.
## Actively supported versions
This table covers [Angular versions under long-term support (LTS)](guide/releases#actively-supported-versions).
| Angular | Node.js | TypeScript | RxJS |
| ------------------ | ------------------------------------ | -------------- | ------------------ |
| 15.2.x | ^14.20.0 \|\| ^16.13.0 \|\| ^18.10.0 | >=4.8.2 <5.0.0 | ^6.5.3 \|\| ^7.4.0 |
| 15.1.x | ^14.20.0 \|\| ^16.13.0 \|\| ^18.10.0 | >=4.8.2 <5.0.0 | ^6.5.3 \|\| ^7.4.0 |
| 15.0.x | ^14.20.0 \|\| ^16.13.0 \|\| ^18.10.0 | ~4.8.2 | ^6.5.3 \|\| ^7.4.0 |
| 14.3.x | ^14.15.0 \|\| ^16.10.0 | >=4.6.2 <4.9.0 | ^6.5.3 \|\| ^7.4.0 |
| 14.2.x | ^14.15.0 \|\| ^16.10.0 | >=4.6.2 <4.9.0 | ^6.5.3 \|\| ^7.4.0 |
| 14.0.x \|\| 14.1.x | ^14.15.0 \|\| ^16.10.0 | >=4.6.2 <4.8.0 | ^6.5.3 \|\| ^7.4.0 |
| 13.3.x | ^12.20.0 \|\| ^14.15.0 \|\| ^16.10.0 | >=4.4.3 <4.7.0 | ^6.5.3 \|\| ^7.4.0 |
| 13.1.x \|\| 13.2.x | ^12.20.0 \|\| ^14.15.0 \|\| ^16.10.0 | >=4.4.3 <4.6.0 | ^6.5.3 \|\| ^7.4.0 |
| 13.0.x | ^12.20.0 \|\| ^14.15.0 \|\| ^16.10.0 | ~4.4.3 | ^6.5.3 \|\| ^7.4.0 |
## Unsupported Angular versions
This table covers Angular versions that are no longer under long-term support (LTS). This information was correct when each version went out of LTS and is provided without any further guarantees. It is listed here for historical reference.
| Angular | Angular CLI | Node.js | TypeScript | RxJS |
| --------------------------- | ---------------- | ---------------------- | -------------- | ------------------ |
| 12.2.x | 12.2.x | ^12.14.0 \|\| ^14.15.0 | >=4.2.3 <4.4.0 | ^6.5.3 \|\| ^7.0.0 |
| 12.1.x | 12.1.x | ^12.14.0 \|\| ^14.15.0 | >=4.2.3 <4.4.0 | ^6.5.3 |
| 12.0.x | 12.0.x | ^12.14.0 \|\| ^14.15.0 | ~4.2.3 | ^6.5.3 |
| 11.2.x | 11.2.x | ^10.13.0 \|\| ^12.11.0 | >=4.0.0 <4.2.0 | ^6.5.3 |
| 11.1.x | 11.1.x | ^10.13.0 \|\| ^12.11.0 | >=4.0.0 <4.2.0 | ^6.5.3 |
| 11.0.x | 11.0.x | ^10.13.0 \|\| ^12.11.0 | ~4.0.0 | ^6.5.3 |
| 10.2.x | 10.2.x | ^10.13.0 \|\| ^12.11.0 | >=3.9.0 <4.1.0 | ^6.5.3 |
| 10.1.x | 10.1.x | ^10.13.0 \|\| ^12.11.0 | >=3.9.0 <4.1.0 | ^6.5.3 |
| 10.0.x | 10.0.x | ^10.13.0 \|\| ^12.11.0 | ~3.9.0 | ^6.5.3 |
| 9.1.x | 9.1.x | ^10.13.0 \|\| ^12.11.0 | >=3.6.0 <3.9.0 | ^6.5.3 |
| 9.0.x | 9.0.x | ^10.13.0 \|\| ^12.11.0 | >=3.6.0 <3.8.0 | ^6.5.3 |
| 8.2.x | 8.3.x | ^10.9.0 | >=3.5.3 <3.6.0 | ^6.4.0 |
| 8.2.x | 8.2.x | ^10.9.0 | >=3.4.2 | ^6.4.0 |
| 8.1.x | 8.1.x | ^10.9.0 | ~3.4.2 | ^6.4.0 |
| 8.0.x | 8.0.x | ^10.9.0 | ~3.4.2 | ^6.4.0 |
| 7.2.x | 7.3.x | ^8.9.0 \|\| ^10.9.0 | ~3.2.2 | ^6.0.0 |
| 7.2.x | 7.2.x | ^8.9.0 \|\| ^10.9.0 | ~3.2.2 | ^6.0.0 |
| 7.1.x | 7.1.x | ^8.9.0 \|\| ^10.9.0 | ~3.1.3 | ^6.0.0 |
| 7.0.x | 7.0.x | ^8.9.0 \|\| ^10.9.0 | ~3.1.3 | ^6.0.0 |
| 6.1.x | 6.2.x | ^8.9.0 | ~2.9.2 | ^6.0.0 |
| 6.1.x | 6.1.x | ^8.9.0 | ~2.7.2 | ^6.0.0 |
| 6.0.x | 6.0.x | ^8.9.0 | ~2.7.2 | ^6.0.0 |
| 5.2.x | 1.6.x \|\| 1.7.x | ^6.9.0 \|\| ^8.9.0 | ~2.5.0 | ^5.5.0 |
| 5.1.x | 1.5.x | ^6.9.0 \|\| ^8.9.0 | >=2.4.0 <2.6.0 | ^5.5.0 |
| 5.0.x | 1.5.x | ^6.9.0 \|\| ^8.9.0 | ~2.4.0 | ^5.5.0 |
| 4.2.x \|\| 4.3.x \|\| 4.4.x | 1.4.x | ^6.9.0 \|\| ^8.9.0 | ~2.4.0 | ^5.0.1 |
| 4.2.x \|\| 4.3.x \|\| 4.4.x | 1.3.x | ^6.9.0 | ~2.4.0 | ^5.0.1 |
| 4.0.x \|\| 4.1.x | 1.2.x | ^6.9.0 | ~2.3.0 | ^5.0.1 |
| >=4.0.0 <4.2.0 | 1.1.x | ^6.9.0 | ~2.3.0 | ^5.0.1 |
| >=4.0.0 <4.2.0 | 1.0.x | ^6.9.0 | ~2.2.0 | ^5.0.1 |
| 2.x | - | ^6.9.0 | ~2.0.0 | ^5.0.1 |
+21 -2
View File
@@ -243,12 +243,14 @@ Some extra options can only be set through the configuration file, either by dir
| `scripts` | An object containing JavaScript script files to add to the global context of the project. The scripts are loaded exactly as if you had added them in a `<script>` tag inside `index.html`. See more in the [Styles and scripts configuration](#style-script-config) section. |
| `budgets` | Default size-budget type and thresholds for all or parts of your application. You can configure the builder to report a warning or an error when the output reaches or exceeds a threshold size. See [Configure size budgets](guide/build#configure-size-budgets). \(Not available in `test` section.\) |
| `fileReplacements` | An object containing files and their compile-time replacements. See more in [Configure target-specific file replacements](guide/build#configure-target-specific-file-replacements). |
`index` | Configures the generation of the application's HTML index. See more in [Index configuration](#index-config). \(Only available in `browser` section.\) | |
<a id="complex-config"></a>
## Complex configuration values
The `assets`, `styles`, and `scripts` options can have either simple path string values, or object values with specific fields.
The `assets`, `index`, `styles`, and `scripts` options can have either simple path string values, or object values with specific fields.
The `sourceMap` and `optimization` options can be set to a simple Boolean value with a command flag. They can also be given a complex value using the configuration file.
The following sections provide more details of how these complex values are used in each case.
@@ -514,6 +516,23 @@ These are useful if you only want source maps to map error stack traces in error
</div>
<a id="index-config"></a>
### Index configuration
Configures the generation of the application's HTML index.
The `index` option can be either a String or an Object for more fine-tune configuration.
When supplying the value as a String the filename of the specified path will be used for the generated file and will be created in the root of the application's configured output path.
#### Index options
| Options | Details | Value type | Default value |
|:--- |:--- |:--- |:--- |
| `input` | The path of a file to use for the application's generated HTML index. | `string` | |
| `output` | The output path of the application's generated HTML index file. The full provided path will be used and will be considered relative to the application's configured output path. | `string` | `index.html` |
<!-- links -->
[AioGuideI18nCommonMerge]: guide/i18n-common-merge "Common Internationalization task #6: Merge translations into the application | Angular"
@@ -522,4 +541,4 @@ These are useful if you only want source maps to map error stack traces in error
<!-- end links -->
@reviewed 2022-02-28
@reviewed 2022-02-28
Binary file not shown.

After

Width:  |  Height:  |  Size: 146 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 103 KiB

+15
View File
@@ -116,6 +116,13 @@
"twitter": "armandotrue",
"bio": "Armen is a senior Angular developer from Armenia, tech writer, speaker, mentor and a Google Developer Expert for Angular."
},
"arturovt": {
"name": "Artur Androsovych",
"picture": "artur-androsovych.jpg",
"groups": ["GDE"],
"website": "https://ng-guru.io",
"bio": "Artur is an Angular expert and OSS core developer of various projects as NGXS, NG-ZORRO, single-spa, ngneat, and RxAngular. He focuses on runtime performance and has taught teams about Angular internals for the past few years."
},
"atscott": {
"name": "Andrew Scott",
"picture": "andrewscott.jpg",
@@ -601,6 +608,14 @@
"bio": "Suguru is a community-loving Frontend developer and a lead of Angular Japan User Group. He organizes the largest Angular event in Japan (ng-japan). And he is a contributor to Angular by sending patches, writing, speaking, and localizing resources in Japanese.",
"groups": ["GDE"]
},
"laranewsom": {
"name": "Lara Newsom",
"picture": "laranewsom.jpg",
"twitter": "laranerdsom",
"website": "https://www.linkedin.com/in/lara-newsom",
"bio": "Lara is a Software Engineering Technical Leader on the Customer Experience Angular Team at Cisco. She is based in Des Moines, Iowa. In addition to speaking at conferences and talking about Angular and related technologies on the Angular Plus Show Podcast, Lara loves traveling with her husband and two teens. Much to the disappointment of her own two cats, Lara also enjoys fostering orphaned kittens. ",
"groups": ["GDE"]
},
"leonardozizzamia": {
"name": "Leonardo Zizzamia",
"picture": "leonardo.jpg",
+84
View File
@@ -1132,5 +1132,89 @@
"start": "2022-12-06"
},
"name": "Angular Contributor Days"
},
{
"date": {
"start": "2023-01-24"
},
"name": "Online Meetup: The Future of Angular"
},
{
"date": {
"start": "2023-02-02"
},
"name": "Angular Zurich Meetup"
},
{
"date": {
"start": "2023-02-08"
},
"name": "JSWorld"
},
{
"date": {
"start": "2023-02-23"
},
"name": "Agent Conf"
},
{
"date": {
"start": "2023-03-24"
},
"name": "ng-be"
},
{
"date": {
"start": "2023-04-25"
},
"name": "CityJS Brazil"
},
{
"date": {
"start": "2023-05-04"
},
"name": "Devoxx Greece"
},
{
"date": {
"start": "2023-05-18"
},
"name": "JSHeroes"
},
{
"date": {
"start": "2023-05-10"
},
"name": "Google I/O"
},
{
"date": {
"start": "2023-06-01"
},
"name": "JSNation"
},
{
"date": {
"start": "2023-06-02"
},
"name": "JSConf India"
},
{
"date": {
"start": "2023-06-14"
},
"name": "ng-conf"
},
{
"date": {
"start": "2023-11-08"
},
"name": "NGPoland"
},
{
"date": {
"start": "2023-11-09"
},
"name": "JSPoland"
}
]
+3 -3
View File
@@ -1,6 +1,6 @@
<h1 class="no-toc">Your first Angular app</h1>
A few lines of TypeScript are all it takes to create your first Angular app. As you your app grows, you can separate the markup and code into different files.
A few lines of TypeScript are all it takes to create your first Angular app. As your app grows, you can separate the markup and code into different files.
## Try your first Angular app
@@ -41,7 +41,7 @@ To give your component a reset button that sets the counter back to 0:
1. Click **Add one** several times and then click **Reset**. The counter value should return to zero.
The new line adds a new `<button>` element. When the `click` event occurs in the button, the TypeScript code in the double-quotes sets the `count` property to `0`.
The new line adds a new `<button>` element. When the `click` event occurs in the button, the TypeScript code in the double quotes sets the `count` property to `0`.
You can also add styles to your new component.
@@ -55,7 +55,7 @@ You can also add styles to your new component.
</code-example>
1. The buttons in your new Angular app should now have bold text and rounded corner.
1. The buttons in your new Angular app should now have bold text and rounded corners.
### Create a new Angular app from the command line
+3 -3
View File
@@ -587,8 +587,8 @@
"resources": {
"-KLIzGEp8Mh5W-FkiQnL": {
"desc": "A no-nonsense beginner's guide to building web applications with Angular and TypeScript",
"title": "Learning Angular - Third Edition",
"url": "https://www.packtpub.com/product/learning-angular-third-edition/9781839210662"
"title": "Learning Angular - Fourth Edition",
"url": "https://www.amazon.com/dp/1803240601"
},
"3ab": {
"desc": "More than 15 books from O'Reilly about Angular",
@@ -674,7 +674,7 @@
"angular-projects": {
"title": "Angular Projects - Second Edition",
"desc": "Build modern web apps by exploring Angular with 10 different projects and cutting-edge technologies",
"url": "https://www.packtpub.com/product/angular-projects-second-edition/9781800205260"
"url": "https://www.amazon.com/dp/1800205260"
},
"rangle-angular-training-book": {
"title": "Rangle’s Angular Training Book",
+19 -3
View File
@@ -312,9 +312,20 @@
"tooltip": "A list of developer guides for building Angular applications."
},
{
"url": "guide/standalone-components",
"title": "Standalone components",
"tooltip": "Standalone components, directives, and pipes"
"title": "Standalone",
"tooltip": "Learn about Angular's standalone APIs and how to convert your application to them.",
"children": [
{
"url": "guide/standalone-components",
"title": "Standalone components",
"tooltip": "Standalone components, directives, and pipes"
},
{
"url": "guide/standalone-migration",
"title": "Migrating to standalone",
"tooltip": "Migrate your application to Angular's standalone APIs"
}
]
},
{
"title": "Change detection",
@@ -869,6 +880,11 @@
"title": "Release practices",
"tooltip": "Angular versioning, release, support, and deprecation policies and practices."
},
{
"url": "guide/versions",
"title": "Version compatibility",
"tooltip": "Angular, Node.js, TypeScript, and RxJS version compatibility."
},
{
"url": "guide/browser-support",
"title": "Browser support",
+1 -1
View File
@@ -195,7 +195,7 @@ This section walks you through creating a child component, `ProductAlertsCompone
<code-example format="shell" language="shell">
`ng generate component product-alerts`
ng generate component product-alerts
</code-example>
@@ -329,7 +329,7 @@ This template binds directly to the component's `messageService`.
The messages look better after you add the private CSS styles to `messages.component.css` as listed in one of the ["final code review"](#final-code-review) tabs below.
## Add messages to hero service
## Add MessageService to HeroesComponent
The following example shows how to display a history of each time the user clicks on a hero.
This helps when you get to the next section on [Routing](tutorial/tour-of-heroes/toh-pt5).
@@ -206,7 +206,7 @@ This `getHeroes()` returns the sliced list of heroes at positions 1 and 5, retur
To navigate to the dashboard, the router needs an appropriate route.
Import the `DashboardComponent` in the `app-routing-module.ts` file.
Import the `DashboardComponent` in the `app-routing.module.ts` file.
<code-example header="src/app/app-routing.module.ts (import DashboardComponent)" path="toh-pt5/src/app/app-routing.module.ts" region="import-dashboard"></code-example>
@@ -251,7 +251,7 @@ The user should be able to get to these details in three ways.
1. By clicking a hero in the heroes list.
1. By pasting a "deep link" URL into the browser address bar that identifies the hero to display.
This section enables navigation to the `HeroDetailComponent` and liberate it from the `HeroesComponent`.
This section enables navigation to the `HeroDetailComponent` and liberates it from the `HeroesComponent`.
### Delete *hero details* from `HeroesComponent`
@@ -299,7 +299,7 @@ The hero items in the `HeroesComponent` are `<li>` elements whose click events a
<code-example header="src/app/heroes/heroes.component.html (list with onSelect)" path="toh-pt4/src/app/heroes/heroes.component.html" region="list"></code-example>
Remove the `<li>` back to just its `*ngFor`.
Remove the inner HTML of `<li>`.
Wrap the badge and name in an anchor `<a>` element.
Add a `routerLink` attribute to the anchor that's the same as in the dashboard template.
@@ -179,10 +179,10 @@ Because each service method returns a different kind of `Observable` result, `ha
### Tap into the Observable
The `HeroService` methods taps into the flow of observable values and send a message, using the `log()` method, to the message area at the bottom of the page.
The `getHero()` method taps into the flow of observable values and sends a message, using the `log()` method, to the message area at the bottom of the page.
The RxJS `tap()` operator enables this ability by looking at the observable values, doing something with those values, and passing them along.
The `tap()` call back doesn't access the values themselves.
The `tap()` callback doesn't access the values themselves.
Here is the final version of `getHeroes()` with the `tap()` that logs the operation.
@@ -422,7 +422,7 @@ The `searchTerms` becomes an `Observable` emitting a steady stream of search ter
### Chaining RxJS operators
Passing a new search term directly to the `searchHeroes()` after every user keystroke creates excessive HTTP requests, which taxes server resources and burning through data plans.
Passing a new search term directly to the `searchHeroes()` after every user keystroke creates excessive HTTP requests, which taxes server resources and burns through data plans.
Instead, the `ngOnInit()` method pipes the `searchTerms` observable through a sequence of RxJS operators that reduce the number of calls to the `searchHeroes()`. Ultimately, this returns an observable of timely hero search results where each one is a `Hero[]`.
+9 -9
View File
@@ -55,20 +55,20 @@
},
"//engines-comment": "If applicable, also update /package.json and /aio/tools/examples/shared/package.json",
"engines": {
"node": ">=14.17.1",
"node": ">=16.14.0",
"yarn": ">=1.22.4 <2",
"npm": "Please use yarn instead of NPM to install dependencies"
},
"private": true,
"dependencies": {
"@angular/animations": "15.2.0-next.4",
"@angular/cdk": "15.2.0-next.4",
"@angular/cdk": "15.2.0-rc.0",
"@angular/common": "15.2.0-next.4",
"@angular/compiler": "15.2.0-next.4",
"@angular/core": "15.2.0-next.4",
"@angular/elements": "15.2.0-next.4",
"@angular/forms": "15.2.0-next.4",
"@angular/material": "15.2.0-next.4",
"@angular/material": "15.2.0-rc.0",
"@angular/platform-browser": "15.2.0-next.4",
"@angular/platform-browser-dynamic": "15.2.0-next.4",
"@angular/router": "15.2.0-next.4",
@@ -85,7 +85,7 @@
"@angular-eslint/eslint-plugin": "^15.0.0",
"@angular-eslint/eslint-plugin-template": "^15.0.0",
"@angular-eslint/template-parser": "^15.0.0",
"@angular/build-tooling": "https://github.com/angular/dev-infra-private-build-tooling-builds.git#8b49b0b38e67191b52367d8d0a6317d00b7d5100",
"@angular/build-tooling": "https://github.com/angular/dev-infra-private-build-tooling-builds.git#d407e91db010f9eb72370b7509fc5e841ff8818b",
"@angular/cli": "15.2.0-next.4",
"@angular/compiler-cli": "15.2.0-next.4",
"@bazel/bazelisk": "^1.7.5",
@@ -99,8 +99,8 @@
"@types/node": "^12.7.9",
"@types/trusted-types": "^2.0.2",
"@types/xregexp": "^4.3.0",
"@typescript-eslint/eslint-plugin": "5.52.0",
"@typescript-eslint/parser": "5.52.0",
"@typescript-eslint/eslint-plugin": "5.54.1",
"@typescript-eslint/parser": "5.54.1",
"archiver": "^5.3.0",
"assert": "^2.0.0",
"canonical-path": "1.0.0",
@@ -114,7 +114,7 @@
"eslint": "^8.0.0",
"eslint-plugin-import": "^2.23.4",
"eslint-plugin-jasmine": "^4.1.2",
"eslint-plugin-jsdoc": "^40.0.0",
"eslint-plugin-jsdoc": "^41.0.0",
"eslint-plugin-prefer-arrow": "^1.2.3",
"find-free-port": "^2.0.0",
"firebase-tools": "^11.0.0",
@@ -145,7 +145,7 @@
"lunr": "^2.3.9",
"npm-run-all": "^4.1.5",
"protractor": "~7.0.0",
"puppeteer-core": "19.5.2",
"puppeteer-core": "19.7.2",
"rehype-slug": "^4.0.1",
"remark": "^12.0.0",
"remark-html": "^13.0.0",
@@ -158,7 +158,7 @@
"ts-node": "^10.8.1",
"tsec": "^0.2.2",
"tslint": "~6.1.3",
"typescript": "~4.8.0",
"typescript": "~4.9.3",
"uglify-js": "^3.13.3",
"unist-util-filter": "^2.0.3",
"unist-util-source": "^3.0.0",
@@ -164,6 +164,7 @@ describe('deploy-to-firebase/pre-deploy-actions:', () => {
describe('undo.checkPayloadSize()', () => {
// This method is a no-op, so there is nothing to test.
// eslint-disable-next-line jasmine/expect-single-argument
it('does not need tests', () => expect().nothing());
});
+2 -2
View File
@@ -11,7 +11,7 @@
<header>
<mat-toolbar #appToolbar color="primary" class="app-toolbar no-print" [class.transitioning]="isTransitioning">
<mat-toolbar-row class="notification-container">
<aio-notification notificationId="survey-january-2023" expirationDate="2023-03-30" [dismissOnContentClick]="true" (dismissed)="notificationDismissed()">
<aio-notification notificationId="survey-january-2023" expirationDate="2023-02-15" [dismissOnContentClick]="true" (dismissed)="notificationDismissed()">
<a href="https://goo.gle/angular-devsat-q1-2023">
<mat-icon class="icon" svgIcon="insert_comment" aria-label="Announcement"></mat-icon>
<span class="message">Help Angular by taking a <b>quick survey</b>!</span>
@@ -67,7 +67,7 @@
<main class="sidenav-content" [id]="pageId">
<div id="main-content" tabindex="-1"></div>
<aio-mode-banner [mode]="deployment.mode" [version]="versionInfo"></aio-mode-banner>
<aio-mode-banner *ngIf="versionInfo" [mode]="deployment.mode" [version]="versionInfo"></aio-mode-banner>
<aio-doc-viewer [class.no-animations]="disableAnimations" [doc]="currentDocument" (docReady)="onDocReady()" (docRemoved)="onDocRemoved()" (docInserted)="onDocInserted()" (docRendered)="onDocRendered()">
</aio-doc-viewer>
<aio-dt *ngIf="dtOn" [(doc)]="currentDocument"></aio-dt>

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