Compare commits

...

50 Commits
8.2.6 ... 8.2.9

Author SHA1 Message Date
11d3b19b32 release: cut the v8.2.9 release 2019-10-02 11:15:13 -07:00
d96167fc54 docs: add lib build note (#32940)
PR Close #32940
2019-10-02 10:59:06 -07:00
68fed2fc28 docs(router): fix typo for "urlUpdateStrategy" (#32960)
PR Close #32960
2019-10-02 10:58:41 -07:00
57457fb7c7 fix(upgrade): fix AngularJsUrlCodec to support Safari (#32959)
Safari throws an error when the new URL() constructor is called with an
undefined base. This change checks whether the base is undefined and
then calls the corresponding version of the URL constructor.

fix(upgrade): simplify solution by replacing undefined with ''

Co-Authored-By: Pete Bacon Darwin <pete@bacondarwin.com>

Simplify solution by replacing undefined with ''

Co-Authored-By: Pete Bacon Darwin <pete@bacondarwin.com>

fix(upgrade): Avoid passing an empty string as the base as well.

Browsers other than Safari may have issues with the empty string.

PR Close #32959
2019-10-02 10:00:48 -07:00
a2fc5774a7 docs: added '>' to ng-template closing tag. (#32939)
Fixes #32931

PR Close #32939
2019-10-02 09:44:24 -07:00
c6041b985e fix(docs-infra): show hamburger button on getting started guide (#32941)
In 1c3ee4190, the `getting-started` guide/tutorial was renamed to
`start`, but the corresponding CSS class that controls the display of
the top-left hamburger (and it automatically derived based on the URL)
was not updated.

This commit updates the class to ensure that the hamburger is not hidden
when navigating to the getting started guide.

PR Close #32941
2019-10-02 09:20:23 -07:00
b45d2e0fb1 docs: add dynamic queries flag migration documentation (#32582)
PR Close #32582
2019-10-01 17:19:06 -07:00
42f7419522 docs: emphasize headers for code examples (#32938)
PR Close #32938
2019-10-01 14:45:30 -07:00
32f5241598 docs: fix capitalization in elements docs (#32917) (#32936)
PR Close #32917

PR Close #32936
2019-10-01 14:44:50 -07:00
06e72721ca docs: clarify http response type (#32817)
PR Close #32817
2019-10-01 11:00:36 -07:00
3a80069f65 docs: fix typo in creating-libraries (#32930)
PR Close #32930
2019-10-01 10:59:02 -07:00
0818e2c799 docs(service-worker): add info about recovering from degraded Driver state (#32682)
Related to #31865

PR Close #32682
2019-09-30 14:15:35 -07:00
7b8b2d4622 docs: update inline lazy loading example to use the import syntax (#32260)
PR Close #32260
2019-09-30 12:06:02 -07:00
f6526a0872 docs: add filename headers to code examples (#32701)
PR Close #32701
2019-09-30 10:28:21 -07:00
0984022192 docs: add prompts section to schematic guide (#32728)
PR Close #32728
2019-09-30 10:27:39 -07:00
bb7603104f docs: removed duplicate "compilerOptions" property (#32449) (#32911)
PR Close #32449

PR Close #32911
2019-09-30 10:26:21 -07:00
bdea243fed docs: add missing space between "Component" and "will" in guide (#32885)
Closes angular/angular#32873

PR Close #32885
2019-09-27 15:59:29 -07:00
2397144e01 docs(router): make InitialNavigation part of the public API (#32707)
`InitialNavigation` is used in `ExtraOptions`, which is already part of
the public API. Thus, `InitialNavigation` should be too. Not publicly
exporting it from `router/index.ts` seems an omission, since the type is
already annotated with the `@publicApi` JSDoc tag.

By publicly exporting `InitialNavigation`, it will also correctly appear
in the API docs on angular.io.

PR Close #32707
2019-09-27 14:21:14 -07:00
466c754cc8 docs: fix typo in deployment guide (#32777)
The typo causes most of the callout to not appear on the page. The issue 
appears at the bottom of the "Lazy loading" section on the live site:
https://angular.io/guide/deployment#lazy-loading
PR Close #32777
2019-09-27 10:32:38 -07:00
45fee069d7 docs: correct spelling of HTMLTableCellElement in Template Syntax (#32805)
Spelling Correction in Docs

Corrected spelling; From `HTMLTableCellElment` to  `HTMLTableCellElement`.

PR Close #32805
2019-09-27 10:03:53 -07:00
432f7ce2a0 docs: fix sentence phrasing (#32846)
`In this section, you'll add a "Buy" button the product details page.` -> `In this section, you'll add a "Buy" button to the product details page.`
PR Close #32846
2019-09-27 10:03:23 -07:00
e8c34c47af docs: clarify sentence in lifecycle hooks doc (#32860)
PR Close #32860
2019-09-27 10:02:54 -07:00
e81fc14da1 fix(docs-infra): correctly run on IE11 (#32871)
Since 007282d2b, [TocService][1] uses [forEach()][2] to iterate over a
`NodeList`. This breaks in IE11, which does not support
`NodeList#forEach()`.

This commit wraps the returned `NodeList` in a regular `Array` to have
access to array methods (such as `forEach()`).

Fixes #32832

[1]: https://github.com/angular/angular/blob/fbad4ff65/aio/src/app/shared/toc.service.ts#L68
[2]: https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach

PR Close #32871
2019-09-26 17:05:39 -07:00
d5c210a2e1 docs: added link to ngRuAir podcast (#32223)
PR Close #32223
2019-09-26 07:37:55 -07:00
7dbde6f570 docs: remove extra parenthesis from inline animations snippet (#32735)
PR Close #32735
2019-09-25 12:05:22 -07:00
78de6211e3 release: cut the v8.2.8 release 2019-09-25 10:08:33 -07:00
104c786b90 docs: removed duplicated spaces in upgrade guide (#32813)
PR Close #32813
2019-09-24 14:01:43 -07:00
9680f4c991 docs: fix typo in upgrade guide (#32807)
PR Close #32807
2019-09-24 14:01:19 -07:00
e63390daf8 docs: correct default for router extra option (#32702)
PR Close #32702
2019-09-23 14:24:21 -07:00
af99f9e98e docs: edit copy on getting started step 1 (#32773)
PR Close #32773
2019-09-19 14:20:51 -07:00
8398f9d54c docs: edit copy on first step of getting started (#32751)
PR Close #32751
2019-09-18 13:37:00 -07:00
da5d91b97b release: cut the v8.2.7 release 2019-09-18 10:01:57 -07:00
ba1ef6b1a5 fix(bazel): ng_package(data) should support non-text files (#32721)
PR Close #32721
2019-09-17 15:58:43 -07:00
acebf6464e ci: build bazel saucelabs tests remotely (#32719)
PR Close #32719
2019-09-17 15:14:18 -07:00
e367aa2ca5 docs: Typo fixes in hierarchical DI guide (#32536)
Introduce minor typo fixes in the guide for hierarchical dependency injection

PR Close #32536
2019-09-17 13:37:54 -07:00
0ee2b755e2 ci: use automatic strategy selection for AngularTemplateCompile and TypeScriptCompile (#32708)
PR Close #32708
2019-09-16 16:35:54 -07:00
f213c7a643 docs: add autoprefixer backward compatability instruction (#32109)
PR Close #32109
2019-09-16 10:48:03 -07:00
947c076ff2 fix(compiler-cli): fix typo in diagnostic template info. (#32684)
Fixes #32662

PR Close #32684
2019-09-16 08:59:49 -07:00
6600bea815 ci: run ts-api-guardian test remotely on CI (#32677)
PR Close #32677
2019-09-13 15:13:45 -07:00
6cd61aeb1c ci: add @josephperrott to global approvers in CODEOWNERS (#32667)
This change aims to align the documented members in `CODEOWNERS` with
the actual members of the secret `framework-global-approvers` GitHub
team.

PR Close #32667
2019-09-13 08:55:57 -07:00
581b991432 docs: add undecorated classes migration faq (#32478)
PR Close #32478
2019-09-12 12:16:15 -07:00
4014aab300 docs: move renderer2 deprecation guide into own file (#32626)
PR Close #32626
2019-09-12 10:43:01 -07:00
b523844966 build(docs-infra): upgrade cli command docs sources to e21aeeecd (#32635)
Updating [angular#8.2.x](https://github.com/angular/angular/tree/8.2.x) from [cli-builds#8.3.x](https://github.com/angular/cli-builds/tree/8.3.x).

##
Relevant changes in [commit range](6734efe52...e21aeeecd):

**Modified**
- help/generate.json

##

PR Close #32635
2019-09-12 10:32:10 -07:00
8d322c89b7 docs: modify lazy-load module instructions for new cli flag (#32588)
PR Close #32588
2019-09-12 10:23:20 -07:00
08a7c6f0b5 ci: update codeowners to reflect GitHub team members (#32569)
PR Close #32569
2019-09-11 20:26:29 -04:00
31f06ee3f9 build: enforce proper compile mode for size-tracking test (#32613)
Ensures that the "core_all:size_test" target runs with "--define=compile=aot".
This is necessary because we don't run this test on CI currently, but if we run
it manually, we need to ensure that it runs with Ivy for proper size comparisons.

PR Close #32613
2019-09-11 20:22:29 -04:00
1c5b157f10 fix(language-service): cache module resolution (#32483)
This is a patch PR for https://github.com/angular/angular/pull/32479

This PR fixes a critical performance issue where the language
service makes a MASSIVE number of filesystem calls when performing
module resolution.
This is because there is no caching. To make matters worse, module
resolution is performed for every program change (which means every
few keystrokes trigger a massive number of fs calls).

PR Close #32483
2019-09-11 20:21:55 -04:00
38fe47316c docs: fix doc links to current version (#32566)
PR Close #32566
2019-09-11 19:27:01 -04:00
9488da0d0a docs: add header to code examples (#32563)
PR Close #32563
2019-09-11 19:26:20 -04:00
5a8c560373 docs: update CHANGELOG to include default message for 8.2.6 2019-09-11 14:06:37 -07:00
56 changed files with 1070 additions and 485 deletions

View File

@ -28,14 +28,3 @@ test --flaky_test_attempts=2
# More details on failures
build --verbose_failures=true
# We have seen some flakiness in using TS workers on CircleCI
# https://angular-team.slack.com/archives/C07DT5M6V/p1562693245183400
# > failures like `ERROR: /home/circleci/ng/packages/core/test/BUILD.bazel:5:1:
# > Compiling TypeScript (devmode) //packages/core/test:test_lib failed: Worker process did not return a WorkResponse:`
# > I saw that issue a couple times today.
# > Example job: https://circleci.com/gh/angular/angular/385517
# We expect that TypeScript compilations will parallelize wider than the number of local cores anyway
# so we should saturate remote workers with TS compilations
build --strategy=AngularTemplateCompile=local
build --strategy=TypeScriptCompile=local

View File

@ -251,6 +251,7 @@ jobs:
- *attach_workspace
- *init_environment
- *setup_circleci_bazel_config
- *setup_bazel_remote_execution
- run:
name: Run Bazel tests in saucelabs
# All web tests are contained within a single //:test_web_all target for Saucelabs

42
.github/CODEOWNERS vendored
View File

@ -44,23 +44,19 @@
# alxhub - Alex Rickabaugh
# AndrewKushnir - Andrew Kushnir
# andrewseguin - Andrew Seguin
# benlesh - Ben Lesh
# brandonroberts - Brandon Roberts
# atscott - Andrew Scott
# devversion - Paul Gschwendtner
# filipesilva - Filipe Silva
# gkalpak - George Kalpakas
# hansl - Hans Larsen
# IgorMinar - Igor Minar
# jasonaden - Jason Aden
# jenniferfell - Jennifer Fell
# JiaLiPassion - Jia Li
# josephperrott - Joey Perrott
# kapunahelewong - Kapunahele Wong
# kara - Kara Erickson
# kyliau - Keen Yee Liau
# matsko - Matias Niemelä
# mgechev - Minko Gechev
# mhevery - Misko Hevery
# ocombe - Olivier Combe
# petebacondarwin - Pete Bacon Darwin
# pkozlowski-opensource - Pawel Kozlowski
# robwormald - Rob Wormald
@ -88,9 +84,9 @@
# (secret team to avoid review requests, it also doesn't inherit from @angular/framework because nested teams can't be secret)
#
# - IgorMinar
# - josephperrott
# - kara
# - mhevery
# - alexeagle
# ===========================================================
@ -99,8 +95,8 @@
# Used for approving minor documentation-only changes that don't require engineering review.
# (secret team to avoid review requests, it also doesn't inherit from @angular/framework because nested teams can't be secret)
#
# - brandonroberts
# - gkalpak
# - kapunahelewong
# - petebacondarwin
@ -125,10 +121,9 @@
# @angular/tools-cli
# ===========================================================
#
# - alexeagle
# - filipesilva
# - hansl
# - mgechev
# - vikerman
# ===========================================================
@ -179,8 +174,7 @@
# @angular/fw-forms
# ===========================================================
#
# - kara
# - jasonaden
# - AndrewKushnir
# ===========================================================
@ -202,7 +196,7 @@
# @angular/fw-router
# ===========================================================
#
# - jasonaden
# - atscott
# ===========================================================
@ -220,7 +214,6 @@
#
# - gkalpak
# - petebacondarwin
# - jasonaden
# ===========================================================
@ -268,8 +261,8 @@
# @angular/fw-integration
# ===========================================================
#
# - alexeagle
# - IgorMinar
# - josephperrott
# - mhevery
@ -277,7 +270,6 @@
# @angular/docs-infra
# ===========================================================
#
# - brandonroberts
# - gkalpak
# - IgorMinar
# - petebacondarwin
@ -287,8 +279,6 @@
# @angular/fw-docs-intro
# ===========================================================
#
# - jenniferfell
# - brandonroberts
# - IgorMinar
# - stephenfluin
@ -297,16 +287,15 @@
# @angular/fw-docs-observables
# ===========================================================
#
# - benlesh
# - jasonaden
# - alxhub
# ===========================================================
# @angular/fw-docs-packaging
# ===========================================================
#
# - alexeagle
# - IgorMinar
# - vikerman
# ===========================================================
@ -314,10 +303,9 @@
# ===========================================================
#
# - alan-agius4
# - alexeagle
# - hansl
# - IgorMinar
# - mgechev
# - vikerman
# ===========================================================
@ -325,11 +313,9 @@
# ===========================================================
#
# - alan-agius4
# - alexeagle
# - hansl
# - IgorMinar
# - mgechev
# - vikerman
# ===========================================================
@ -855,7 +841,9 @@ testing/** @angular/fw-test
/aio/content/guide/updating.md @angular/fw-docs-packaging @angular/framework-global-approvers @angular/framework-global-approvers-for-docs-only-changes
/aio/content/guide/workspace-config.md @angular/fw-docs-packaging @angular/framework-global-approvers @angular/framework-global-approvers-for-docs-only-changes
/aio/content/guide/deprecations.md @angular/fw-docs-packaging @angular/framework-global-approvers @angular/framework-global-approvers-for-docs-only-changes
/aio/content/guide/migration-renderer.md @angular/fw-docs-packaging @angular/framework-global-approvers @angular/framework-global-approvers-for-docs-only-changes
/aio/content/guide/migration-undecorated-classes.md @angular/fw-docs-packaging @angular/framework-global-approvers @angular/framework-global-approvers-for-docs-only-changes
/aio/content/guide/migration-dynamic-flag.md @angular/fw-docs-packaging @angular/framework-global-approvers @angular/framework-global-approvers-for-docs-only-changes
# ================================================

View File

@ -1,6 +1,37 @@
<a name="8.2.9"></a>
## [8.2.9](https://github.com/angular/angular/compare/8.2.8...8.2.9) (2019-10-02)
### Bug Fixes
* **upgrade:** fix AngularJsUrlCodec to support Safari ([#32959](https://github.com/angular/angular/issues/32959)) ([57457fb](https://github.com/angular/angular/commit/57457fb))
<a name="8.2.8"></a>
## [8.2.8](https://github.com/angular/angular/compare/8.2.7...8.2.8) (2019-09-25)
This release contains various API docs improvements.
<a name="8.2.7"></a>
## [8.2.7](https://github.com/angular/angular/compare/8.2.6...8.2.7) (2019-09-18)
### Bug Fixes
* **bazel:** ng_package(data) should support non-text files ([#32721](https://github.com/angular/angular/issues/32721)) ([ba1ef6b](https://github.com/angular/angular/commit/ba1ef6b))
* **compiler-cli:** fix typo in diagnostic template info. ([#32684](https://github.com/angular/angular/issues/32684)) ([947c076](https://github.com/angular/angular/commit/947c076)), closes [#32662](https://github.com/angular/angular/issues/32662)
* **language-service:** cache module resolution ([#32483](https://github.com/angular/angular/issues/32483)) ([1c5b157](https://github.com/angular/angular/commit/1c5b157))
<a name="8.2.6"></a>
## [8.2.6](https://github.com/angular/angular/compare/8.2.5...8.2.6) (2019-09-11)
This release contains various API docs improvements.
<a name="8.2.5"></a>

View File

@ -8,13 +8,7 @@ This page discusses build-specific configuration options for Angular projects.
You can define different named build configurations for your project, such as *stage* and *production*, with different defaults.
Each named build configuration can have defaults for any of the options that apply to the various build targets, such as `build`, `serve`, and `test`. The [Angular CLI](cli) `build`, `serve`, and `test` commands can then replace files with appropriate versions for your intended target environment.
The following figure shows how a project has multiple build targets, which can be executed using the named configurations that you define.
<figure>
<img src="generated/images/guide/build/build-config-targets.gif" alt="build configurations and targets">
</figure>
Each named configuration can have defaults for any of the options that apply to the various [builder targets](guide/glossary#target), such as `build`, `serve`, and `test`. The [Angular CLI](cli) `build`, `serve`, and `test` commands can then replace files with appropriate versions for your intended target environment.
### Configure environment-specific defaults
@ -170,8 +164,9 @@ You can also configure the `serve` command to use the targeted build configurati
```
{@a size-budgets}
{@a configure-size-budgets}
## Configure size budgets
## Configuring size budgets
As applications grow in functionality, they also grow in size.
The CLI allows you to set size thresholds in your configuration to ensure that parts of your application stay within size boundaries that you define.
@ -296,10 +291,9 @@ Autoprefixer looks for the `browserslist` configuration when it prefixes your CS
See the [browserslist repo](https://github.com/browserslist/browserslist) for more examples of how to target specific browsers and versions.
<div class="alert is-helpful">
Backward compatibility
### Backward compatibility with Lighthouse
If you want to produce a progressive web app and are using [Lighthouse](https://developers.google.com/web/tools/lighthouse/) to grade the project, add the following browserslist entry to your `package.json` file, in order to eliminate the [old flexbox](https://developers.google.com/web/tools/lighthouse/audits/old-flexbox) prefixes:
If you want to produce a progressive web app and are using [Lighthouse](https://developers.google.com/web/tools/lighthouse/) to grade the project, add the following `browserslist` entry to your `package.json` file, in order to eliminate the [old flexbox](https://developers.google.com/web/tools/lighthouse/audits/old-flexbox) prefixes:
```
"browserslist": [
@ -309,7 +303,23 @@ If you want to produce a progressive web app and are using [Lighthouse](https://
]
```
</div>
### Backward compatibility with CSS grid
CSS grid layout support in Autoprefixer, which was previously on by default, is off by default in Angular 8 and higher.
To use CSS grid with IE10/11, you must explicitly enable it using the `autoplace` option.
To do this, add the following to the top of the global styles file (or within a specific css selector scope):
```
/* autoprefixer grid: autoplace /
```
or
```
/ autoprefixer grid: no-autoplace */
```
For more information, see [Autoprefixer documentation](https://autoprefixer.github.io/).
{@a proxy}

View File

@ -59,8 +59,7 @@ npm install @example/my-builder
As an example, lets create a builder that executes a shell command.
To create a builder, use the `createBuilder()` CLI Builder function, and return a `BuilderOutput` object.
```
<code-example language="typescript" header="/command/index.ts">
import { BuilderOutput, createBuilder } from '@angular-devkit/architect';
export default createBuilder(_commandBuilder);
@ -72,13 +71,13 @@ function _commandBuilder(
...
}
```
</code-example>
Now lets add some logic to it.
The following code retrieves the command and arguments from the user options, spawns the new process, and waits for the process to finish.
If the process is successful (returns a code of 0), it resolves the return value.
```
<code-example language="typescript" header="/command/index.ts">
import { BuilderOutput, createBuilder } from '@angular-devkit/architect';
import * as childProcess from 'child_process';
@ -95,7 +94,8 @@ function _commandBuilder(
});
});
}
```
</code-example>
### Handling output
@ -105,7 +105,7 @@ This also allows the builder itself to be executed in a separate process, even i
We can retrieve a Logger instance from the context.
```
<code-example language="typescript" header="/command/index.ts">
import { BuilderOutput, createBuilder, BuilderContext } from '@angular-devkit/architect';
import * as childProcess from 'child_process';
@ -130,7 +130,7 @@ function _commandBuilder(
});
}
```
</code-example>
### Progress and status reporting
@ -147,7 +147,7 @@ Use the `BuilderContext.reportStatus()` method to generate a status string of an
(Note that theres no guarantee that a long string will be shown entirely; it could be cut to fit the UI that displays it.)
Pass an empty string to remove the status.
```
<code-example language="typescript" header="/command/index.ts">
import { BuilderOutput, createBuilder, BuilderContext } from '@angular-devkit/architect';
import * as childProcess from 'child_process';
@ -174,7 +174,8 @@ function _commandBuilder(
});
});
}
```
</code-example>
## Builder input
@ -191,8 +192,7 @@ For our example builder, we expect the `options` value to be a `JsonObject` with
We can provide the following schema for type validation of these values.
<code-example language="json">
<code-example language="json" header="command/schema.json">
{
"$schema": "http://json-schema.org/schema",
"type": "object",
@ -222,7 +222,7 @@ To link our builder implementation with its schema and name, we need to create a
Create a file named `builders.json` file that looks like this.
<code-example language="json">
<code-example language="json" header="builders.json">
{
"builders": {
@ -238,7 +238,7 @@ Create a file named `builders.json` file that looks like this.
In the `package.json` file, add a `builders` key that tells the Architect tool where to find our builder definition file.
<code-example language="json">
<code-example language="json" header="package.json">
{
"name": "@example/command-runner",
@ -257,7 +257,7 @@ The first part of this is the package name (resolved using node resolution), an
Using one of our `options` is very straightforward, we did this in the previous section when we accessed `options.command`.
<code-example language="typescript">
<code-example language="typescript" header="/command/index.ts">
context.reportStatus(`Executing "${options.command}"...`);
const child = childProcess.spawn(options.command, options.args, { stdio: 'pipe' });
@ -267,14 +267,14 @@ Using one of our `options` is very straightforward, we did this in the previous
A builder must have a defined target that associates it with a specific input configuration and [project](guide/glossary#project).
Targets are defined in the `angular.json` [workspace configuration file](guide/workspace-config).
Targets are defined in the `angular.json` [CLI configuration file](guide/workspace-config).
A target specifies the builder to use, its default options configuration, and named alternative configurations.
The Architect tool uses the target definition to resolve input options for a given run.
The `angular.json` file has a section for each project, and the "architect" section of each project configures targets for builders used by CLI commands such as 'build', 'test', and 'lint'.
By default, for example, the `build` command runs the builder `@angular-devkit/build-angular:browser` to perform the build task, and passes in default option values as specified for the `build` target in `angular.json`.
By default, for example, the `build` command runs the builder `@angular-devkit/build-angular:browser` to perform the build task, and passes in default option values as specified for the `build` target in `angular.json`.
<code-example language="json">
<code-example language="json" header="angular.json">
{
"myApp": {
...
@ -361,7 +361,7 @@ npm install @example/command-runner
If we create a new project with `ng new builder-test`, the generated `angular.json` file looks something like this, with only default builder configurations.
<code-example language="json">
<code-example language="json" header="angular.json">
{
// ...
@ -413,7 +413,7 @@ We need to update the `angular.json` file to add a target for this builder to th
* The configurations key is optional, we'll leave it out for now.
<code-example language="json">
<code-example language="json" header="angular.json">
{
"projects": {
@ -493,7 +493,7 @@ Use integration testing for your builder, so that you can use the Architect sche
Heres an example of a test that runs the command builder.
The test uses the builder to run the `ls` command, then validates that it ran successfully and listed the proper files.
<code-example language="typescript">
<code-example language="typescript" header="command/index_spec.ts">
import { Architect } from '@angular-devkit/architect';
import { TestingArchitectHost } from '@angular-devkit/architect/testing';

View File

@ -188,8 +188,23 @@ You can rebuild your library whenever you make changes to it, but this extra ste
*Incremental builds* functionality improves the library-development experience.
Every time a file is changed a partial build is performed that emits the amended files.
Incremental builds can be run as a backround process in your dev environment. To take advantage of this feature add the `--watch` flag to the build command:
Incremental builds can be run as a background process in your dev environment. To take advantage of this feature add the `--watch` flag to the build command:
<code-example language="bash">
ng build my-lib --watch
</code-example>
<div class="alert is-important">
The CLI `build` command uses a different builder and invokes a different build tool for libraries than it does for applications.
* The build system for apps, `@angular-devkit/build-angular`, is based on `webpack`, and is included in all new Angular CLI projects.
* The build system for libraries is based on `ng-packagr`. It is only added to your dependencies when you add a library using `ng generate library my-lib`.
The two build systems support different things, and even where they support the same things, they do those things differently.
This means that the TypeScript source can result in different JavaScript code in a built library than it would in a built application.
For this reason, an app that depends on a library should only use TypeScript path mappings that point to the *built library*.
TypeScript path mappings should *not* point to the library source `.ts` files.
</div>

View File

@ -304,7 +304,7 @@ Configure the Angular Router to defer loading of all other modules (and their as
or by [_lazy loading_](guide/router#asynchronous-routing "Lazy loading")
them on demand.
<div class="callout is-helpful>
<div class="callout is-helpful">
<header>Don't eagerly import something from a lazy-loaded module</header>

View File

@ -321,7 +321,7 @@ In a typical Angular project, the polyfill is not used in production builds, so
{@a static-query-resolution}
### `@ViewChild()` / `@ContentChild()` static resolution as the default
See our [dedicated migration guide for static queries](guide/static-query-migration).
See the [dedicated migration guide for static queries](guide/static-query-migration).
{@a contentchild-input-together}
### `@ContentChild()` / `@Input()` used together
@ -389,6 +389,23 @@ As of Angular version 8, all `platform-webworker` APIs are deprecated.
This includes both packages: `@angular/platform-webworker` and
`@angular/platform-webworker-dynamic`.
## Angular version 9 schematics
{@a renderer-to-renderer2}
### Migrating from `Renderer` to `Renderer2`
See the [dedicated migration guide for Renderer](guide/migration-renderer).
{@a undecorated-classes}
### Migrating undecorated classes
See the [dedicated migration guide for undecorated classes](guide/migration-undecorated-classes).
{@a flag-migration}
### Dynamic queries flag migration
See the [dedicated migration guide for dynamic queries](guide/migration-dynamic-flag).
{@a removed}
## Removed APIs
@ -396,10 +413,10 @@ The following APIs have been removed starting with version 8.0.0:
| Package | API | Replacement | Notes |
| ------- | -------------- | ----------- | ----- |
| [`@angular/http`](https://v7.angular.io/api/http) | All exports | [`@angular/common/http`](https://v7.angular.io/api/common/http) | See [below](#http). |
[`@angular/http/testing`](https://v7.angular.io/api/http/testing) | All exports | [`@angular/common/http/testing`](https://v7.angular.io/api/common/http/testing) | See [below](#http). |
| `@angular/platform-browser` | [`DOCUMENT`](https://v7.angular.io/api/platform-browser/DOCUMENT) | [`DOCUMENT` in `@angular/common`](https://v7.angular.io/api/common/DOCUMENT) | Updating to version 8 with [`ng update`](cli/update) changes this automatically. |
| `@angular/core/testing` | [`TestBed.deprecatedOverrideProvider()`](https://v7.angular.io/api/core/testing/TestBed#deprecatedoverrideprovider) | [`TestBed.overrideProvider()`] (api/core/testing/TestBed#overrideprovider) | none |
| [`@angular/http`](https://v7.angular.io/api/http) | All exports | [`@angular/common/http`](api/common/http) | See [below](#http). |
[`@angular/http/testing`](https://v7.angular.io/api/http/testing) | All exports | [`@angular/common/http/testing`](api/common/http/testing) | See [below](#http). |
| `@angular/platform-browser` | [`DOCUMENT`](https://v7.angular.io/api/platform-browser/DOCUMENT) | [`DOCUMENT` in `@angular/common`](api/common/DOCUMENT) | Updating to version 8 with [`ng update`](cli/update) changes this automatically. |
| `@angular/core/testing` | [`TestBed.deprecatedOverrideProvider()`](https://v7.angular.io/api/core/testing/TestBed#deprecatedoverrideprovider) | [`TestBed.overrideProvider()`](api/core/testing/TestBed#overrideprovider) | none |
| `@angular/core/testing` | [`TestBedStatic.deprecatedOverrideProvider()`](https://v7.angular.io/api/core/testing/TestBedStatic#deprecatedoverrideprovider) | [`TestBedStatic.overrideProvider()`](api/core/testing/TestBedStatic#overrideprovider) | none |
@ -464,100 +481,3 @@ For more information about using `@angular/common/http`, see the [HttpClient gui
| --------------------- | ------------------------------------------- |
| `MockBackend` | [`HttpTestingController`](/api/common/http/testing/HttpTestingController) |
| `MockConnection` | [`HttpTestingController`](/api/common/http/testing/HttpTestingController) |
## Renderer to Renderer2 migration
### Migration Overview
The `Renderer` class has been marked as deprecated since Angular version 4. This section provides guidance on migrating from this deprecated API to the newer `Renderer2` API and what it means for your app.
### Why should I migrate to Renderer2?
The deprecated `Renderer` class has been removed in version 9 of Angular, so it's necessary to migrate to a supported API. Using `Renderer2` is the recommended strategy because it supports a similar set of functionality to `Renderer`. The API surface is quite large (with 19 methods), but the schematic should simplify this process for your applications.
### Is there action required on my end?
No. The schematic should handle most cases with the exception of `Renderer.animate()` and `Renderer.setDebugInfo()`, which already arent supported.
### What are the `__ngRendererX` methods? Why are they necessary?
Some methods either don't have exact equivalents in `Renderer2`, or they correspond to more than one expression. For example, both renderers have a `createElement()` method, but they're not equal because a call such as `renderer.createElement(parentNode, namespaceAndName)` in the `Renderer` corresponds to the following block of code in `Renderer2`:
```ts
const [namespace, name] = splitNamespace(namespaceAndName);
const el = renderer.createElement(name, namespace);
if (parentNode) {
renderer.appendChild(parentNode, el);
}
return el;
```
Migration has to guarantee that the return values of functions and types of variables stay the same. To handle the majority of cases safely, the schematic declares helper functions at the bottom of the user's file. These helpers encapsulate your own logic and keep the replacements inside your code down to a single function call. Here's an example of how the `createElement()` migration looks:
**Before:**
```ts
public createAndAppendElement() {
const el = this.renderer.createElement('span');
el.textContent = 'hello world';
return el;
}
```
**After:**
<code-example>
public createAndAppendElement() {
const el = __ngRendererCreateElement(this.renderer, this.element, 'span');
el.textContent = 'hello world';
return el;
}
// Generated code at the bottom of the file
__ngRendererCreateElement(renderer: any, parentNode: any, nameAndNamespace: any) {
const [namespace, name] = __ngRendererSplitNamespace(namespaceAndName);
const el = renderer.createElement(name, namespace);
if (parentNode) {
renderer.appendChild(parentNode, el);
}
return el;
}
__ngRendererSplitNamespace(nameAndNamespace: any) {
// returns the split name and namespace
}
</code-example>
When implementing these helper functions, the schematic ensures that they're only declared once per file and that their names are unique enough that there's a small chance of colliding with pre-existing functions in your code. The schematic also keeps their parameter types as `any` so that it doesn't have to insert extra logic that ensures that their values have the correct type.
### Im a library author. Should I run this migration?
**Library authors should definitely use this migration to move away from the `Renderer`. Otherwise, the libraries won't work with applications built with version 9.**
### Full list of method migrations
The following table shows all methods that the migration maps from `Renderer` to `Renderer2`.
|Renderer|Renderer2|
|---|---|
|`listen(renderElement, name, callback)`|`listen(renderElement, name, callback)`|
|`setElementProperty(renderElement, propertyName, propertyValue)`|`setProperty(renderElement, propertyName, propertyValue)`|
|`setText(renderNode, text)`|`setValue(renderNode, text)`|
|`listenGlobal(target, name, callback)`|`listen(target, name, callback)`|
|`selectRootElement(selectorOrNode, debugInfo?)`|`selectRootElement(selectorOrNode)`|
|`createElement(parentElement, name, debugInfo?)`|`appendChild(parentElement, createElement(name))`|
|`setElementStyle(el, style, value?)`|`value == null ? removeStyle(el, style) : setStyle(el, style, value)`
|`setElementAttribute(el, name, value?)`|`attributeValue == null ? removeAttribute(el, name) : setAttribute(el, name, value)`
|`createText(parentElement, value, debugInfo?)`|`appendChild(parentElement, createText(value))`|
|`createTemplateAnchor(parentElement)`|`appendChild(parentElement, createComment(''))`|
|`setElementClass(renderElement, className, isAdd)`|`isAdd ? addClass(renderElement, className) : removeClass(renderElement, className)`|
|`projectNodes(parentElement, nodes)`|`for (let i = 0; i < nodes.length; i<ins></ins>) { appendChild(parentElement, nodes<i>); }`|
|`attachViewAfter(node, viewRootNodes)`|`const parentElement = parentNode(node); const nextSibling = nextSibling(node); for (let i = 0; i < viewRootNodes.length; i<ins></ins>) { insertBefore(parentElement, viewRootNodes<i>, nextSibling);}`|
|`detachView(viewRootNodes)`|`for (let i = 0; i < viewRootNodes.length; i<ins></ins>) {const node = viewRootNodes<i>; const parentElement = parentNode(node); removeChild(parentElement, node);}`|
|`destroyView(hostElement, viewAllNodes)`|`for (let i = 0; i < viewAllNodes.length; i<ins></ins>) { destroyNode(viewAllNodes<i>); }`|
|`setBindingDebugInfo()`|This function is a noop in `Renderer2`.|
|`createViewRoot(hostElement)`|Should be replaced with a reference to `hostElement`|
|`invokeElementMethod(renderElement, methodName, args?)`|`(renderElement as any)<methodName>.apply(renderElement, args);`|
|`animate(element, startingStyles, keyframes, duration, delay, easing, previousPlayers?)`|Throws an error (same behavior as `Renderer.animate()`)|

View File

@ -322,6 +322,7 @@ The <code class="no-auto-link">item</code> property is `true`.
For block code snippets, we generally prefer to display code with
the Angular documentation _code-example_ component represented by the `<code-example>` tag.
The `<code-example>` tag has a `header` attribute that you use to identify the file that the example comes from. The header should be used whenever possible to establish the context of the example.
See [Code snippets and code examples](guide/docs-style-guide#code-snippets-and-code-samples) for more details.
<h3 class="no-toc">Inline code-snippets</h3>
@ -348,6 +349,8 @@ user input in a command shell or the _output_ of some process.
**Do not write inline code snippets** unless you have a good reason and the editor's permission to do so.
In all other cases, code snippets should be generated automatically from tested code samples.
For hypothetical examples such as illustrations of configuration options in a JSON file, you should still use The `<code-example>` tag with the `header` attribute to identify the context.
{@a from-code-samples}
<h3 class="no-toc">Code snippets and code samples</h3>

View File

@ -170,7 +170,7 @@ You can download the full code for the example <live-example downloadOnly>here</
Generic DOM APIs, such as `document.createElement()` or `document.querySelector()`, return an element type that is appropriate for the specified arguments. For example, calling `document.createElement('a')` will return an `HTMLAnchorElement`, which TypeScript knows has an `href` property. Similarly, `document.createElement('div')` will return an `HTMLDivElement`, which TypeScript knows has no `href` property.
When called with unknown elements, such as a custom element name (`popup-element` in our example), the methods will return a generic type, such as `HTMLELement`, since TypeScript can't infer the correct type of the returned element.
When called with unknown elements, such as a custom element name (`popup-element` in our example), the methods will return a generic type, such as `HTMLElement`, since TypeScript can't infer the correct type of the returned element.
Custom elements created with Angular extend `NgElement` (which in turn extends `HTMLElement`). Additionally, these custom elements will have a property for each input of the corresponding component. For example, our `popup-element` will have a `message` property of type `string`.
@ -194,7 +194,7 @@ aDialog.body = 'News'; // <-- ERROR: TypeScript knows there is no `body` proper
This is a good way to quickly get TypeScript features, such as type checking and autocomplete support, for you custom element. But it can get cumbersome if you need it in several places, because you have to cast the return type on every occurrence.
An alternative way, that only requires defining each custom element's type once, is augmenting the `HTMLELementTagNameMap`, which TypeScript uses to infer the type of a returned element based on its tag name (for DOM methods such as `document.createElement()`, `document.querySelector()`, etc.):
An alternative way, that only requires defining each custom element's type once, is augmenting the `HTMLElementTagNameMap`, which TypeScript uses to infer the type of a returned element based on its tag name (for DOM methods such as `document.createElement()`, `document.querySelector()`, etc.):
```ts
declare global {

View File

@ -3,7 +3,7 @@
Injectors in Angular have rules that you can leverage to
achieve the desired visibility of injectables in your apps.
By understanding these rules, you can determine in which
NgModule or component you should declare a provider.
NgModule, Component or Directive you should declare a provider.
## Two injector hierarchies
@ -592,7 +592,7 @@ its search at the `<#VIEW>` belonging to `<app-child>` (`<#VIEW>` is
included because it is injected from `@Component()`) and ends with
`<app-child>`. In this case, the `FlowerService` is resolved in the
`<app-child>`'s `providers` array with sunflower 🌻. The injector doesn't
have to look any further in the injector tree. It stops as soon as it as it
have to look any further in the injector tree. It stops as soon as it
finds the `FlowerService` and never sees the 🌺 (red hibiscus).
@ -618,7 +618,7 @@ set it up on your own, skip ahead to [Modifying service availability](guide/hier
The example app features a second service, the `AnimalService` to
demonstrate `viewProviders`.
First, create an `AnimalService` with an `emoji` property of whale 🐳:
First, create an `AnimalService` with an `emoji` property of 🐳 (whale):
<code-example path="providers-viewproviders/src/app/animal.service.ts" header="providers-viewproviders/src/app/animal.service.ts" region="animal-service">
@ -795,7 +795,7 @@ The `AnimalService` in the logical tree would look like this:
</app-root>
```
The projected content of `<app-inspector>` sees the whale 🐳, not
The projected content of `<app-inspector>` sees the 🐳 (whale), not
the 🐶 (puppy), because the
🐶 (puppy) is inside the `<app-child>` `<#VIEW>`. The `<app-inspector>` can
only see the 🐶 (puppy)

View File

@ -193,7 +193,7 @@ text messages with different descriptions (not different meanings), then they ar
The angular i18n extractor tool generates a file with a translation unit entry for each `i18n`
attribute in a template. By default, it assigns each translation unit a unique id such as this one:
<code-example path="i18n/doc-files/messages.fr.xlf.html" region="generated-id"></code-example>
<code-example path="i18n/doc-files/messages.fr.xlf.html" header="messages.fr.xlf.html" region="generated-id"></code-example>
When you change the translatable text, the extractor tool generates a new id for that translation unit.
You must then update the translation file with the new id.
@ -206,7 +206,7 @@ The example below defines the custom id `introductionHeader`:
When you specify a custom id, the extractor tool and compiler generate a translation unit with that
custom id.
<code-example path="i18n/doc-files/messages.fr.xlf.html" region="custom-id"></code-example>
<code-example path="i18n/doc-files/messages.fr.xlf.html" header="messages.fr.xlf.html" region="custom-id"></code-example>
The custom id is persistent. The extractor tool does not change it when the translatable text changes.
Therefore, you do not need to update the translation. This approach makes maintenance easier.
@ -645,9 +645,9 @@ ready-to-run application package, typically for production.
When you internationalize with the AOT compiler, you must pre-build a separate application
package for each language and serve the appropriate package based on either server-side language
detection or url parameters.
detection or URL parameters.
To instruct the AOT compiler to use your translation configuration, set the three "i18n" build configuration options in your `angular.json` file.
To instruct the AOT compiler to use your translation configuration, set the three "i18n" build configuration options in your CLI configuration file, `angular.json`.
* `i18nFile`: the path to the translation file.
* `i18nFormat`: the format of the translation file.
@ -763,6 +763,7 @@ Then provide the `LOCALE_ID` in the main module:
{@a missing-translation}
### Report missing translations
By default, when a translation is missing, the build succeeds but generates a warning such as
`Missing translation for message "foo"`. You can configure the level of warning that is generated by
the Angular compiler:
@ -772,7 +773,7 @@ compilation, the app will fail to load.
* Warning (default): show a 'Missing translation' warning in the console or shell.
* Ignore: do nothing.
You specify the warning level in the `configurations` section your Angular CLI build configuration. The example below shows how to set the warning level to error:
You specify the warning level in the `configurations` section of your Angular CLI configuration file, `angular.json`. The example below shows how to set the warning level to error.
```
"configurations": {
@ -786,7 +787,7 @@ You specify the warning level in the `configurations` section your Angular CLI b
If you use the JIT compiler, specify the warning level in the compiler config at bootstrap by adding
the 'MissingTranslationStrategy' property. The example below shows how to set the warning level to
error:
error.
<code-example path="i18n/doc-files/main.3.ts" header="src/main.ts">
</code-example>

View File

@ -5,13 +5,13 @@
By default, NgModules are eagerly loaded, which means that as soon as the app loads, so do all the NgModules, whether or not they are immediately necessary. For large apps with lots of routes, consider lazy loading&mdash;a design pattern that loads NgModules as needed. Lazy loading helps keep initial
bundle sizes smaller, which in turn helps decrease load times.
For the final sample app with two lazy loaded modules that this page describes, see the
For the final sample app with two lazy-loaded modules that this page describes, see the
<live-example></live-example>.
There are three main steps to setting up a lazy loaded feature module:
There are three main steps to setting up a lazy-loaded feature module:
1. Create the feature module.
1. Create the feature modules routing module.
1. Create the feature module with the CLI, using the `--route` flag.
1. Create the feature modules component.
1. Configure the routes.
## Set up an app
@ -21,9 +21,9 @@ create one with the CLI. If you do already have an app, skip to
[Configure the routes](#config-routes). Enter the following command
where `customer-app` is the name of your app:
```sh
<code-example language="bash">
ng new customer-app --routing
```
</code-example>
This creates an app called `customer-app` and the `--routing` flag
generates a file called `app-routing.module.ts`, which is one of
@ -32,71 +32,63 @@ Navigate into the project by issuing the command `cd customer-app`.
## Create a feature module with routing
Next, youll need a feature module to route to. To make one, enter
the following command at the terminal window prompt where `customers` is the name of the module:
Next, youll need a feature module with a component to route to.
To make one, enter the following command in the terminal, where `customers` is the name of the feature module, and `customer-list` is the route path for loading the `customers` component:
```sh
ng generate module customers --routing
```
<code-example language="bash">
ng generate module customers --route customer-list --module app.module
</code-example>
This creates a customers folder with two files inside; `CustomersModule`
and `CustomersRoutingModule`. `CustomersModule` will act as the gatekeeper
for anything that concerns customers. `CustomersRoutingModule` will handle
any customer-related routing. This keeps the apps structure organized as
the app grows and allows you to reuse this module while easily keeping its routing intact.
This creates a `customers` folder with the new lazy-loadable module `CustomersModule` defined in the file `customers.module.ts`. The command automatically adds the `CustomerComponent` to the new feature module.
The CLI imports the `CustomersRoutingModule` into the `CustomersModule` by
adding a JavaScript import statement at the top of the file and adding
`CustomersRoutingModule` to the `@NgModule` `imports` array.
Because the new module is meant to be lazy-loaded, the command does NOT add a reference for the new feature module to the root application's module file, `app.module.ts`.
Instead, it adds the declared route, `customer-list` to the `Routes` array declared in the module provided as the `--module` option.
## Add a component to the feature module
<code-example language="typescript" header="src/app/app-routing.module.ts">
const routes: Routes = [
{ path: 'customer-list',
loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule) }
];
</code-example>
In order to see the module being lazy loaded in the browser, create a component to render some HTML when the app loads `CustomersModule`. At the command line, enter the following:
Notice that the lazy-loading syntax uses `loadChildren` followed by a function that uses the browser's built-in `import('...')` syntax for dynamic imports.
The import path is the relative path to the module.
```sh
ng generate component customers/customer-list
```
### Add another feature module
This creates a folder inside of `customers` called `customer-list`
with the four files that make up the component.
Use the same command to create a second lazy-loaded feature module with routing, along with its stub component.
Just like with the routing module, the CLI imports the
`CustomerListComponent` into the `CustomersModule`.
<code-example language="bash">
ng generate module orders --route order-list --module app.module
</code-example>
This creates a new folder called `orders` containing an `OrdersModule` and `OrdersRoutingModule`, along with the new `OrderComponent` source files.
The `order-list` route is added to the `Routes` array in `app-routing.module.ts`, using the lazy-loading syntax.
## Add another feature module
For another place to route to, create a second feature module with routing:
```sh
ng generate module orders --routing
```
This makes a new folder called `orders` containing an `OrdersModule` and an `OrdersRoutingModule`.
Now, just like with the `CustomersModule`, give it some content:
```sh
ng generate component orders/order-list
```
<code-example language="typescript" header="src/app/app-routing.module.ts">
const routes: Routes = [
{ path: 'customer-list',
loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule) },
{ path: 'order-list',
loadChildren: () => import('./orders/orders.module').then(m => m.OrdersModule) }
];
</code-example>
## Set up the UI
Though you can type the URL into the address bar, a nav
is easier for the user and more common. Replace the default
placeholder markup in `app.component.html` with a custom nav
Though you can type the URL into the address bar, a navigation UI is easier for the user and more common.
Replace the default placeholder markup in `app.component.html` with a custom nav
so you can easily navigate to your modules in the browser:
<code-example path="lazy-loading-ngmodules/src/app/app.component.html" region="app-component-template" header="src/app/app.component.html"></code-example>
<code-example path="lazy-loading-ngmodules/src/app/app.component.html" header="app.component.html" region="app-component-template" header="src/app/app.component.html"></code-example>
To see your app in the browser so far, enter the following command in the terminal window:
```sh
<code-example language="bash">
ng serve
```
</code-example>
Then go to `localhost:4200` where you should see “app works!” and three buttons.
@ -104,59 +96,42 @@ Then go to `localhost:4200` where you should see “app works!” and three butt
<img src="generated/images/guide/lazy-loading-ngmodules/three-buttons.png" width="300" alt="three buttons in the browser">
</figure>
To make the buttons work, you need to configure the routing modules.
These buttons work, because the CLI automatically added the routes to the feature modules to the `routes` array in `app.module.ts`.
{@a config-routes}
## Configure the routes
The two feature modules, `OrdersModule` and `CustomersModule`, have to be
wired up to the `AppRoutingModule` so the router knows about them. The structure is as follows:
<figure>
<img src="generated/images/guide/lazy-loading-ngmodules/lazy-load-relationship.jpg" width="400" alt="lazy loaded modules diagram">
</figure>
Each feature module acts as a doorway via the router. In the `AppRoutingModule`, you configure the routes to the feature modules, in this case `OrdersModule` and `CustomersModule`. This way, the router knows to go to the feature module. The feature module then connects the `AppRoutingModule` to the `CustomersRoutingModule` or the `OrdersRoutingModule`. Those routing modules tell the router where to go to load relevant components.
### Routes at the app level
## Imports and route configuration
The CLI automatically added each feature module to the routes map at the application level.
Finish this off by adding the default route.
In `AppRoutingModule`, update the `routes` array with the following:
<code-example path="lazy-loading-ngmodules/src/app/app-routing.module.ts" id="app-routing.module.ts" region="const-routes" header="src/app/app-routing.module.ts"></code-example>
<code-example path="lazy-loading-ngmodules/src/app/app-routing.module.ts" region="const-routes" header="src/app/app-routing.module.ts"></code-example>
The first two paths are the routes to the `CustomersModule` and the `OrdersModule`.
The final entry defines a default route. The empty path matches everything that doesn't match an earlier path.
The import statements stay the same. The first two paths are the routes to the `CustomersModule` and the `OrdersModule` respectively. Notice that the lazy loading syntax uses `loadChildren` followed by a function that uses the browser's built-in `import('...')` syntax for dynamic imports. The import path is the relative path to the module.
### Inside the feature module
Next, take a look at `customers.module.ts`. If youre using the CLI and following the steps outlined in this page, you dont have to do anything here. The feature module is like a connector between the `AppRoutingModule` and the feature routing module. The `AppRoutingModule` imports the feature module, `CustomersModule`, and `CustomersModule` in turn imports the `CustomersRoutingModule`.
<code-example path="lazy-loading-ngmodules/src/app/customers/customers.module.ts" region="customers-module" header="src/app/customers/customers.module.ts"></code-example>
Next, take a look at `customers.module.ts`. If youre using the CLI and following the steps outlined in this page, you dont have to do anything here.
<code-example path="lazy-loading-ngmodules/src/app/customers/customers.module.ts" id="customers.module.ts" region="customers-module" header="src/app/customers/customers.module.ts"></code-example>
The `customers.module.ts` file imports the `CustomersRoutingModule` and `CustomerListComponent` so the `CustomersModule` class can have access to them. `CustomersRoutingModule` is then listed in the `@NgModule` `imports` array giving `CustomersModule` access to its own routing module, and `CustomerListComponent` is in the `declarations` array, which means `CustomerListComponent` belongs to the `CustomersModule`.
### Configure the feature modules routes
The feature module has its own routing module, `customers-routing.module.ts`. The `AppRoutingModule` imports the feature module, `CustomersModule`, and `CustomersModule` in turn imports the `CustomersRoutingModule`.
The next step is in `customers-routing.module.ts`. First, import the component at the top of the file with the other JavaScript import statements. Then, add the route to `CustomerListComponent`.
<code-example path="lazy-loading-ngmodules/src/app/customers/customers-routing.module.ts" region="customers-routing-module" header="src/app/customers/customers-routing.module.ts"></code-example>
The feature-specific routing module imports its own feature component, `CustomerListComponent`, along with the other JavaScript import statements. It also adds the route to its own component.
<code-example path="lazy-loading-ngmodules/src/app/customers/customers-routing.module.ts" id="customers-routing.module.ts" region="customers-routing-module" header="src/app/customers/customers-routing.module.ts"></code-example>
Notice that the `path` is set to an empty string. This is because the path in `AppRoutingModule` is already set to `customers`, so this route in the `CustomersRoutingModule`, is already within the `customers` context. Every route in this routing module is a child route.
Repeat this last step of importing the `OrdersListComponent` and configuring the Routes array for the `orders-routing.module.ts`:
The other feature module's routing module is configured similarly.
<code-example path="lazy-loading-ngmodules/src/app/orders/orders-routing.module.ts" region="orders-routing-module-detail" header="src/app/orders/orders-routing.module.ts (excerpt)"></code-example>
Now, if you view the app in the browser, the three buttons take you to each module.
<code-example path="lazy-loading-ngmodules/src/app/orders/orders-routing.module.ts" id="orders-routing.module.ts" region="orders-routing-module-detail" header="src/app/orders/orders-routing.module.ts (excerpt)"></code-example>
## Confirm its working
@ -167,7 +142,7 @@ You can check to see that a module is indeed being lazy loaded with the Chrome d
</figure>
Click on the Orders or Customers button. If you see a chunk appear, youve wired everything up properly and the feature module is being lazy loaded. A chunk should appear for Orders and for Customers but will only appear once for each.
Click on the Orders or Customers button. If you see a chunk appear, everything is wired up properly and the feature module is being lazy loaded. A chunk should appear for Orders and for Customers but will only appear once for each.
<figure>
@ -186,17 +161,17 @@ Then reload with `Cmd+r` or `Ctrl+r`, depending on your platform.
## `forRoot()` and `forChild()`
You might have noticed that the CLI adds `RouterModule.forRoot(routes)` to the `app-routing.module.ts` `imports` array. This lets Angular know that this module,
`AppRoutingModule`, is a routing module and `forRoot()` specifies that this is the root
routing module. It configures all the
routes you pass to it, gives you access to the router directives, and registers the `RouterService`.
You might have noticed that the CLI adds `RouterModule.forRoot(routes)` to the `app-routing.module.ts` `imports` array.
This lets Angular know that this module, `AppRoutingModule`, is a routing module and `forRoot()` specifies that this is the root routing module.
It configures all the routes you pass to it, gives you access to the router directives, and registers the `RouterService`.
Use `forRoot()` in the `AppRoutingModule`&mdash;that is, one time in the app at the root level.
The CLI also adds `RouterModule.forChild(routes)` to feature routing modules. This way, Angular
knows that the route list is only responsible for providing additional routes and is intended for feature modules. You can use `forChild()` in multiple modules.
`forRoot()` contains injector configuration which is global; such as configuring the Router. `forChild()` has no injector configuration, only directives such as `RouterOutlet` and `RouterLink`.
The CLI also adds `RouterModule.forChild(routes)` to feature routing modules.
This way, Angular knows that the route list is only responsible for providing additional routes and is intended for feature modules.
You can use `forChild()` in multiple modules.
The `forRoot()` method takes care of the *global* injector configuration for the Router.
The `forChild()` method has no injector configuration. It uses directives such as `RouterOutlet` and `RouterLink`.
For more information, see the [`forRoot()` pattern](guide/singleton-services#forRoot) section of the [Singleton Services](guide/singleton-services) guide.
<hr>
@ -209,4 +184,3 @@ You may also be interested in the following:
* [Types of Feature Modules](guide/module-types).
* [Route-level code-splitting in Angular](https://web.dev/route-level-code-splitting-in-angular/)
* [Route preloading strategies in Angular](https://web.dev/route-preloading-in-angular/)

View File

@ -2,8 +2,7 @@
A component has a lifecycle managed by Angular.
Angular creates it, renders it, creates and renders its children,
checks it when its data-bound properties change, and destroys it before removing it from the DOM.
Angular creates and renders components along with their children, checks when their data-bound properties change, and destroys them before removing them from the DOM.
Angular offers **lifecycle hooks**
that provide visibility into these key life moments and the ability to act when they occur.

View File

@ -0,0 +1,107 @@
# Dynamic queries flag migration
## What does this migration do?
In Angular version 8, a schematic added `static` flags to all `@ViewChild()`
and `@ContentChild()` queries.
This was the first step towards changing the default behavior.
With version 9, the default value
changes to `static: false` and the flag becomes optional.
This schematic scans classes in the compilation and for each
class, checks if the members have a `@ViewChild()` or
`@ContentChild()` query with the `static` flag set to
`false`. If so, the schematic removes the flag, as it
now matches the default.
**Before:**
```ts
@ViewChild('foo', {static: false}) foo: ElementRef;
@ViewChild('bar', {static: true}) bar: ElementRef;
```
**After:**
```ts
@ViewChild('foo') foo: ElementRef;
// this query doesn't change because the static value is true
@ViewChild('bar', {static: true}) bar: ElementRef;
```
Note that the flag is not supported in `@ViewChildren()`
or `@ContentChildren()` queries, so the schematic
will not check these properties.
## Why is this migration necessary?
This schematic performs a code cleanup to remove `static`
flags that match the default, as they are no longer
necessary. Functionally, the code change should be a noop.
Before version 9, Angular figured out the static or
dynamic nature of a query automatically, based
on how the template was written. Looking at templates
in this way, however, caused buggy and surprising behavior
(see more about that in the [Static Query Migration Guide](guide/static-query-migration#what-does-this-flag-mean)).
As of version 9, Angular uses dynamic queries
(`static: false`) by default, which simplifies
queries. Developers can still explicitly set a
query to `static: true` if necessary.
<div class=" alert is-helpful">
### What is the difference between static and dynamic queries?
The `static` option for `@ViewChild()` and `@ContentChild()`
queries determines when
the query results become available.
With static queries (`static: true`), the query resolves
once the view has been created, but before change detection runs.
The result, though, will never be updated to reflect
changes to your view, such as
changes to `ngIf` and `ngFor` blocks.
With dynamic queries (`static: false`), the query resolves
after either `ngAfterViewInit()` or
`ngAfterContentInit()` for `@ViewChild()` and `@ContentChild()`
respectively. The result will
be updated for changes to your view, such as changes to
`ngIf` and `ngFor` blocks.
For more information, see the following entries in the
[Static Query Migration Guide](https://angular.io/guide/static-query-migration):
* [How do I choose which `static` flag value to use: `true` or `false`?](https://angular.io/guide/static-query-migration#how-do-i-choose-which-static-flag-value-to-use-true-or-false)
* [Is there a case where I should use `{static: true}`?](https://angular.io/guide/static-query-migration#is-there-a-case-where-i-should-use-static-true)
</div>
## What does this mean for libraries?
In order to support applications that are still running
with version 8, the safest option for libraries is to
retain the `static` flag to keep the resolution
timing consistent.
- *Libraries on version 9 with applications running version 8: *
The schematic won't run on libraries. As long as libraries retain their `static` flags from version 8, they should work with apps on 8.
- *Libraries on version 8 with applications running version 9: *
Libraries will have explicit flags defined. The behavior
with explicit flags has not changed.
### What about applications using non-migrated libraries?
Because this is a code cleanup that is a noop,
non-migrated libraries will work the same either way.

View File

@ -0,0 +1,96 @@
# `Renderer` to `Renderer2` migration
## Migration Overview
The `Renderer` class has been marked as deprecated since Angular version 4. This section provides guidance on migrating from this deprecated API to the newer `Renderer2` API and what it means for your app.
## Why should I migrate to Renderer2?
The deprecated `Renderer` class has been removed in version 9 of Angular, so it's necessary to migrate to a supported API. Using `Renderer2` is the recommended strategy because it supports a similar set of functionality to `Renderer`. The API surface is quite large (with 19 methods), but the schematic should simplify this process for your applications.
## Is there action required on my end?
No. The schematic should handle most cases with the exception of `Renderer.animate()` and `Renderer.setDebugInfo()`, which already arent supported.
## What are the `__ngRendererX` methods? Why are they necessary?
Some methods either don't have exact equivalents in `Renderer2`, or they correspond to more than one expression. For example, both renderers have a `createElement()` method, but they're not equal because a call such as `renderer.createElement(parentNode, namespaceAndName)` in the `Renderer` corresponds to the following block of code in `Renderer2`:
```ts
const [namespace, name] = splitNamespace(namespaceAndName);
const el = renderer.createElement(name, namespace);
if (parentNode) {
renderer.appendChild(parentNode, el);
}
return el;
```
Migration has to guarantee that the return values of functions and types of variables stay the same. To handle the majority of cases safely, the schematic declares helper functions at the bottom of the user's file. These helpers encapsulate your own logic and keep the replacements inside your code down to a single function call. Here's an example of how the `createElement()` migration looks:
**Before:**
```ts
public createAndAppendElement() {
const el = this.renderer.createElement('span');
el.textContent = 'hello world';
return el;
}
```
**After:**
<code-example>
public createAndAppendElement() {
const el = __ngRendererCreateElement(this.renderer, this.element, 'span');
el.textContent = 'hello world';
return el;
}
// Generated code at the bottom of the file
__ngRendererCreateElement(renderer: any, parentNode: any, nameAndNamespace: any) {
const [namespace, name] = __ngRendererSplitNamespace(namespaceAndName);
const el = renderer.createElement(name, namespace);
if (parentNode) {
renderer.appendChild(parentNode, el);
}
return el;
}
__ngRendererSplitNamespace(nameAndNamespace: any) {
// returns the split name and namespace
}
</code-example>
When implementing these helper functions, the schematic ensures that they're only declared once per file and that their names are unique enough that there's a small chance of colliding with pre-existing functions in your code. The schematic also keeps their parameter types as `any` so that it doesn't have to insert extra logic that ensures that their values have the correct type.
### Im a library author. Should I run this migration?
**Library authors should definitely use this migration to move away from the `Renderer`. Otherwise, the libraries won't work with applications built with version 9.**
### Full list of method migrations
The following table shows all methods that the migration maps from `Renderer` to `Renderer2`.
|Renderer|Renderer2|
|---|---|
|`listen(renderElement, name, callback)`|`listen(renderElement, name, callback)`|
|`setElementProperty(renderElement, propertyName, propertyValue)`|`setProperty(renderElement, propertyName, propertyValue)`|
|`setText(renderNode, text)`|`setValue(renderNode, text)`|
|`listenGlobal(target, name, callback)`|`listen(target, name, callback)`|
|`selectRootElement(selectorOrNode, debugInfo?)`|`selectRootElement(selectorOrNode)`|
|`createElement(parentElement, name, debugInfo?)`|`appendChild(parentElement, createElement(name))`|
|`setElementStyle(el, style, value?)`|`value == null ? removeStyle(el, style) : setStyle(el, style, value)`
|`setElementAttribute(el, name, value?)`|`attributeValue == null ? removeAttribute(el, name) : setAttribute(el, name, value)`
|`createText(parentElement, value, debugInfo?)`|`appendChild(parentElement, createText(value))`|
|`createTemplateAnchor(parentElement)`|`appendChild(parentElement, createComment(''))`|
|`setElementClass(renderElement, className, isAdd)`|`isAdd ? addClass(renderElement, className) : removeClass(renderElement, className)`|
|`projectNodes(parentElement, nodes)`|`for (let i = 0; i < nodes.length; i<ins></ins>) { appendChild(parentElement, nodes<i>); }`|
|`attachViewAfter(node, viewRootNodes)`|`const parentElement = parentNode(node); const nextSibling = nextSibling(node); for (let i = 0; i < viewRootNodes.length; i<ins></ins>) { insertBefore(parentElement, viewRootNodes<i>, nextSibling);}`|
|`detachView(viewRootNodes)`|`for (let i = 0; i < viewRootNodes.length; i<ins></ins>) {const node = viewRootNodes<i>; const parentElement = parentNode(node); removeChild(parentElement, node);}`|
|`destroyView(hostElement, viewAllNodes)`|`for (let i = 0; i < viewAllNodes.length; i<ins></ins>) { destroyNode(viewAllNodes<i>); }`|
|`setBindingDebugInfo()`|This function is a noop in `Renderer2`.|
|`createViewRoot(hostElement)`|Should be replaced with a reference to `hostElement`|
|`invokeElementMethod(renderElement, methodName, args?)`|`(renderElement as any)<methodName>.apply(renderElement, args);`|
|`animate(element, startingStyles, keyframes, duration, delay, easing, previousPlayers?)`|Throws an error (same behavior as `Renderer.animate()`)|

View File

@ -0,0 +1,138 @@
# Undecorated classes migration (DI)
This section discusses an Angular version 9 schematic that migrates
two inheritance patterns that need to be updated to work with Ivy.
## What does this migration do?
This migration adds an empty `@Directive()` decorator to undecorated
base classes that are extended by either directives or components.
Before:
```ts
export class BaseMenu {
constructor(private vcr: ViewContainerRef) {}
}
@Directive({selector: '[settingsMenu]'})
export class SettingsMenu extends BaseMenu {}
```
After:
```ts
@Directive()
export class BaseMenu {
constructor(private vcr: ViewContainerRef) {}
}
@Directive({selector: '[settingsMenu]'})
export class SettingsMenu extends BaseMenu {}
```
The schematic also copies any inherited directive or component metadata to the derived class.
Before:
```ts
@Component({
selector: 'base-menu',
template: '<div></div>'
})
class BaseMenu {}
export class SettingsMenu extends BaseMenu {}
```
After:
```ts
@Component({
selector: 'base-menu',
template: '<div></div>'
})
class BaseMenu {}
@Component({
selector: 'settings-menu',
template: '<div></div>'
})
export class SettingsMenu extends BaseMenu {}
```
## Why is this migration necessary?
When a class has a `@Directive()` or `@Component()` decorator,
the Angular compiler generates extra code to inject dependencies into
the constructor. When using inheritance, Ivy needs both the parent class
and the child class to apply a decorator to generate the correct code.
You can think of this change as two cases: a parent class is missing a
decorator or a child class is missing a decorator. In both scenarios,
Angular's run-time needs additional information from the compiler.
This additional information comes from adding decorators.
### Decorator missing from parent class
When the decorator is missing from the parent class,
the subclass will inherit a constructor from a class for
which the compiler did not generate special constructor
info (because it was not decorated as a directive).
When Angular then tries to create the subclass,
it doesn't have the correct info
to create it.
In View Engine, the compiler has global knowledge, so it
can look up the missing data. However, the Ivy compiler
only processes each directive in isolation. This means that
compilation can be faster, but the compiler can't
automatically infer the same
information as before. Adding the `@Directive()` explicitly
provides this information.
In the future, add `@Directive()` to base classes that
do not already have decorators and are extended by directives.
### Decorator missing from child class
When the child class is missing the decorator, the
child class inherits from the
parent class yet has no decorators of its own.
Without a decorator, the compiler has no way of knowing
that the class is a `@Directive` or `@Component`, so
it doesn't generate the proper instructions for the directive.
## What does it mean to have a `@Directive()` decorator with no metadata inside of it?
The presence of the `@Directive` decorator causes Angular to generate
extra code for the affected class. If that decorator includes no
properties (metadata),
the directive won't be matched to elements or instantiated
directly, but other classes that _extend_ the
directive class will inherit this generated code. You can think of
this as an "abstract" directive.
Adding an abstract directive to an `NgModule` will cause an error.
A directive must have a `selector` property defined in order to match some element in a template.
## When do I need a `@Directive()` decorator without a selector?
If you're using dependency injection, or any Angular-specific
feature, such as `@HostBinding()`, `@ViewChild()`, or `@Input()`, you need a
`@Directive()` or `@Component()` decorator.
The decorator lets the compiler know to generate the correct
instructions to create that class and any classes that extend it.
If you don't want to use that base class as a directive directly, leave
the selector blank. If you do want it to be usable independently,
fill in the metadata as usual.
Classes that don't use Angular features don't need an Angular decorator.
## I'm a library author. Should I add the `@Directive()` decorator to base classes?
As support for selectorless decorators is introduced in
Angular version 9, if you want to support Angular version 8 and earlier, you
shouldn't add a selectorless `@Directive()` decorator.
You can either add `@Directive()` with a selector or
add an explicit constructor to affected subclasses.

View File

@ -32,7 +32,7 @@ The context also defines a *merge strategy* that determines how changes are merg
When you create a new blank schematic with the [Schematics CLI](#cli), the generated entry function is a *rule factory*.
A `RuleFactory`object defines a higher-order function that creates a `Rule`.
<code-example language="TypeScript">
<code-example language="TypeScript" header="index.ts">
import { Rule, SchematicContext, Tree } from '@angular-devkit/schematics';
// You don't have to export the function as default.
@ -49,7 +49,7 @@ You need a rule, for example, to define how a template in the schematic is to be
Rules can make use of utilities provided with the `@schematics/angular` package. Look for helper functions for working with modules, dependencies, TypeScript, AST, JSON, Angular CLI workspaces and projects, and more.
<code-example language="none">
<code-example language="TypeScript" header="index.ts">
import {
JsonAstObject,
@ -69,8 +69,191 @@ Rules can collect option values from the caller and inject them into templates.
The options available to your rules, with their allowed values and defaults, are defined in the schematic's JSON schema file, `<schematic>/schema.json`.
You can define variable or enumerated data types for the schema using TypeScript interfaces.
The schema defines the types and default values of variables used in the schematic.
For example, the hypothetical "Hello World" schematic might have the following schema.
<code-example language="json" header="src/hello-world/schema.json">
{
"properties": {
"name": {
"type": "string",
"minLength": 1,
"default": "world"
},
"useColor": {
"type": "boolean"
}
}
}
</code-example>
You can see examples of schema files for the Angular CLI command schematics in [`@schematics/angular`](https://github.com/angular/angular-cli/blob/7.0.x/packages/schematics/angular/application/schema.json).
### Schematic prompts
Schematic *prompts* introduce user interaction into schematic execution.
You can configure schematic options to display a customizable question to the user.
The prompts are displayed before the execution of the schematic, which then uses the response as the value for the option.
This allows users to direct the operation of the schematic without requiring in-depth knowledge of the full spectrum of available options.
The "Hello World" schematic might, for example, ask the user for their name, and display that name in place of the default name "world". To define such a prompt, add an `x-prompt` property to the schema for the `name` variable.
Similarly, you can add a prompt to allow the user to decide whether the schematic will use color when executing its hello action. The schema with both prompts would be as follows.
<code-example language="json" header="src/hello-world/schema.json">
{
"properties": {
"name": {
"type": "string",
"minLength": 1,
"default": "world",
"x-prompt": "What is your name?"
},
"useColor": {
"type": "boolean",
"x-prompt": "Would you like the response in color?"
}
}
}
</code-example>
#### Prompt short-form syntax
These examples use a shorthand form of the prompt syntax, supplying only the text of the question.
In most cases, this is all that is required.
Notice however, that the two prompts expect different types of input.
When using the shorthand form, the most appropriate type is automatically selected based on the property's schema.
In the example, the `name` prompt uses the `input` type because it it is a string property.
The `useColor` prompt uses a `confirmation` type because it is a Boolean property.
In this case, "yes" corresponds to `true` and "no" corresponds to `false`.
There are three supported input types.
| Input type | Description |
| :----------- | :-------------------|
| confirmation | A yes or no question; ideal for Boolean options. |
| input | Textual input; ideal for string or number options. |
| list | A predefined set of allowed values. |
In the short form, the type is inferred from the property's type and constraints.
| Property Schema | Prompt Type |
| :--------------- | :------------- |
| "type": "boolean" | confirmation ("yes"=`true`, "no"=`false`) |
| "type": "string" | input |
| "type": "number" | input (only valid numbers accepted) |
| "type": "integer" | input (only valid numbers accepted) |
| "enum": [...] | list (enum members become list selections) |
In the following example, the property takes an enumerated value, so the schematic automatically chooses the list type, and creates a menu from the possible values.
<code-example language="json" header="schema.json">
"style": {
"description": "The file extension or preprocessor to use for style files.",
"type": "string",
"default": "css",
"enum": [
"css",
"scss",
"sass",
"less",
"styl"
],
"x-prompt": "Which stylesheet format would you like to use?"
}
</code-example>
The prompt runtime automatically validates the provided response against the constraints provided in the JSON schema.
If the value is not acceptable, the user is prompted for a new value.
This ensures that any values passed to the schematic meet the expectations of the schematic's implementation, so that you do not need to add additional checks within the schematic's code.
#### Prompt long-form syntax
The `x-prompt` field syntax supports a long form for cases where you require additional customization and control over the prompt.
In this form, the `x-prompt` field value is a JSON object with subfields that customize the behavior of the prompt.
| Field | Data Value |
| :----------- | :------ |
| type | `confirmation`, `input`, or `list` (selected automatically in short form) |
| message | string (required) |
| items | string and/or label/value object pair (only valid with type `list`) |
The following example of the long form is from the JSON schema for the schematic that the CLI uses to [generate applications](https://github.com/angular/angular-cli/blob/ba8a6ea59983bb52a6f1e66d105c5a77517f062e/packages/schematics/angular/application/schema.json#L56).
It defines the prompt that allows users to choose which style preprocessor they want to use for the application being created.
By using the long form, the schematic can provide more explicit formatting of the menu choices.
<code-example language="json" header="package/schematics/angular/application/schema.json">
"style": {
"description": "The file extension or preprocessor to use for style files.",
"type": "string",
"default": "css",
"enum": [
"css",
"scss",
"sass",
"less",
"styl"
],
"x-prompt": {
"message": "Which stylesheet format would you like to use?",
"type": "list",
"items": [
{ "value": "css", "label": "CSS" },
{ "value": "scss", "label": "SCSS [ https://sass-lang.com/documentation/syntax#scss ]" },
{ "value": "sass", "label": "Sass [ https://sass-lang.com/documentation/syntax#the-indented-syntax ]" },
{ "value": "less", "label": "Less [ http://lesscss.org ]" },
{ "value": "styl", "label": "Stylus [ http://stylus-lang.com ]" }
]
},
},
</code-example>
#### x-prompt schema
The JSON schema that defines a schematic's options supports extensions to allow the declarative definition of prompts and their respective behavior.
No additional logic or changes are required to the code of a schematic to support the prompts.
The following JSON schema is a complete description of the long-form syntax for the `x-prompt` field.
<code-example language="json" header="x-prompt schema">
{
"oneOf": [
{ "type": "string" },
{
"type": "object",
"properties": {
"type": { "type": "string" },
"message": { "type": "string" },
"items": {
"type": "array",
"items": {
"oneOf": [
{ "type": "string" },
{
"type": "object",
"properties": {
"label": { "type": "string" },
"value": { }
},
"required": [ "value" ]
}
]
}
}
},
"required": [ "message" ]
}
]
}
</code-example>
{@a cli}
## Schematics CLI

View File

@ -207,6 +207,9 @@ There are two possible degraded states:
clean copy of the latest known version of the app. Older cached
versions are safe to use, so existing tabs continue to run from
cache, but new loads of the app will be served from the network.
The service worker will try to recover from this state when a new
version of the application is detected and installed (that is,
when a new `ngsw.json` is available).
* `SAFE_MODE`: the service worker cannot guarantee the safety of
using cached data. Either an unexpected error occurred or all
@ -216,6 +219,12 @@ network, running as little service worker code as possible.
In both cases, the parenthetical annotation provides the
error that caused the service worker to enter the degraded state.
Both states are temporary; they are saved only for the lifetime of the [ServiceWorker
instance](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope).
The browser sometimes terminates an idle service worker to conserve memory and
processor power, and creates a new service worker instance in response to
network events. The new instance starts in the `NORMAL` mode, regardless of the
state of the previous instance.
#### Latest manifest hash

View File

@ -297,7 +297,7 @@ describes additional `NgFor` directive properties and context properties.
These microsyntax mechanisms are also available to you when you write your own structural directives.
For example, microsyntax in Angular allows you to write `<div *ngFor="let item of items">{{item}}</div>`
instead of `<ng-template ngFor [ngForOf]="items"><div>{{item}}</div></ng-template`.
instead of `<ng-template ngFor [ngForOf]="items"><div>{{item}}</div></ng-template>`.
The following sections provide detailed information on constraints, grammar,
and translation of microsyntax.

View File

@ -635,7 +635,7 @@ which is the attribute, spelled with a lowercase `s`.
<code-example path="property-binding/src/app/app.component.html" region="colSpan" header="src/app/app.component.html"></code-example>
For more details, see the [MDN HTMLTableCellElment](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableCellElement) documentation.
For more details, see the [MDN HTMLTableCellElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableCellElement) documentation.
<!-- Add link when Attribute Binding updates are merged:
For more about `colSpan` and `colspan`, see (Attribute Binding)[guide/template-syntax]. -->
@ -1610,8 +1610,8 @@ by HTML.
The reference value of itemForm, without the ngForm attribute value, would be
the [HTMLFormElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement).
There is, however, a difference between a Component and a Directive in that a `Component
`will be referenced without specifying the attribute value, and a `Directive` will not
There is, however, a difference between a Component and a Directive in that a `Component`
will be referenced without specifying the attribute value, and a `Directive` will not
change the implicit reference (that is, the element).

View File

@ -34,7 +34,6 @@ The initial `tsconfig.json` for an Angular app typically looks like this example
<code-example lang="json" header="tsconfig.json" linenums="false">
{
"compileOnSave": false,
"compilerOptions": {
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
@ -54,6 +53,7 @@ The initial `tsconfig.json` for an Angular app typically looks like this example
"dom"
]
}
}
</code-example>

View File

@ -203,9 +203,9 @@ One solution is to provide the full URL to your application on the server, and w
value and prepend it to the request URL. If you're using the `ngExpressEngine`, as shown in the example in this guide, half
the work is already done. We'll assume this is the case, but it's trivial to provide the same functionality.
Start by creating an [HttpInterceptor](api/common/http/HttpInterceptor):
Start by creating an [HttpInterceptor](api/common/http/HttpInterceptor).
<code-example language="typescript">
<code-example language="typescript" header="universal-interceptor.ts">
import {Injectable, Inject, Optional} from '@angular/core';
import {HttpInterceptor, HttpHandler, HttpRequest, HttpHeaders} from '@angular/common/http';
@ -233,9 +233,9 @@ export class UniversalInterceptor implements HttpInterceptor {
</code-example>
Next, provide the interceptor in the providers for the server `AppModule` (app.server.module.ts):
Next, provide the interceptor in the providers for the server `AppModule`.
<code-example language="typescript">
<code-example language="typescript" header="app.server.module.ts">
import {HTTP_INTERCEPTORS} from '@angular/common/http';
import {UniversalInterceptor} from './universal-interceptor';

View File

@ -1622,7 +1622,7 @@ There are several notable changes here:
* You're using the property binding syntax around `ng-class`. Though Angular
does have [a very similar `ngClass`](guide/template-syntax#directives)
as AngularJS does, its value is not magically evaluated as an expression.
In Angular, you always specify in the template when an attribute's value is
In Angular, you always specify in the template when an attribute's value is
a property expression, as opposed to a literal string.
* You've replaced `ng-repeat`s with `*ngFor`s.
@ -1709,7 +1709,7 @@ Create a new `app.component.ts` file with the following `AppComponent` class:
<code-example path="upgrade-phonecat-3-final/app/app.component.ts" header="app/app.component.ts">
</code-example>
It has a simple template that only includes the `<router-outlet>.
It has a simple template that only includes the `<router-outlet>`.
This component just renders the contents of the active route and nothing else.
The selector tells Angular to plug this root component into the `<phonecat-app>`

View File

@ -13,16 +13,16 @@ Running this command will:
- configure your project to use Web Workers, if it isn't already.
- add `src/app/app.worker.ts` with scaffolded code to receive messages:
```typescript
<code-example language="typescript" header="src/app/app.worker.ts">
addEventListener('message', ({ data }) => {
const response = `worker response to ${data}`;
postMessage(response);
});
```
</code-example>
- add scaffolded code to `src/app/app.component.ts` to use the worker:
```typescript
<code-example language="typescript" header="src/app/app.component.ts">
if (typeof Worker !== 'undefined') {
// Create a new
const worker = new Worker('./app.worker', { type: 'module' });
@ -34,7 +34,7 @@ Running this command will:
// Web Workers are not supported in this environment.
// You should add a fallback so that your program still executes correctly.
}
```
</code-example>
After the initial scaffolding, you will need to refactor your code to use the Web Worker by sending messages to and from.

View File

@ -66,6 +66,13 @@
"rev": true,
"title": "Happy Angular Podcast",
"url": "https://happy-angular.de/"
},
"ngruair": {
"desc": "Russian language video podcast about Angular.",
"logo": "",
"rev": true,
"title": "NgRuAir",
"url": "https://github.com/ngRuAir/ngruair"
}
}
}

View File

@ -20,7 +20,7 @@ Services are the place where you share data between parts of your application. F
Up to this point, users can view product information, and simulate sharing and being notified about product changes. They cannot, however, buy products.
In this section, you'll add a "Buy" button the product details page.
In this section, you'll add a "Buy" button to the product details page.
You'll also set up a cart service to store information about products in the cart.
<div class="alert is-helpful">

View File

@ -2,13 +2,12 @@
Welcome to Angular!
This tutorial introduces you to the essentials of Angular.
It leverages what you already know about HTML and JavaScript&mdash;plus some useful Angular features&mdash;to build a simple online store application, with a catalog, shopping cart, and check-out form.
You don't need to install anything: you'll build the app using the [StackBlitz](https://stackblitz.com/ "StackBlitz web site") online development environment.
This tutorial introduces you to the essentials of Angular by walking you through building a simple e-commerce site with a catalog, shopping cart, and check-out form. It uses the [StackBlitz](https://stackblitz.com/ "StackBlitz website") online development environment so you can get started right away.
<div class="alert is-helpful">
We are using the StackBlitz Generator to show you a ready-made, simple application that you can examine and play with interactively. In actual development you will typically use the [Angular CLI](guide/glossary#command-line-interface-cli), a powerful command-line tool that lets you generate and modify applications. For more information, see the [CLI Overview](cli).
This guide uses the StackBlitz Generator to show you a ready-made, simple application that you can examine and play with interactively. In actual development you will typically use the [Angular CLI](guide/glossary#command-line-interface-cli), a powerful command-line tool that lets you generate and modify applications. For more information, see the [CLI Overview](cli).
</div>
@ -16,10 +15,10 @@ We are using the StackBlitz Generator to show you a ready-made, simple applicati
<header>New to web development?</header>
You'll find many resources to complement the Angular docs. Mozilla's MDN docs include both [HTML](https://developer.mozilla.org/en-US/docs/Learn/HTML "Learning HTML: Guides and tutorials") and [JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript "JavaScript") introductions. [TypeScript's docs](https://www.typescriptlang.org/docs/home.html "TypeScript documentation") include a 5-minute tutorial. Various online course platforms, such as [Udemy](http://www.udemy.com "Udemy online courses") and [Codecademy](https://www.codecademy.com/ "Codeacademy online courses"), also cover web development basics.
There are many resources to complement the Angular docs. Mozilla's MDN docs include both [HTML](https://developer.mozilla.org/en-US/docs/Learn/HTML "Learning HTML: Guides and tutorials") and [JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript "JavaScript") introductions. [TypeScript's docs](https://www.typescriptlang.org/docs/home.html "TypeScript documentation") include a 5-minute tutorial. Various online course platforms, such as [Udemy](http://www.udemy.com "Udemy online courses") and [Codecademy](https://www.codecademy.com/ "Codeacademy online courses"), also cover web development basics.
</div>
</div>
@ -27,11 +26,12 @@ You'll find many resources to complement the Angular docs. Mozilla's MDN docs in
## Create a new project
<h4>
<live-example name="getting-started-v0" noDownload>Click here to create a new project in StackBlitz.</live-example>
<live-example name="getting-started-v0" noDownload>Click here to create a new project in StackBlitz.</live-example>
</h4>
StackBlitz creates a starter Angular app.
We've seeded this particular app with a top bar&mdash;containing the store name and checkout icon&mdash;and the title for a product list.
StackBlitz creates a starter Angular app with a top
bar&mdash;containing the store name and
checkout icon&mdash;and the title for a product list.
<figure>
@ -42,100 +42,111 @@ We've seeded this particular app with a top bar&mdash;containing the store name
<div class="callout is-helpful">
<header>StackBlitz tips</header>
* Log into StackBlitz, so you can save and resume your work. If you have a GitHub account, you can log into StackBlitz with that account. In order to save your progress, first fork the project using the Fork button at the top left, then you'll be able to save your work to your own StackBlitz account by clicking the Save button.
* To copy a code example from this tutorial, click the icon at the top right of the code example box, and then paste the code snippet from the clipboard into StackBlitz.
* If the StackBlitz preview pane isn't showing what you expect, save and then click the refresh button.
* StackBlitz is continually improving, so there may be slight differences in generated code, but the app's behavior will be the same.
* Log into StackBlitz so you can save and resume your work.
If you have a GitHub account, you can log into StackBlitz
with that account. In order to save your progress, first
fork the project using the Fork button at the top left,
then you'll be able to save your work to your own StackBlitz
account by clicking the Save button.
* To copy a code example from this tutorial, click the icon
at the top right of the code example box, and then paste the
code snippet from the clipboard into StackBlitz.
* If the StackBlitz preview pane isn't showing what you
expect, save and then click the refresh button.
* StackBlitz is continually improving, so there may be
slight differences in generated code, but the app's
behavior will be the same.
</div>
{@a template-syntax}
## Template syntax
<!--
Angular extends HTML with a template syntax that gives components control over the display of content.
This section introduces five things you can do in an Angular template to affect what your user sees, based on the component's state and behavior:
-->
Angular's template syntax extends HTML and JavaScript.
This section introduces template syntax by enhancing the "Products" area.
Angular's template syntax extends HTML and JavaScript.
In this section, you'll learn about template syntax by enhancing the "Products" area.
<div class="alert is-helpful">
(So that you can focus on the template syntax, the following steps use predefined product data and methods from the `product-list.component.ts` file.)
To help you get going, the following steps use predefined product data and methods from the `product-list.component.ts` file.
1. In the `product-list` folder, open the template file `product-list.component.html`.
</div>
1. Modify the product list template to display a list of product names.
1. In the `product-list` folder, open the template
file `product-list.component.html`.
1. We want each product in the list to be displayed the same way, one after the other on the page. To iterate over the predefined list of products, use the `*ngFor` directive. Put the `*ngFor` directive on a `<div>`, as shown below:
1. Modify the product list template to display a list of product names.
1. Each product in the list displays the same way, one after another on the page. To iterate over the predefined list of products, put the `*ngFor` directive on a `<div>`, as follows:
<code-example header="src/app/product-list/product-list.component.html" path="getting-started/src/app/product-list/product-list.component.2.html" region="ngfor">
</code-example>
`*ngFor` causes the `<div>` to be repeated for each product in the list.
With `*ngFor`, the `<div>` repeats for each product in the list.
<div class="alert is-helpful">
`*ngFor` is a "structural directive". Structural directives shape or reshape the DOM's structure, typically by adding, removing, and manipulating the elements to which they are attached. Any directive with an `*` is a structural directive.
`*ngFor` is a "structural directive". Structural directives shape or reshape the DOM's structure, typically by adding, removing, and manipulating the elements to which they are attached. Any directive with an asterisk, `*`, is a structural directive.
</div>
1. To display the names of the products, use the interpolation syntax {{ }}. Interpolation renders a property's value as text. Inside the `<div>`, add an `<h3>` heading to display the interpolation of the product's name property:
1. To display the names of the products, use the interpolation syntax `{{ }}`. Interpolation renders a property's value as text. Inside the `<div>`, add an `<h3>` to display the interpolation of the product's name property:
<code-example path="getting-started/src/app/product-list/product-list.component.2.html" region="interpolation">
<code-example path="getting-started/src/app/product-list/product-list.component.2.html" header="src/app/product-list/product-list.component.html" region="interpolation">
</code-example>
The preview pane immediately updates to display the name of each product in the list.
The preview pane immediately updates to display the name of each product in the list.
<figure>
<img src="generated/images/guide/start/template-syntax-product-names.png" alt="Product names added to list">
</figure>
1. In the final app, each product name will be a link to product details. Add the anchor now, and set the anchor's title to be the product's name by using the property binding [ ] syntax, as shown below:
1. To make each product name a link to product details, add the `<a>` element and set its title to be the product's name by using the property binding `[ ]` syntax, as follows:
<code-example path="getting-started/src/app/product-list/product-list.component.2.html">
<code-example path="getting-started/src/app/product-list/product-list.component.2.html" header="src/app/product-list/product-list.component.html">
</code-example>
<!--
To do: Description and code don't match exactly. Do we want to just use product name as the anchor hover text to show a simple property or append "details" to show an expression? Also affects screen shot.
-->
In the preview pane, hover over the displayed product name to see the bound name property value. They are the same. Interpolation {{ }} lets you render the property value as text; property binding [ ] lets you use the property value in a template expression.
In the preview pane, hold the pointer over a product
name to see the bound name property value, which is
the product name plus the word "details".
Interpolation `{{ }}` lets you render the
property value as text; property binding `[ ]` lets you
use the property value in a template expression.
<figure>
<img src="generated/images/guide/start/template-syntax-product-anchor.png" alt="Product name anchor text is product name property">
</figure>
1. Add the product descriptions. On the paragraph tag, use an `*ngIf` directive so that the paragraph element is only created if the current product has a description.
<code-example path="getting-started/src/app/product-list/product-list.component.3.html">
1. Add the product descriptions. On the `<p>` element, use an `*ngIf` directive so that Angular only creates the `<p>` element if the current product has a description.
<code-example path="getting-started/src/app/product-list/product-list.component.3.html" header="src/app/product-list/product-list.component.html">
</code-example>
The app now displays the name and description of each product in the list, as shown below. Notice that the final product does not have a description paragraph at all. Because the product's description property is empty, the paragraph element&mdash;including the word "Description"&mdash;is not created.
The app now displays the name and description of each product in the list. Notice that the final product does not have a description paragraph. Because the product's description property is empty, Angular doesn't create the `<p>` element&mdash;including the word "Description".
<figure>
<img src="generated/images/guide/start/template-syntax-product-description.png" alt="Product descriptions added to list">
</figure>
1. Add a button so users can share a product with friends. Bind the button's `click` event to the `share()` event that we defined for you (in `product-list.component.ts`). Event binding is done by using ( ) around the event, as shown below:
1. Add a button so users can share a product with friends. Bind the button's `click` event to the `share()` method (in `product-list.component.ts`). Event binding uses a set of parentheses, `( )`, around the event, as in the following `<button>` element:
<code-example path="getting-started/src/app/product-list/product-list.component.4.html">
<code-example path="getting-started/src/app/product-list/product-list.component.4.html" header="src/app/product-list/product-list.component.html">
</code-example>
Each product now has a "Share" button:
Each product now has a "Share" button:
<figure>
<img src="generated/images/guide/start/template-syntax-product-share-button.png" alt="Share button added for each product">
</figure>
Test the "Share" button:
Test the "Share" button:
<figure>
<img src="generated/images/guide/start/template-syntax-product-share-alert.png" alt="Alert box indicating product has been shared">
</figure>
The app now has a product list and sharing feature.
In the process, you've learned to use five common features of Angular's template syntax:
The app now has a product list and sharing feature.
In the process, you've learned to use five common features of Angular's template syntax:
* `*ngFor`
* `*ngIf`
* Interpolation `{{ }}`
@ -145,7 +156,8 @@ In the process, you've learned to use five common features of Angular's template
<div class="alert is-helpful">
Learn more: See the [Template Syntax guide](guide/template-syntax "Template Syntax") for information about the full capabilities of Angular's template syntax.
For more information about the full capabilities of Angular's
template syntax, see [Template Syntax](guide/template-syntax "Template Syntax").
</div>
@ -153,50 +165,53 @@ Learn more: See the [Template Syntax guide](guide/template-syntax "Template Synt
{@a components}
## Components
*Components* define areas of responsibility in your UI that let you reuse these sets of UI functionality.
You've already built one with the product list component.
*Components* define areas of responsibility in the user interface, or UI,
that let you reuse sets of UI functionality.
You've already built one with the product list component.
A component is comprised of three things:
* **A component class,** which handles data and functionality. In the previous section, the product data and the `share()` method were defined for you in the component class.
* **An HTML template,** which determines what is presented to the user. In the previous section, you modified the product list's HTML template to display the name, description, and a "Share" button for each product.
* **Component-specific styles** that define the look and feel. The product list does not define any styles.
A component consists of three things:
* **A component class** that handles data and functionality. In the previous section, the product data and the `share()` method in the component class handle data and functionality, respectively.
* **An HTML template** that determines the UI. In the previous section, the product list's HTML template displays the name, description, and a "Share" button for each product.
* **Component-specific styles** that define the look and feel.
Though product list does not define any styles, this is where component CSS
resides.
<!--
<!--
### Class definition
Let's take a quick look a the product list component's class definition:
Let's take a quick look a the product list component's class definition:
1. In the `product-list` directory, open `product-list.component.ts`.
1. In the `product-list` directory, open `product-list.component.ts`.
1. Notice the `@Component` decorator. This provides metadata about the component, including its templates, styles, and a selector.
1. Notice the `@Component` decorator. This provides metadata about the component, including its templates, styles, and a selector.
* The `selector` is used to identify the component. The selector is the name you give the Angular component when it is rendered as an HTML element on the page. By convention, Angular component selectors begin with the prefix such as `app-`, followed by the component name.
* The `selector` is used to identify the component. The selector is the name you give the Angular component when it is rendered as an HTML element on the page. By convention, Angular component selectors begin with the prefix such as `app-`, followed by the component name.
* The template and style filename also are provided here. By convention each of the component's parts is in a separate file, all in the same directory and with the same prefix.
* The template and style filename also are provided here. By convention each of the component's parts is in a separate file, all in the same directory and with the same prefix.
1. The component definition also includes an exported class, which handles functionality for the component. This is where the product list data and `Share()` method are defined.
1. The component definition also includes an exported class, which handles functionality for the component. This is where the product list data and `Share()` method are defined.
### Composition
-->
An Angular application is composed of a tree of components, in which each Angular component has a specific purpose and responsibility.
An Angular application comprises a tree of components, in which each Angular component has a specific purpose and responsibility.
Currently, our app has three components:
Currently, the example app has three components:
<figure>
<img src="generated/images/guide/start/app-components.png" alt="Online store with three components">
</figure>
* `app-root` (orange box) is the application shell. This is the first component to load, and the parent of all other components. You can think of it as the base page.
* `app-root` (orange box) is the application shell. This is the first component to load and the parent of all other components. You can think of it as the base page.
* `app-top-bar` (blue background) is the store name and checkout button.
* `app-product-list` (purple box) is the product list that you modified in the previous section.
* `app-product-list` (purple box) is the product list that you modified in the previous section.
In the next section, you'll expand the app's capabilities by adding a new component for a product alert. You'll add it as a child of the product list component.
The next section expands the app's capabilities by adding a new component&mdash;a product alert&mdash;as a child of the product list component.
<div class="alert is-helpful">
Learn more: See [Introduction to Components](guide/architecture-components "Architecture > Introduction to Components") for more information about components and how they interact with templates.
For more information about components and how they interact with templates, see [Introduction to Components](guide/architecture-components "Architecture > Introduction to Components").
</div>
@ -204,12 +219,12 @@ Learn more: See [Introduction to Components](guide/architecture-components "Arch
{@a input}
## Input
Currently, the product list displays the name and description of each product.
You might have noticed that the product list component also defines a `products` property that contains imported data for each product. (See the `products` array in `products.ts`.)
Currently, the product list displays the name and description of each product.
The product list component also defines a `products` property that contains imported data for each product from the `products` array in `products.ts`.
We're going to create a new alert feature. The alert feature will take a product as an input. It will then check the product's price, and, if the price is greater than $700, it will display a "Notify Me" button that lets users sign up for notifications when the product goes on sale.
The next step is to create a new alert feature that takes a product as an input. The alert checks the product's price, and, if the price is greater than $700, displays a "Notify Me" button that lets users sign up for notifications when the product goes on sale.
1. Create a new product alerts component.
1. Create a new product alerts component.
1. Right click on the `app` folder and use the `Angular Generator` to generate a new component named `product-alerts`.
@ -217,50 +232,50 @@ We're going to create a new alert feature. The alert feature will take a product
<img src="generated/images/guide/start/generate-component.png" alt="StackBlitz command to generate component">
</figure>
The generator creates starter files for all three parts of the component:
The generator creates starter files for all three parts of the component:
* `product-alerts.component.ts`
* `product-alerts.component.html`
* `product-alerts.component.css`
1. Open `product-alerts.component.ts`.
<code-example header="src/app/product-alerts/product-alerts.component.ts" path="getting-started/src/app/product-alerts/product-alerts.component.1.ts" region="as-generated"></code-example>
<code-example header="src/app/product-alerts/product-alerts.component.ts" path="getting-started/src/app/product-alerts/product-alerts.component.1.ts" region="as-generated"></code-example>
1. Notice the `@Component` decorator. This indicates that the following class is a component. It provides metadata about the component, including its templates, styles, and a selector.
1. Notice the `@Component()` decorator. This indicates that the following class is a component. It provides metadata about the component, including its selector, templates, and styles.
* The `selector` is used to identify the component. The selector is the name you give the Angular component when it is rendered as an HTML element on the page. By convention, Angular component selectors begin with the prefix `app-`, followed by the component name.
* The `selector` identifies the component. The selector is the name you give the Angular component when it is rendered as an HTML element on the page. By convention, Angular component selectors begin with the prefix `app-`, followed by the component name.
* The template and style filenames. These reference the other two files generated for you.
* The template and style filenames reference the HTML and CSS files that StackBlitz generates.
1. The component definition also includes an exported class (`ProductAlertsComponent`), which handles functionality for the component.
1. The component definition also exports the class, `ProductAlertsComponent`, which handles functionality for the component.
1. Set up the new product alerts component to receive a product as input:
1. Import `Input` from `@angular/core`.
<code-example path="getting-started/src/app/product-alerts/product-alerts.component.1.ts" region="imports"></code-example>
<code-example path="getting-started/src/app/product-alerts/product-alerts.component.1.ts" region="imports" header="src/app/product-list/product-alerts.component.ts"></code-example>
1. In the `ProductAlertsComponent` class definition, define a property named `product` with an `@Input` decorator. The `@Input` decorator indicates that the property value will be passed in from the component's parent (in this case, the product list component).
1. In the `ProductAlertsComponent` class definition, define a property named `product` with an `@Input()` decorator. The `@Input()` decorator indicates that the property value passes in from the component's parent, the product list component.
<code-example path="getting-started/src/app/product-alerts/product-alerts.component.1.ts" region="input-decorator"></code-example>
<code-example path="getting-started/src/app/product-alerts/product-alerts.component.1.ts" region="input-decorator" header="src/app/product-list/product-alerts.component.ts"></code-example>
1. Define the view for the new product alert component.
1. Define the view for the new product alert component.
Open the `product-alerts.component.html` template and replace the placeholder paragraph with a "Notify Me" button that appears if the product price is over $700.
1. Open the `product-alerts.component.html` template and replace the placeholder paragraph with a "Notify Me" button that appears if the product price is over $700.
<code-example header="src/app/product-alerts/product-alerts.component.html" path="getting-started/src/app/product-alerts/product-alerts.component.1.html"></code-example>
1. Display the new product alert component as part of (a child of) the product list.
1. Display the new product alert component as a child of the product list.
1. Open `product-list.component.html`.
1. To include the new component, use its selector (`app-product-alert`) as you would an HTML element.
1. Pass the current product as input to the component using property binding.
1. To include the new component, use its selector, `app-product-alert`, as you would an HTML element.
1. Pass the current product as input to the component using property binding.
<code-example header="src/app/product-list/product-list.component.html" path="getting-started/src/app/product-list/product-list.component.5.html" region="app-product-alerts"></code-example>
The new product alert component takes a product as input from the product list. With that input, it shows or hides the "Notify Me" button, based on the price of the product. The Phone XL price is over $700, so the "Notify Me" button appears on that product.
The new product alert component takes a product as input from the product list. With that input, it shows or hides the "Notify Me" button, based on the price of the product. The Phone XL price is over $700, so the "Notify Me" button appears on that product.
<figure>
<img src="generated/images/guide/start/product-alert-button.png" alt="Product alert button added to products over $700">
@ -269,7 +284,7 @@ The new product alert component takes a product as input from the product list.
<div class="alert is-helpful">
Learn more: See [Component Interaction](guide/component-interaction "Components & Templates > Component Interaction") for more information about passing data from a parent to child component, intercepting and acting upon a value from the parent, and detecting and acting on changes to input property values.
See [Component Interaction](guide/component-interaction "Components & Templates > Component Interaction") for more information about passing data from a parent to child component, intercepting and acting upon a value from the parent, and detecting and acting on changes to input property values.
</div>
@ -277,33 +292,36 @@ Learn more: See [Component Interaction](guide/component-interaction "Components
{@a output}
## Output
The "Notify Me" button doesn't do anything yet. In this section, you'll set up the product alert component so that it emits an event up to the product list component when the user clicks "Notify Me". You'll define the notification behavior in the product list component.
To make the "Notify Me" button work, you need to configure two things:
- the product alert component to emit an event when the user clicks "Notify Me"
- the product list component to act on that event
1. Open `product-alerts.component.ts`.
1. Import `Output` and `EventEmitter` from `@angular/core`:
1. Import `Output` and `EventEmitter` from `@angular/core`:
<code-example header="src/app/product-alerts/product-alerts.component.ts" path="getting-started/src/app/product-alerts/product-alerts.component.ts" region="imports"></code-example>
1. In the component class, define a property named `notify` with an `@Output` decorator and an instance of event emitter. This makes it possible for the product alert component to emit an event when the value of the notify property changes.
1. In the component class, define a property named `notify` with an `@Output()` decorator and an instance of `EventEmitter()`. This allows the product alert component to emit an event when the value of the notify property changes.
<code-example path="getting-started/src/app/product-alerts/product-alerts.component.ts" region="input-output"></code-example>
<code-example path="getting-started/src/app/product-alerts/product-alerts.component.ts" header="src/app/product-alerts/product-alerts.component.ts" region="input-output"></code-example>
1. In the product alert template (`product-alerts.component.html`), update the "Notify Me" button with an event binding to call the `notify.emit()` method.
1. In the product alert template, `product-alerts.component.html`, update the "Notify Me" button with an event binding to call the `notify.emit()` method.
<code-example header="src/app/product-alerts/product-alerts.component.html" path="getting-started/src/app/product-alerts/product-alerts.component.html"></code-example>
1. Next, define the behavior that should happen when the button is clicked. Recall that it's the parent (product list component)&mdash;not the product alerts component&mdash;that's going to take the action. In the `product-list.component.ts` file, define an `onNotify()` method, similar to the `share()` method:
1. Next, define the behavior that should happen when the user clicks the button. Recall that it's the parent, product list component&mdash;not the product alerts component&mdash;that's acts when the child raises the event. In `product-list.component.ts`, define an `onNotify()` method, similar to the `share()` method:
<code-example header="src/app/product-list/product-list.component.ts" path="getting-started/src/app/product-list/product-list.component.ts" region="on-notify"></code-example>
1. Finally, update the product list component to receive output from the product alerts component.
1. Finally, update the product list component to receive output from the product alerts component.
In `product-list.component.html`, bind the `app-product-alerts` component (which is what displays the "Notify Me" button) to the `onNotify()` method of the product list component.
In `product-list.component.html`, bind the `app-product-alerts` component (which is what displays the "Notify Me" button) to the `onNotify()` method of the product list component.
<code-example header="src/app/product-list/product-list.component.html" path="getting-started/src/app/product-list/product-list.component.6.html" region="on-notify"></code-example>
1. Try out the "Notify Me" button:
1. Try the "Notify Me" button:
<figure>
<img src="generated/images/guide/start/product-alert-notification.png" alt="Product alert notification confirmation dialog">
@ -312,7 +330,7 @@ The "Notify Me" button doesn't do anything yet. In this section, you'll set up t
<div class="alert is-helpful">
Learn more: See [Component Interaction](guide/component-interaction "Components & Templates > Component Interaction") for more information about listening for events from child components, reading child properties or invoking child methods, and using a service for bi-directional communication within the family.
See [Component Interaction](guide/component-interaction "Components & Templates > Component Interaction") for more information about listening for events from child components, reading child properties or invoking child methods, and using a service for bi-directional communication between components.
</div>
@ -322,11 +340,11 @@ Learn more: See [Component Interaction](guide/component-interaction "Components
Congratulations! You've completed your first Angular app!
You have a basic online store catalog, with a product list, "Share" button, and "Notify Me" button.
You've learned about the foundation of Angular: components and template syntax.
You've also learned how the component class and template interact, and how components communicate with each other.
You have a basic online store catalog with a product list, "Share" button, and "Notify Me" button.
You've learned about the foundation of Angular: components and template syntax.
You've also learned how the component class and template interact, and how components communicate with each other.
To continue exploring Angular, choose either of the following options:
* [Continue to the "Routing" section](start/routing "Getting Started: Routing") to create a product details page that can be accessed by clicking a product name and that has its own URL pattern.
* [Continue to the "Routing" section](start/routing "Getting Started: Routing") to create a product details page that can be accessed by clicking a product name and that has its own URL pattern.
* [Skip ahead to the "Deployment" section](start/deployment "Getting Started: Deployment") to move to local development, or deploy your app to Firebase or your own server.

View File

@ -23,7 +23,7 @@
"build-with-ivy": "yarn ~~build",
"prebuild-with-ivy-ci": "yarn setup-local --no-build-packages && node scripts/switch-to-ivy",
"build-with-ivy-ci": "yarn ~~build --progress=false",
"extract-cli-command-docs": "node tools/transforms/cli-docs-package/extract-cli-commands.js 6734efe52",
"extract-cli-command-docs": "node tools/transforms/cli-docs-package/extract-cli-commands.js e21aeeecd",
"lint": "yarn check-env && yarn docs-lint && ng lint && yarn example-lint && yarn tools-lint",
"test": "yarn check-env && ng test",
"pree2e": "yarn check-env && yarn update-webdriver",

View File

@ -65,10 +65,10 @@ export class TocService {
div.innerHTML = heading.innerHTML;
// Remove any `.github-links` or `.header-link` elements (along with their content).
div.querySelectorAll('.github-links, .header-link').forEach(removeNode);
querySelectorAll(div, '.github-links, .header-link').forEach(removeNode);
// Remove any remaining `a` elements (but keep their content).
div.querySelectorAll('a').forEach(anchorLink => {
querySelectorAll(div, 'a').forEach(anchorLink => {
// We want to keep the content of this anchor, so move it into its parent.
const parent = anchorLink.parentNode!;
while (anchorLink.childNodes.length) {
@ -88,10 +88,11 @@ export class TocService {
}
private findTocHeadings(docElement: Element): HTMLHeadingElement[] {
const headings = docElement.querySelectorAll('h1,h2,h3');
// const headings = querySelectorAll(docElement, 'h1,h2,h3');
const headings = querySelectorAll<HTMLHeadingElement>(docElement, 'h1,h2,h3');
const skipNoTocHeadings = (heading: HTMLHeadingElement) => !/(?:no-toc|notoc)/i.test(heading.className);
return Array.prototype.filter.call(headings, skipNoTocHeadings);
return headings.filter(skipNoTocHeadings);
}
private resetScrollSpyInfo() {
@ -127,6 +128,16 @@ export class TocService {
}
// Helpers
function querySelectorAll<K extends keyof HTMLElementTagNameMap>(parent: Element, selector: K): HTMLElementTagNameMap[K][];
function querySelectorAll<K extends keyof SVGElementTagNameMap>(parent: Element, selector: K): SVGElementTagNameMap[K][];
function querySelectorAll<E extends Element = Element>(parent: Element, selector: string): E[];
function querySelectorAll(parent: Element, selector: string) {
// Wrap the `NodeList` as a regular `Array` to have access to array methods.
// NOTE: IE11 does not even support some methods of `NodeList`, such as
// [NodeList#forEach()](https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach).
return Array.from(parent.querySelectorAll(selector));
}
function removeNode(node: Node): void {
if (node.parentNode !== null) {
// We cannot use `Node.remove()` because of IE11.

View File

@ -49,8 +49,8 @@ aio-shell.page-resources mat-toolbar.mat-toolbar {
aio-shell.folder-api mat-toolbar.mat-toolbar,
aio-shell.folder-cli mat-toolbar.mat-toolbar,
aio-shell.folder-docs mat-toolbar.mat-toolbar,
aio-shell.folder-getting-started mat-toolbar.mat-toolbar,
aio-shell.folder-guide mat-toolbar.mat-toolbar,
aio-shell.folder-start mat-toolbar.mat-toolbar,
aio-shell.folder-tutorial mat-toolbar.mat-toolbar {
@media (min-width: 992px) {
.hamburger.mat-button {

View File

@ -6,6 +6,10 @@ package(default_visibility = ["//modules/playground:__subpackages__"])
ng_module(
name = "relative_assets",
srcs = glob(["**/*.ts"]),
assets = [
"app/style.css",
"app/tpl.html",
],
# This example demonstrates how external resources can be loaded relatively, so we
# need to disable resource inlining.
inline_resources = False,

View File

@ -6,7 +6,10 @@ package(default_visibility = ["//modules/playground:__subpackages__"])
ng_module(
name = "todo",
srcs = glob(["**/*.ts"]),
assets = ["todo.html"],
assets = [
"todo.html",
"css/base.css",
],
tsconfig = "//modules/playground:tsconfig-build.json",
# TODO: FW-1004 Type checking is currently not complete.
type_check = False,

View File

@ -1,6 +1,6 @@
{
"name": "angular-srcs",
"version": "8.2.6",
"version": "8.2.9",
"private": true,
"description": "Angular - a web framework for modern web apps",
"homepage": "https://github.com/angular/angular",

View File

@ -707,7 +707,7 @@ export function group(
*
* ```typescript
* sequence([
* style({ opacity: 0 })),
* style({ opacity: 0 }),
* animate("1s", style({ opacity: 1 }))
* ])
* ```

View File

@ -109,7 +109,7 @@ function main(args: string[]): number {
* @param inputPath Path to the file in the input tree.
* @param fileContent Content of the file.
*/
function writeFileFromInputPath(inputPath: string, fileContent: string) {
function writeFileFromInputPath(inputPath: string, fileContent: string | Buffer) {
// We want the relative path from the given file to its ancestor "root" directory.
// This root depends on whether the file lives in the source tree (srcDir) as a basic file
// input to ng_package, the bin output tree (binDir) as the output of another rule, or
@ -127,7 +127,7 @@ function main(args: string[]): number {
// Always ensure that the target directory exists.
shx.mkdir('-p', path.dirname(outputPath));
fs.writeFileSync(outputPath, fileContent, 'utf-8');
fs.writeFileSync(outputPath, fileContent);
}
/**
@ -135,7 +135,7 @@ function main(args: string[]): number {
* @param inputPath a path relative to the binDir, typically from a file in the deps[]
*/
function copyFileFromInputPath(inputPath: string) {
writeFileFromInputPath(inputPath, fs.readFileSync(inputPath, 'utf-8'));
writeFileFromInputPath(inputPath, fs.readFileSync(inputPath));
}
/**

View File

@ -22,6 +22,7 @@ ng_package(
":arbitrary_bin_file",
":arbitrary_genfiles_file",
":extra-styles.css",
":logo.png",
],
entry_point = ":index.ts",
entry_point_name = "waffels",

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

View File

@ -42,6 +42,7 @@ fesm5
fesm5/secondary.js.map
fesm5/waffels.js
fesm5/waffels.js.map
logo.png
package.json
secondary
secondary/package.json
@ -987,6 +988,10 @@ export { MyModule };
//# sourceMappingURL=waffels.js.map
--- logo.png ---
9db278d630f5fabd8e7ba16c2e329a3a
--- package.json ---
{

View File

@ -6,6 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
import * as crypto from 'crypto';
import {createPatch} from 'diff';
import * as fs from 'fs';
import * as path from 'path';
@ -64,6 +65,10 @@ function getDescendantFilesContents(directoryPath: string): string[] {
result.push(...getDescendantFilesContents(path.posix.join(directoryPath, dir)));
});
}
// Binary files should equal the same as in the srcdir.
else if (path.extname(directoryPath) === '.png') {
result.push(`--- ${directoryPath} ---`, '', hashFileContents(directoryPath), '');
}
// Note that we don't want to include ".map" files in the golden file since these are not
// consistent across different environments (e.g. path delimiters)
else if (path.extname(directoryPath) !== '.map') {
@ -128,6 +133,10 @@ function readFileContents(filePath: string): string {
return fs.readFileSync(filePath, 'utf8').replace(/\r/g, '');
}
function hashFileContents(filePath: string): string {
return crypto.createHash('md5').update(fs.readFileSync(filePath)).digest('hex');
}
if (require.main === module) {
const args = process.argv.slice(2);
const acceptingNewGold = (args[0] === '--accept');

View File

@ -20,6 +20,12 @@ import {HttpEvent, HttpResponse} from './response';
/**
* Constructs an instance of `HttpRequestOptions<T>` from a source `HttpMethodOptions` and
* the given `body`. This function clones the object and adds the body.
*
* Note that the `responseType` *options* value is a String that identifies the
* single data type of the response.
* A single overload version of the method handles each response type.
* The value of `responseType` cannot be a union, as the combined signature could imply.
*
*/
function addBody<T>(
options: {
@ -46,10 +52,15 @@ export type HttpObserve = 'body' | 'events' | 'response';
/**
* Performs HTTP requests.
*
* This service is available as an injectable class, with methods to perform HTTP requests.
* Each request method has multiple signatures, and the return type varies based on
* the signature that is called (mainly the values of `observe` and `responseType`).
*
* Note that the `responseType` *options* value is a String that identifies the
* single data type of the response.
* A single overload version of the method handles each response type.
* The value of `responseType` cannot be a union, as the combined signature could imply.
*
* @usageNotes
* Sample HTTP requests for the [Tour of Heroes](/tutorial/toh-pt0) application.

View File

@ -198,7 +198,8 @@ export class AngularJSUrlCodec implements UrlCodec {
// https://github.com/angular/angular.js/blob/864c7f0/src/ng/urlUtils.js#L60
parse(url: string, base?: string) {
try {
const parsed = new URL(url, base);
// Safari 12 throws an error when the URL constructor is called with an undefined base.
const parsed = !base ? new URL(url) : new URL(url, base);
return {
href: parsed.href,
protocol: parsed.protocol ? parsed.protocol.replace(/:$/, '') : '',
@ -335,4 +336,4 @@ function encodeUriQuery(val: string, pctEncodeSpaces: boolean = false) {
.replace(/%2C/gi, ',')
.replace(/%3B/gi, ';')
.replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
}
}

View File

@ -238,7 +238,7 @@ class ExpressionDiagnosticsVisitor extends RecursiveTemplateAstVisitor {
'The template context does not have an implicit value', spanOf(ast.sourceSpan));
} else {
this.reportError(
`The template context does not defined a member called '${ast.value}'`,
`The template context does not define a member called '${ast.value}'`,
spanOf(ast.sourceSpan));
}
}

View File

@ -32,10 +32,14 @@ js_size_tracking_test(
":bundle",
":bundle.golden_size_map.json",
],
goldenFile = "angular/packages/core/test/bundling/core_all/bundle.golden_size_map.json",
maxByteDiff = 250,
maxPercentageDiff = 15,
sourceMap = "angular/packages/core/test/bundling/core_all/bundle.min.js.map",
golden_file = "angular/packages/core/test/bundling/core_all/bundle.golden_size_map.json",
max_byte_diff = 250,
max_percentage_diff = 15,
# Ensures that this target runs with "--define=compile=aot" (aka Ivy). This is necessary
# because we don't run this test on CI currently, but if we run it manually, we need to
# ensure that it runs with Ivy for proper size comparisons.
required_compile_mode = "aot",
source_map = "angular/packages/core/test/bundling/core_all/bundle.min.js.map",
tags = [
"ivy-only",
"manual",

View File

@ -7,7 +7,7 @@
*/
import {StaticSymbolResolverHost} from '@angular/compiler';
import {CompilerOptions, MetadataCollector, MetadataReaderHost, createMetadataReaderCache, readMetadata} from '@angular/compiler-cli/src/language_services';
import {MetadataCollector, MetadataReaderHost, createMetadataReaderCache, readMetadata} from '@angular/compiler-cli/src/language_services';
import * as path from 'path';
import * as ts from 'typescript';
@ -48,13 +48,23 @@ class ReflectorModuleModuleResolutionHost implements ts.ModuleResolutionHost, Me
}
export class ReflectorHost implements StaticSymbolResolverHost {
private hostAdapter: ReflectorModuleModuleResolutionHost;
private metadataReaderCache = createMetadataReaderCache();
private readonly hostAdapter: ReflectorModuleModuleResolutionHost;
private readonly metadataReaderCache = createMetadataReaderCache();
private readonly moduleResolutionCache: ts.ModuleResolutionCache;
private readonly fakeContainingPath: string;
constructor(
getProgram: () => ts.Program, serviceHost: ts.LanguageServiceHost,
private options: CompilerOptions) {
this.hostAdapter = new ReflectorModuleModuleResolutionHost(serviceHost, getProgram);
getProgram: () => ts.Program, private readonly tsLSHost: ts.LanguageServiceHost, _: {}) {
// tsLSHost.getCurrentDirectory() returns the directory where tsconfig.json
// is located. This is not the same as process.cwd() because the language
// service host sets the "project root path" as its current directory.
const currentDir = tsLSHost.getCurrentDirectory();
this.fakeContainingPath = currentDir ? path.join(currentDir, 'fakeContainingFile.ts') : '';
this.hostAdapter = new ReflectorModuleModuleResolutionHost(tsLSHost, getProgram);
this.moduleResolutionCache = ts.createModuleResolutionCache(
currentDir,
s => s, // getCanonicalFileName
tsLSHost.getCompilationSettings());
}
getMetadataFor(modulePath: string): {[key: string]: any}[]|undefined {
@ -63,15 +73,22 @@ export class ReflectorHost implements StaticSymbolResolverHost {
moduleNameToFileName(moduleName: string, containingFile?: string): string|null {
if (!containingFile) {
if (moduleName.indexOf('.') === 0) {
if (moduleName.startsWith('.')) {
throw new Error('Resolution of relative paths requires a containing file.');
}
// Any containing file gives the same result for absolute imports
containingFile = path.join(this.options.basePath !, 'index.ts').replace(/\\/g, '/');
if (!this.fakeContainingPath) {
// If current directory is empty then the file must belong to an inferred
// project (no tsconfig.json), in which case it's not possible to resolve
// the module without the caller explicitly providing a containing file.
throw new Error(`Could not resolve '${moduleName}' without a containing file.`);
}
containingFile = this.fakeContainingPath;
}
const resolved =
ts.resolveModuleName(moduleName, containingFile !, this.options, this.hostAdapter)
.resolvedModule;
const compilerOptions = this.tsLSHost.getCompilationSettings();
const resolved = ts.resolveModuleName(
moduleName, containingFile, compilerOptions, this.hostAdapter,
this.moduleResolutionCache)
.resolvedModule;
return resolved ? resolved.resolvedFileName : null;
}

View File

@ -20,7 +20,7 @@ describe('reflector_host_spec', () => {
const originalJoin = path.join;
const originalPosixJoin = path.posix.join;
let mockHost =
new MockTypescriptHost(['/app/main.ts', '/app/parsing-cases.ts'], toh, 'app/node_modules', {
new MockTypescriptHost(['/app/main.ts', '/app/parsing-cases.ts'], toh, 'node_modules', {
...path,
join: (...args: string[]) => originalJoin.apply(path, args),
posix:
@ -37,4 +37,4 @@ describe('reflector_host_spec', () => {
const result = reflectorHost.moduleNameToFileName('@angular/core');
expect(result).not.toBeNull('could not find @angular/core using path.win32');
});
});
});

View File

@ -180,7 +180,7 @@ describe('plugin', () => {
'Identifier \'people_1\' is not defined. The component declaration, template variable declarations, and element references do not contain such a member');
});
it('should report an unknown context reference', () => {
expectError('even_1', 'The template context does not defined a member called \'even_1\'');
expectError('even_1', 'The template context does not define a member called \'even_1\'');
});
it('should report an unknown value in a key expression', () => {
expectError(
@ -193,8 +193,7 @@ describe('plugin', () => {
expectSemanticError('app/ng-if-cases.ts', locationMarker, message);
}
it('should report an implicit context reference', () => {
expectError(
'implicit', 'The template context does not defined a member called \'unknown\'');
expectError('implicit', 'The template context does not define a member called \'unknown\'');
});
});
});

View File

@ -372,17 +372,14 @@ export type RunGuardsAndResolvers = 'pathParamsChange' | 'pathParamsOrQueryParam
* into multiple bundles and loading them on demand.
* To use lazy loading, provide the `loadChildren` property instead of the `children` property.
*
* Given the following example route, the router uses the registered
* `NgModuleFactoryLoader` to fetch an NgModule associated with 'team'.
* It then extracts the set of routes defined in that NgModule,
* and transparently adds those routes to the main configuration.
* Given the following example route, the router will lazy load
* the associated module on demand using the browser native import system.
*
* ```
* [{
* path: 'team/:id',
* component: Team,
* loadChildren: 'team'
* }]
* path: 'lazy',
* loadChildren: () => import('./lazy-route/lazy.module').then(mod => mod.LazyModule),
* }];
* ```
*
* @publicApi

View File

@ -16,7 +16,7 @@ export {CanActivate, CanActivateChild, CanDeactivate, CanLoad, Resolve} from './
export {DetachedRouteHandle, RouteReuseStrategy} from './route_reuse_strategy';
export {Navigation, NavigationExtras, Router} from './router';
export {ROUTES} from './router_config_loader';
export {ExtraOptions, ROUTER_CONFIGURATION, ROUTER_INITIALIZER, RouterModule, provideRoutes} from './router_module';
export {ExtraOptions, InitialNavigation, ROUTER_CONFIGURATION, ROUTER_INITIALIZER, RouterModule, provideRoutes} from './router_module';
export {ChildrenOutletContexts, OutletContext} from './router_outlet_context';
export {NoPreloading, PreloadAllModules, PreloadingStrategy, RouterPreloader} from './router_preloader';
export {ActivatedRoute, ActivatedRouteSnapshot, RouterState, RouterStateSnapshot} from './router_state';

View File

@ -379,7 +379,7 @@ export class Router {
/**
* Determines when the router updates the browser URL.
* By default (`"deferred"`), udates the browser URL after navigation has finished.
* By default (`"deferred"`), updates the browser URL after navigation has finished.
* Set to `'eager'` to update the browser URL at the beginning of navigation.
* You can choose to update early so that, if navigation fails,
* you can show an error message with the URL that failed.

View File

@ -233,16 +233,17 @@ export function provideRoutes(routes: Routes): any {
* Allowed values in an `ExtraOptions` object that configure
* when the router performs the initial navigation operation.
*
* * 'enabled' (Default) The initial navigation starts before the root component is created.
* The bootstrap is blocked until the initial navigation is complete.
* * 'enabled' - The initial navigation starts before the root component is created.
* The bootstrap is blocked until the initial navigation is complete. This value is required
* for [server-side rendering](guide/universal) to work.
* * 'disabled' - The initial navigation is not performed. The location listener is set up before
* the root component gets created. Use if there is a reason to have
* more control over when the router starts its initial navigation due to some complex
* initialization logic.
* * 'legacy_enabled'- The initial navigation starts after the root component has been created.
* * 'legacy_enabled'- (Default, for compatibility.) The initial navigation starts after the root component has been created.
* The bootstrap is not blocked until the initial navigation is complete. @deprecated
* * 'legacy_disabled'- The initial navigation is not performed. The location listener is set up
* after the root component gets created. @deprecated
* after the root component gets created. @deprecated since v4
* * `true` - same as 'legacy_enabled'. @deprecated since v4
* * `false` - same as 'legacy_disabled'. @deprecated since v4
*
@ -275,11 +276,24 @@ export interface ExtraOptions {
useHash?: boolean;
/**
* One of `enabled` (the default) or `disabled`.
* By default, the initial navigation starts before the root component is created.
* The bootstrap is blocked until the initial navigation is complete.
* One of `enabled` or `disabled`.
* When set to `enabled`, the initial navigation starts before the root component is created.
* The bootstrap is blocked until the initial navigation is complete. This value is required for
* [server-side rendering](guide/universal) to work.
* When set to `disabled`, the initial navigation is not performed.
* The location listener is set up before the root component gets created.
* Use if there is a reason to have more control over when the router
* starts its initial navigation due to some complex initialization logic.
*
* Legacy values are deprecated since v4 and should not be used for new applications:
*
* * `legacy_enabled` - Default for compatibility.
* The initial navigation starts after the root component has been created,
* but the bootstrap is not blocked until the initial navigation is complete.
* * `legacy_disabled` - The initial navigation is not performed.
* The location listener is set up after the root component gets created.
* * `true` - same as `legacy_enabled`.
* * `false` - same as `legacy_disabled`.
*/
initialNavigation?: InitialNavigation;
@ -317,24 +331,24 @@ export interface ExtraOptions {
*
* ```typescript
* class AppModule {
* constructor(router: Router, viewportScroller: ViewportScroller) {
* router.events.pipe(
* filter((e: Event): e is Scroll => e instanceof Scroll)
* ).subscribe(e => {
* if (e.position) {
* // backward navigation
* viewportScroller.scrollToPosition(e.position);
* } else if (e.anchor) {
* // anchor navigation
* viewportScroller.scrollToAnchor(e.anchor);
* } else {
* // forward navigation
* viewportScroller.scrollToPosition([0, 0]);
* }
* });
* }
* }
* ```
* constructor(router: Router, viewportScroller: ViewportScroller) {
* router.events.pipe(
* filter((e: Event): e is Scroll => e instanceof Scroll)
* ).subscribe(e => {
* if (e.position) {
* // backward navigation
* viewportScroller.scrollToPosition(e.position);
* } else if (e.anchor) {
* // anchor navigation
* viewportScroller.scrollToAnchor(e.anchor);
* } else {
* // forward navigation
* viewportScroller.scrollToPosition([0, 0]);
* }
* });
* }
* }
* ```
*/
scrollPositionRestoration?: 'disabled'|'enabled'|'top';

View File

@ -148,6 +148,9 @@ export declare class GuardsCheckStart extends RouterEvent {
toString(): string;
}
/** @deprecated */
export declare type InitialNavigation = true | false | 'enabled' | 'disabled' | 'legacy_enabled' | 'legacy_disabled';
export declare type LoadChildren = LoadChildrenCallback | DeprecatedLoadChildren;
export declare type LoadChildrenCallback = () => Type<any> | NgModuleFactory<any> | Observable<Type<any>> | Promise<NgModuleFactory<any> | Type<any> | any>;

View File

@ -14,10 +14,11 @@ load("@build_bazel_rules_nodejs//:defs.bzl", "nodejs_binary", "nodejs_test")
def js_size_tracking_test(
name,
src,
sourceMap,
goldenFile,
maxPercentageDiff,
maxByteDiff,
source_map,
golden_file,
max_percentage_diff,
max_byte_diff,
required_compile_mode = "",
data = [],
**kwargs):
all_data = data + [
@ -32,7 +33,15 @@ def js_size_tracking_test(
data = all_data,
entry_point = entry_point,
configuration_env_vars = ["compile"],
templated_args = [src, sourceMap, goldenFile, "%d" % maxPercentageDiff, "%d" % maxByteDiff, "false"],
templated_args = [
src,
source_map,
golden_file,
"%d" % max_percentage_diff,
"%d" % max_byte_diff,
"false",
required_compile_mode,
],
**kwargs
)
@ -42,6 +51,6 @@ def js_size_tracking_test(
data = all_data,
entry_point = entry_point,
configuration_env_vars = ["compile"],
templated_args = [src, sourceMap, goldenFile, "0", "0", "true"],
templated_args = [src, source_map, golden_file, "0", "0", "true", required_compile_mode],
**kwargs
)

View File

@ -14,24 +14,33 @@ import {FileSizeData} from './file_size_data';
if (require.main === module) {
const
[filePath, sourceMapPath, goldenPath, maxPercentageDiffArg, maxSizeDiffArg, writeGoldenArg] =
process.argv.slice(2);
[filePath, sourceMapPath, goldenPath, maxPercentageDiffArg, maxSizeDiffArg, writeGoldenArg,
requiredCompileMode] = process.argv.slice(2);
const status = main(
require.resolve(filePath), require.resolve(sourceMapPath), require.resolve(goldenPath),
writeGoldenArg === 'true', parseInt(maxPercentageDiffArg), parseInt(maxSizeDiffArg));
writeGoldenArg === 'true', parseInt(maxPercentageDiffArg), parseInt(maxSizeDiffArg),
requiredCompileMode);
process.exit(status ? 0 : 1);
}
export function main(
filePath: string, sourceMapPath: string, goldenSizeMapPath: string, writeGolden: boolean,
maxPercentageDiff: number, maxByteDiff: number): boolean {
maxPercentageDiff: number, maxByteDiff: number, requiredCompileMode: string): boolean {
const {sizeResult} = new SizeTracker(filePath, sourceMapPath);
const compileMode = process.env['compile'];
if (requiredCompileMode && compileMode !== requiredCompileMode) {
console.error(chalk.red(
`Expected the size-tracking tool to be run with: ` +
`--define=compile=${requiredCompileMode}`));
return false;
}
if (writeGolden) {
writeFileSync(goldenSizeMapPath, JSON.stringify(sizeResult, null, 2));
console.error(chalk.green(`Updated golden size data in ${goldenSizeMapPath}`));
return;
return true;
}
const expectedSizeData = <FileSizeData>JSON.parse(readFileSync(goldenSizeMapPath, 'utf8'));
@ -50,10 +59,10 @@ export function main(
console.error(chalk.red(` ${failurePrefix}${message}`));
});
const compile = process.env['compile'];
const defineFlag = (compile !== 'legacy') ? `--define=compile=${compile} ` : '';
const bazelTargetName = process.env['TEST_TARGET'];
const defineFlag = (compileMode !== 'legacy') ? `--define=compile=${compileMode} ` : '';
console.error(`\nThe golden file can be updated with the following command:`);
console.error(` yarn bazel run ${defineFlag}${bazelTargetName}.accept`);
return false;
}

View File

@ -80,7 +80,6 @@ jasmine_node_test(
# TODO: remove this once the boostrap.js workaround has been removed.
":package.json",
],
tags = ["local"],
)
# END-INTERNAL