Previously, the Angular AOT compiler would always add a
`ɵprov` to injectables. But in ngcc this resulted in duplicate `ɵprov`
properties since published libraries already have this property.
Now in ngtsc, trying to add a duplicate `ɵprov` property is an error,
while in ngcc the additional property is silently not added.
// FW-1750
PR Close#34085
Prior to this commit, the unknown element can happen twice for AOT-compiled components: once during compilation and once again at runtime. Due to the fact that `schemas` information is not present on Component and NgModule defs after AOT compilation, the second check (at runtime) may fail, even though the same check was successful at compile time. This commit updates the code to avoid the second check for AOT-compiled components by checking whether `schemas` information is present in a logic that executes the unknown element check.
PR Close#34024
the package.json in these tests points to file:dist/packages-dist which
is not materialized on renovate-bot, so the bot freaks out and fails to
update the lock files.
This means that the bot currently just opens up PRs that can't be merged.
Example: https://github.com/angular/angular/pull/34071
(In the past this worked nicely because we didn't keep the yarn.lock files
in the git repo for these projects, but that had a problem with unpined
depenedencies and undeterministic build/test runs).
For now it's better to disable the bot by removing all the package.jsons
from the config. We should revisit this in the future have the bot update
the root package.json instead.
PR Close#34074
When creating synthesized tagged template literals, one must provide both
the "cooked" text and the "raw" (unparsed) text. Previously there were no
good APIs for creating the AST nodes with raw text for such literals.
Recently the APIs were improved to support this, and they do an extra
check to ensure that the raw text parses to be equal to the cooked text.
It turns out there is a bug in this check -
see https://github.com/microsoft/TypeScript/issues/35374.
This commit works around the bug by synthesizing a "head" node and morphing
it by changing its `kind` into the required node type.
// FW-1747
PR Close#34065
With Angular CLI version 9 RC 3 we can run a single migration for a package using the name of the migration schematic.
We need to pass the schematic name as a value to the `migrate-only` option.
Ex:
```
ng update @angular/core --migrate-only migration-v9-undecorated-classes-with-di
```
See: https://github.com/angular/angular-cli/pull/16174
PR Close#33958
We don't collect/review the results from CI, so it's just a waste of CPU time.
It's sufficient if we are able to run these locally and manually.
PR Close#34057
This bring is changes to the @nodejs repository required for https://github.com/angular/angular/pull/33927. See release notes for more details: https://github.com/bazelbuild/rules_nodejs/releases/tag/0.41.0.
rules_nodejs is approaching 1.0 and breaking changes for that release are being made more frequently. In this release, the ts_devserver API changed and it no longer injects html script tags into a provided index.html file. The diff on this commit is large as this breaking change affects quite a few tests.
Also note that we don’t update @angular/bazel schematics and integration/bazel as 0.41.0 is not a recommended update for angular users yet due to the breaking changes in ts_devserver & web_package (now named pkg_web). When a suitable plain npm package that is in progress is finished then it will be possible to easily replace the html injection functionality removed from ts_devserver & pkg_web.
PR Close#33996
In order to keep integration tests on CI as determinitstic as possible,
we need to ensure that the same dependencies (including transitive ones)
are installed each time. One way to ensure that is using a lockfile
(such as `yarn.lock`) to pin the dependencies to exact versions. This
works as long as the lockfile itself is in-sync with the corresponding
`package.json`, which specifies the dependencies.
Ideally, we would run `yarn install` with the `--frozen-lockfile` option
to verify that the lockfile is in-sync with `package.json`, but we
cannot do that for integration projects, because we want to be able to
install the locally built Angular packages). Therefore, we must manually
esnure that the integration project lockfiles remain in-sync, which is
error-prone.
This commit introduces a helper script that performs some checks on each
project's (non-local) dependencies:
- Ensure that exact versions (not version ranges) are specified in
`package.json`. This reduces the probability of installing a breaking
version of a direct or transitive dependency, in case of an
out-of-sync lockfile.
- Ensure that the lockfile is in-sync with `package.json` wrt these
dependencies.
While these checks are not full-proof, they provide yet another line of
defense against indeterminism.
PR Close#33968
Since we cannot run `yarn install` with the `--frozen-lockfile` option
(because we want to be able to install the locally built Angular
packages), integration project lockfiles are susceptible to getting
out-of-sync with the corresponding `package.json`. When this happens,
yarn will install the latest available version that satisfies the
version range specified in `package.json`.
This commit adds another line of defense, by specifying exact versions
for the dependencies in `package.json` files (i.e. `1.33.7` instead of
`^1.33.0`). While transitive dependencies will be unpinned, this still
ensures that the same version of direct dependencies will be installed
in case of an out-of-sync lockfile, thus reducing the probability of
random failures.
PR Close#33968
In the `integration_test` CircleCI job, we run `yarn install` on all
projects in the `integration/` directory. If a project has no lockfile
or if the lockfile is out-of-sync with the corresponding `package.json`
file, then the installed dependency versions are no longer pinned, which
can result in different versions being installed between different runs
of the same job (if, for example, a new version is released for a
package) and breaks hermeticity.
This could be prevented by using the `--frozen-lockfile` option with
`yarn install`, but this is not possible with the current setup, because
yarn needs to be able to install the locally built Angular packages,
whose checksums will be different from the ones in the lockfile.
Therefore, we have to manually ensure that the lockfiles remain in-sync
with the corresponding `package.json` files for the rest of the
dependencies.
For example, previously, [cli-hello-world-lazy/yarn.lock][1] had an
entry for `@angular-devkit/build-angular@0.900.0-next.9` (pinned to
`0.900.0-next.9`), but [cli-hello-world-lazy/package.json][2] specified
the `@angular-devkit/build-angular` version as `^0.900.0-rc.0` (note the
leading caret). As a result, since the version in the lock file does not
much the one in `package.json`, the lockfile is ignored and the latest
available version that matches `^0.900.0-rc.0` is installed.
This, for example, started causing unrelated CI failures ([example][3]),
when `@angular-devkit/build-angular@9.0.0-rc.3` was released with a size
improvement.
This commit ensures that all integration projects have a lockfile and
that lockfiles are up-to-date (with the current `package.json` files).
[1]: https://github.com/angular/angular/blob/fc2f6b845/integration/cli-hello-world-lazy/yarn.lock#L13
[2]: https://github.com/angular/angular/blob/fc2f6b845/integration/cli-hello-world-lazy/package.json#L26
[3]: https://circleci.com/gh/angular/angular/535959#tests/containers/2
PR Close#33968
Commit 53fc2ed8bf added support for
determining index types accessed using index signatures, but did not
include support for index types accessed using dot notation:
```typescript
const obj<T>: { [key: string]: T };
obj['stringKey']. // gets `T.` completions
obj.stringKey. // did not peviously get `T.` completions
```
This adds support for determining an index type accessed via dot
notation by rigging an object's symbol table to return the string index
signature type a property access refers to, if that property does not
explicitly exist on the object. This is very similar to @ivanwonder's
work in #29811.
`SymbolWrapper` now takes an additional parameter to explicitly set the
type of the symbol wrapped. This is done because
`SymbolTableWrapper#get` only has access to the symbol of the index
type, _not_ the index signature symbol itself. An attempt to get the
type of the index type will give an error.
Closes#29811
Closes https://github.com/angular/vscode-ng-language-service/issues/126
PR Close#33884
Now that all compile decisions are determined by the define=angular_ivy_enabled
flag, we can remove the setting of the define=compile flag throughout the repo.
PR Close#33983
Use angular_ivy_enabled to determine if Ivy is being used for the ivy_test_selector.ts symbols.
Additionally, remove the reflect_metadata genrules as we not longer have a "jit" compile option
so all possible invocations result in the same generated file. Instead we can just commit this
file.
PR Close#33983
We need to migrate to using angular_ivy_enabled value to determine whether to use
Ivy or ViewEngine for package building scripts and for size-tracking and
symbol-extract tooling.
PR Close#33983
Since config=ivy now sets the define=compile flag and the define=angular_ivy_enabled
flag to cause usage of Ivy, we can update all of the documentation and scripts that
reference compile=aot to use config=ivy.
PR Close#33983
Beginning of migration away from --define=compile=* to --define=angular_ivy_enabled=*.
Additionally, to make it clearer to developers, we will encourage use of --config=ivy
instead of directy setting the --define flag, this abstraction will allow us more
flexibility as we move foward with relation to our compile decisions at build time.
PR Close#33983
Since we created the migration guide for the `missing-injectable` schematic, the schematic
changed in various ways. e.g. the migration no longer migrates classes passed to `useExisting`
Additionally the migration has been expanded to handle another Ivy breaking change where
providers like `{provide: X}` will be intepreted as `{provide: X, useClass: X}`. This pattern should
be documented in the migration guide.
PR Close#33960
Prior to this commit, there was a runtime check in i18n logic to make sure "other" case is always present in an ICU. That was not a requirement in View Engine, so ICUs that previously worked may produce errors. This commit removes that restriction and adds support for ICUs without "other" cases.
PR Close#34042
Previously, indexing a container type would not return completions for
the indexed type because for every TypeScript type, the recorded index
type was always marked as `undefined`, regardless of the index
signature.
This PR now returns the index type of TypeScript containers with numeric
or string index signatures. This allows use to generate completions for
arrays and defined index types:
```typescript
interface Container<T> {
[key: string]: T;
}
const ctr: Container<T>;
ctr['stringKey']. // gives `T.` completions
const arr: T[];
arr[0]. // gives `T.` completions
```
Note that this does _not_ provide completions for properties indexed by
string literals, e.g.
```typescript
interface Container<T> {
foo: T;
}
const ctr: Container<T>;
ctr['foo']. // does not give `T.` completions
```
Closes angular/vscode-ng-language-service#110
Closes angular/vscode-ng-language-service#277
PR Close#34047
Move a view only if it would end up at a different place.
Otherwise we would do unnecessary processing like DOM manipulation, query notifications etc.
Thanks to @pkozlowski-opensource for the change.
PR Close#34052
When inserting a `viewRef` it is possible to not provide
an `index`, which is regarded as appending to the end of
the container.
If the `viewRef` already exists in the container, then
this results in a move. But there was a fault in the logic
that computed where to insert the `viewRef` that did not
account for the fact that the `viewRef` was already in
the container, so the insertion `index` was outside the
bounds of the array.
Fixes#33924
PR Close#34052
Prior to this commit, all styles extracted from Component's template (defined using <style> tags) were ignored by JIT compiler, so only `styles` array values defined in @Component decorator were used. This change updates JIT compiler to take styles extracted from the template into account. It also ensures correct order where `styles` array values are applied first and template styles are applied second.
PR Close#34017
This commit fixes a compatibility bug where pre-order lifecycle
hooks (onInit, doCheck, OnChanges) for directives on the same
host node were executed based on the order the directives were
matched, rather than the order the directives were instantiated
(i.e. injection order).
This discrepancy can cause issues with forms, where it is common
to inject NgControl and try to extract its control property in
ngOnInit. As the NgControl directive is injected, it should be
instantiated before the control value accessor directive (and
thus its hooks should run first). This ensures that the NgControl
ngOnInit can set up the form control before the ngOnInit
for the control value accessor tries to access it.
Closes#32522
PR Close#34026
These apis have been deprecated in v8, so they should stick around till v10,
but since they are defunct we are removing them early so that they don't take up payload size.
PR Close#33949
At the end of the `integration/run_tests.sh` script, we check and upload
the payload sizes of UMD bundles in `dist/packages-dist/`. At some
point, we started sharding the integration tests on CI to speed the
overall build time. As a result, checking and uploading of UMD bundle
sizes was run multiple times (once per shard).
Given that the data is identical on each shard, the data was just
overwriting the previously uploaded data. Even if the end result is the
same, checking and uploading the data multiple times is wasteful.
This commit fixes `integration/run_tests.sh` to only check/upload UMD
bundle sizes on the 1st shard.
PR Close#33987
The change type was only recorded for `aio/` and was not correct anyway.
For example:
- It considered `package.json` changes as `application` (even if only
`package.json` and `yarn.lock` had changed).
- It failed to account for changes in `@angular/*` dependencies, when
using the locally built Angular packages (instead reporting them as
`other`).
- It only looked at the last commit, so it failed to provide accurate
information for multi-commit builds (which are rare, but possible).
For the above reasons (and because there is no straight-forward way of
fixing it), this commit removes the change type from the uploaded data.
If necessary, it is still possible to find the type of changes from the
uploaded info (e.g. extract the associated commits and look at their
changes using git).
PR Close#33987
As part of the `payload-size` npm script in `aio/package.json` (which is
run on CI), the sizes of the angular.io app bundles are checked to
ensure they do not exceed certain limits and are also uploaded to
Firebase to be available for later analysis. The uploaded data include
the type of the changes (dependencies only, application only, or both).
The type of changes is inferred by looking at the files that have
changed inside the `aio/` directory.
When the `payload-size.sh` script was first introduced, the only files
that could affect bundle sizes were inside the `aio/` directory.
Therefore, the script would skip uploading the data and checking the
sizes if no changes were detected inside the `aio/` directory.
However, this assumption stopped being valid over time. For example:
- We started tracking/checking bundle sizes when building the angular.io
app with the locally built Angular packages (which live outside the
`aio/` directory.
- Due to CircleCI limitations, the `CI_COMMIT_RANGE` environment
variable (which is used for determining what files have been affected)
stopped reflecting the whole commit range of the build and only
included the last commit instead.
Based on the above, there were many cases were size data would not be
uploaded to Firebase, even when they may have been affected (because the
affecting changes were outside `aio/` - e.g. in framework packages).
This makes it harder to analyze size regressions, because important
data-points are missing.
Even worse, in these cases, the sizes were not even checked against the
specified limits, thus making it possible for size regressions to go
unnoticed (unless caught by other similar tests).
This commit fixes the `scripts/ci/payload-size.sh` script to always
track and check payload sizes for angular.io bundles.
NOTE: This change will result in more data being recorded (i.e.
recording data when it is not possible for the bundle sizes to
have been affected by the changes). This is still preferable to
failing to record and/or check when sizes could have been
affected.
PR Close#33987
Micro-benchmarks were broken after we've introduced concept of
DECLARATION_COMPONENT_VIEW on LView (after this change embedded
views must have a pointer to a parent LView).
PR Close#34031
The root view case is already covered by the existing code in the
getRenderParent function so no need to have an explicit checks
(and associated memory reads) again.
PR Close#33988
We need to make is_ivy_enabled public to allow the internal i18n
build rule to rely on it rather than relying on compile_strategy.
After we move the internal i18n rule to rely on is_ivy_enabled,
compile_strategy can then be removed.
PR Close#33992
Previously, our incremental build system kept track of the changes between
the current compilation and the previous one, and used its knowledge of
inter-file dependencies to evaluate the impact of each change and emit the
right set of output files.
However, a problem arose if the compiler was not able to extract a
dependency graph successfully. This typically happens if the input program
contains errors. In this case the Angular analysis part of compilation is
never executed.
If a file changed in one of these failed builds, in the next build it
appears unchanged. This means that the compiler "forgets" to emit it!
To fix this problem, the compiler needs to know the set of changes made
_since the last successful build_, not simply since the last invocation.
This commit changes the incremental state system to much more explicitly
pass information from the previous to the next compilation, and in the
process to keep track of changes across multiple failed builds, until the
program can be analyzed successfully and the results of those changes
incorporated into the emit plan.
Fixes#32214
PR Close#33971
Previously the visible compiler name during the ng_module build action was
ngc/ngtsc. These names however are only really known to the compiler team.
Instead we should use more general terms for which compiler is used to match
how we speak about compiler choices.
PR Close#33995
This PR brings a couple of changes;
- Removes undeed dependencies in bazel targets such as `//packages/common` & `//packages/core`
- Removes RxJs usage
- Adds `document-register-element` to architect test targets
- Use @schematics/angular helpers
- Uses the standard `$source": "projectName"` to get the projectName, which is defined in the `schema.json`
- Use workspace writer to update the workspace config
PR Close#33723
Under bazel and Ivy we don't need the shim files to be emmited by default.
We still need to the shims for blaze however because google3 code imports them.
This improves build latency by 1-2 seconds per ng_module target.
PR Close#33765
The size diff threshold of 1% has proven to be too lenient for us
to catch size regressions in AIO. Since the AIO main bundle is
between 400-500 KB, a size regression must be between 4-5 KB before
it will cause the tests to fail. As a result, we may merge many
changes with smaller regressions of a few KB before the size test
eventually lets us know that the number has increased. The hope is
that lowering the threshold will help us catch the smaller
regressions during code review and prevent the size tests failing at
a random later time when someone catches the size "hot potato".
PR Close#33969
It will be easier to track regressions in size if fewer people
are approving size diffs in PRs. That way, we will have a few
people that have a fuller picture of where size changes are
coming from.
PR Close#33969
In efbbae5a4, the `publish_packages_as_artifacts` CircleCI job was
created to publish the build artifacts of PR builds on CI. In a8f4f14bd,
its scope was expanded to also publish build artifacts on non-PR builds.
The published artifacts names are constructed based on the PR number
(e.g. include `-pr12345-`), so on non-PR builds the names do not reflect
the source branch (instead, they include `-prfalse-`).
This commit fixes this by using the current branch name. For example,
artifact names for the `master` or `9.0.x` branch will include
`-master-` and `-9.0.x-` respectively (instead of `-prfalse-`).
(NOTE: For PRs, where branch name is `pull/12345`, the branch name is
transformed to `pr12345`.)
PR Close#33957
Before creating a mutating http request, service-worker
invalidates lru cache entry and writes to cache storage.
Therefore, cache storage failure can prevent making post requests.
Fix this by catching and logging cache error, add a test case.
Fixes#33793
PR Close#33930
In a package.json file, the "typings" or "types" field could be an array
of typings files. ngcc would previously crash unexpectedly for such
packages, as it assumed that the typings field would be a string. This
commit lets ngcc skip over such packages, as having multiple typing
entry-points is not supported for Angular packages so it is safe to
ignore them.
Fixes#33646
PR Close#33973
The url_tree equalQueryParams and containsQueryParam methods did not handle query params that has arrays, which resulted in the routerLinkActive to not behave as expected, change was made to ensure query params with arrays are handled correctly
fixes#22223
PR Close#22666
This introduces a second possible define flag for informing bazel to build with ivy, but
does not remove the old `compile=aot` flag for configuration.
This is the first step in migrating away from using the `compile=aot` define flag.
PR Close#33975
The assertion that we have in the `directiveInject` instruction is too restrictive and we came across some pattern where it throws unnecessarily. This commit removes that assertion for now and more detailed investigation is needed to decide is we need to restrict the set of TNodeType again.
This commit also adds a test which triggered the TNodeType.View to come up in the `directiveInject` instruction, so it might be useful to avoid regressions during further refactoring.
PR Close#33948
link to the correct section of the HttpClientGuide:
if someone searches for CSRF (and not XSRF), she will not find the right section in the HttpClient guide
added CSRF as name of XSRF attack:
in order to make it easier to find the XSRF protection, I've added a reference to the other name "CSRF". The security guide has the same reference to XSRF/CSRF.
When I searched for this feature, I had quite some problems to find it because of this missing reference
PR Close#32933
The search input has 50% width of the parent container in a focused
state for the big break point (> 1000px). In this case when window width
is between 1000px and 1115px the search input shrinks from 180 to
~123px. The width of the search input was increased to 80% so that when
focused its width expands from 180 to 196px when window size is 1000px.
Fixes#33305
PR Close#33804
In 5d5c94d83, the deprecated `versionedFiles` option from the SW
asset-group configuration in `ngsw-config.json`. As a result, the
option would be silently ignored and the runtime behavior of the SW
would change (i.e. some files might not be cached and available offline
any more). This change could be easily go unnoticed by the developer.
This commit ensures this does not happen by throwing a build-time error,
when detecting the unsupported `versionedFiles` option with an error
message prompting the user to use the `files` option instead.
Jira issue: [FW-1727](https://angular-team.atlassian.net/browse/FW-1727)
PR Close#33903
Recently the ngtsc translator was modified to be more `ScriptTarget`
aware, which basically means that it will not generate non-ES5 code
when the output format is ES5 or similar.
This commit enhances that change by also "downleveling" localized
messages. In ES2015 the messages use tagged template literals, which
are not available in ES5.
PR Close#33857
We have determined that the upload time cost of remote caching via http is too costly
to be effective for our distributed usage scenario. However this cost is still worth
it for us for Windows CI runs on a full cache hit move from a ~60 minute task to ~10
minutes.
It is worth noting that this remote http-caching is entirely separate from RBE caching
mechanisms.
PR Close#33907
Due to the fact that Tsickle runs between analyze and transform phases in Angular, Tsickle may transform nodes (add comments with type annotations for Closure) that we captured during the analyze phase. As a result, some patterns where a function is returned from another function may trigger automatic semicolon insertion, which breaks the code (makes functions return `undefined` instead of a function). In order to avoid the problem, this commit updates the code to wrap all functions in some expression ("privders" and "viewProviders") in parentheses. More info can be found in Tsickle source code here: d797426257/src/jsdoc_transformer.ts (L1021)
PR Close#33609
When ngtsc comes across a source file during partial evaluation, it
would determine all exported symbols from that module and evaluate their
values greedily. This greedy evaluation strategy introduces unnecessary
work and can fall into infinite recursion when the evaluation result of
an exported expression would circularly depend on the source file. This
would primarily occur in CommonJS code, where the `exports` variable can
be used to refer to an exported variable. This variable would be
resolved to the source file itself, thereby greedily evaluating all
exported symbols and thus ending up evaluating the `exports` variable
again. This variable would be resolved to the source file itself,
thereby greedily evaluating all exported symbols and thus ending u
evaluating the `exports` variable again. This variable would be
resolved to the source file itself, thereby greedily evaluating all
exported symbols and thus ending up evaluating the `exports` variable
again. This variable would be resolved to the source file itself,
thereby greedily evaluating all exported symbols and thus ending up
evaluating the `exports` variable again. This went on for some time
until all stack frames were exhausted.
This commit introduces a `ResolvedModule` that delays the evaluation of
its exports until they are actually requested. This avoids the circular
dependency when evaluating `exports`, thereby fixing the issue.
Fix#33734
PR Close#33772
The template type checker generates code to check directive inputs and
outputs, whose name may contain characters that can not be used as
identifier in TypeScript. Prior to this change, such names would be
emitted into the generated code as is, resulting in invalid code and
unexpected template type check errors.
This commit fixes the bug by representing the potentially invalid names
as string literal instead of raw identifier.
Fixes#33590
PR Close#33741
NgModule compilation in JIT mode (that is also used in TestBed) caches module scopes on NgModule defs (using `transitiveCompileScopes` field). Module overrides (defined via TestBed.overrideModule) may invalidate this data by adding/removing items in `declarations` list. This commit forces TestBed to recalculate transitive scopes in case module overrides are present, so TestBed always gets the most up-to-date information.
PR Close#33787
This change enables "var(--my-var)" to pass through the style sanitizer.
After consulation with our security team, allowing these doesn't create
new attack vectors, so the sanitizer doesn't need to strip them.
Fixes parts of #23485 related to the sanitizer, other use cases discussed
there related to binding have been addressed via other changes to the
class and style handling in the runtime.
Closes#23485
PR Close#33841
Previously, the generated StackBlitz examples as well as the
corresponding downloadable zips for the `http` guide examples were not
correct and thus trying to run the app and/or tests would fail.
This commit fixes the examples:
- Replace `TestBed.inject()` (which was [introduced in v9][1]) with
`TestBed.get()` (which is available in v8 used in the examples).
(NOTE: The examples will soon be updated to v9 (as part of
[FW-1609][2] and switched back to `TestBed.inject()` then.)
- Include `src/app/heroes/hero.ts` in the zip, because it is referenced
by some of the other files and the compilation fails without it.
- Ensure `src/main-specs.ts` is not included in the zip that does not
include the tests. Including the file broke the app, because there is
logic in our zip-builder that renamed `main-*.ts` files to `main.ts`
and thus `main-specs.ts` ended up overwriting the actual `main.ts`.
[1]: https://next.angular.io/guide/deprecations#angularcoretesting
[2]: https://angular-team.atlassian.net/browse/FW-1609Fixes#33874Fixes#33945
PR Close#33941
This commit transforms the setClassMetadata calls generated by ngtsc from:
```typescript
/*@__PURE__*/ setClassMetadata(...);
```
to:
```typescript
/*@__PURE__*/ (function() {
setClassMetadata(...);
})();
```
Without the IIFE, terser won't remove these function calls because the
function calls have arguments that themselves are function calls or other
impure expressions. In order to make the whole block be DCE-ed by terser,
we wrap it into IIFE and mark the IIFE as pure.
It should be noted that this change doesn't have any impact on CLI* with
build-optimizer, which removes the whole setClassMetadata block within
the webpack loader, so terser or webpack itself don't get to see it at
all. This is done to prevent cross-chunk retention issues caused by
webpack's internal module registry.
* actually we do expect a short-term size regression while
https://github.com/angular/angular-cli/pull/16228
is merged and released in the next rc of the CLI. But long term this
change does nothing to CLI + build-optimizer configuration and is done
primarly to correct the seemingly correct but non-function PURE annotation
that builds not using build-optimizer could rely on.
PR Close#33337
NgModules in Ivy have a definition which contains various different bits
of metadata about the module. In particular, this metadata falls into two
categories:
* metadata required to use the module at runtime (for bootstrapping, etc)
in AOT-only applications.
* metadata required to depend on the module from a JIT-compiled app.
The latter metadata consists of the module's declarations, imports, and
exports. To support JIT usage, this metadata must be included in the
generated code, especially if that code is shipped to NPM. However, because
this metadata preserves the entire NgModule graph (references to all
directives and components in the app), it needs to be removed during
optimization for AOT-only builds.
Previously, this was done with a clever design:
1. The extra metadata was added by a function called `setNgModuleScope`.
A call to this function was generated after each NgModule.
2. This function call was marked as "pure" with a comment and used
`noSideEffects` internally, which causes optimizers to remove it.
The effect was that in dev mode or test mode (which use JIT), no optimizer
runs and the full NgModule metadata was available at runtime. But in
production (presumably AOT) builds, the optimizer runs and removes the JIT-
specific metadata.
However, there are cases where apps that want to use JIT in production, and
still make an optimized build. In this case, the JIT-specific metadata would
be erroneously removed. This commit solves that problem by adding an
`ngJitMode` global variable which guards all `setNgModuleScope` calls. An
optimizer can be configured to statically define this global to be `false`
for AOT-only builds, causing the extra metadata to be stripped.
A configuration for Terser used by the CLI is provided in `tooling.ts` which
sets `ngJitMode` to `false` when building AOT apps.
PR Close#33671
The Ivy template type-checker is capable of inferring the type of a
structural directive (such as NgForOf<T>). Previously, this was done with
fullTemplateTypeCheck: true, even if strictTemplates was false. View Engine
previously did not do this inference, and so this causes breakages if the
type of the template context is not what the user expected.
In particular, consider the template:
```html
<div *ngFor="let user of users as all">
{{user.index}} out of {{all.length}}
</div>
```
As long as `users` is an array, this seems reasonable, because it appears
that `all` is an alias for the `users` array. However, this is misleading.
In reality, `NgForOf` is rendered with a template context that contains
both a `$implicit` value (for the loop variable `user`) as well as a
`ngForOf` value, which is the actual value assigned to `all`. The type of
`NgForOf`'s template context is `NgForContext<T>`, which declares `ngForOf`'s
type to be `NgIterable<T>`, which does not have a `length` property (due to
its incorporation of the `Iterable` type).
This commit stops the template type-checker from inferring template context
types unless strictTemplates is set (and strictInputTypes is not disabled).
Fixes#33527.
PR Close#33537
This commit changes the reporting of watch mode diagnostics for ngtsc to use
the same formatting as non-watch mode diagnostics. This prints rich and
contextual errors even in watch mode, which previously was not the case.
Fixes#32213
PR Close#33862
Previously, the ngtsc compiler attempted to reuse analysis work from the
previous program during an incremental build. To do this, it had to prove
that the work was safe to reuse - that no changes made to the new program
would invalidate the previous analysis.
The implementation of this had a significant design flaw: if the previous
program had errors, the previous analysis would be missing significant
information, and the dependency graph extracted from it would not be
sufficient to determine which files should be re-analyzed to fill in the
gaps. This often meant that the build output after an error was resolved
would be wholly incorrect.
This commit switches ngtsc to take a simpler approach to incremental
rebuilds. Instead of attempting to reuse prior analysis work, the entire
program is re-analyzed with each compilation. This is actually not as
expensive as one might imagine - analysis is a fairly small part of overall
compilation time.
Based on the dependency graph extracted during this analysis, the compiler
then can make accurate decisions on whether to emit specific files. A new
suite of tests is added to validate behavior in the presence of source code
level errors.
This new approach is dramatically simpler than the previous algorithm, and
should always produce correct results for a semantically correct program.s
Fixes#32388Fixes#32214
PR Close#33862
By clearing `sessionStorage` and unsubscribing from `Location` events,
after each test, we reduce the possibility of potential
[spooky action at a distance][1]-type of failures in the future.
This does not have an impact on the actual app, since `ScrollService` is
currently expected to live throughout the lifetime of the app. Still,
unsubscribing from `Location` events keeps the code consistent with how
other `ScrollService` listeners are handled (e.g. for `window` events).
[1]: https://en.wikipedia.org/wiki/Action_at_a_distance_(computer_programming)
PR Close#33937
`ScrollService` subscribes to global `window` events and mutates global
state in the listener (e.g. read/write values from/to `sessionStorage`).
Therefore, we need to always call its `ngOnDestroy()` method to
unsubscribe from these events after each test.
In f69c6e204, a new testcase was introduced that was not destroyed. As a
result, random failures started to randomly happen in other, unrelated
tests ([example CI failure][1]).
This commit fixes this by ensuring all `ScrollService` instances are
destroyed after each tests (provided that they are created with the
`createScrollService()` helper).
[1]: https://circleci.com/gh/angular/angular/533298
PR Close#33937
This adds a `tools/ng_rollup_bundle/terser_config.json` file to override the default terser_minified config provided by the rule. After this change, the layer violation in rules_nodejs can be fixed by removing `"global_defs": {"ngDevMode": false, "ngI18nClosureMode": false},` from `terser_config.default.json` in rules_nodejs.
Change requested by Alex Rickabaugh in https://github.com/bazelbuild/rules_nodejs/pull/1338.
PR Close#33865
Originally, QueryList implemented Iterable and provided a Symbol.iterator
on its prototype. This caused issues with tree-shaking, so QueryList was
refactored and the Symbol.iterator added in its constructor instead. As
part of this change, QueryList no longer implemented Iterable directly.
Unfortunately, this meant that QueryList was no longer assignable to
Iterable or, consequently, NgIterable. NgIterable is used for NgFor's input,
so this meant that QueryList was not usable (in a type sense) for NgFor
iteration. View Engine's template type checking would not catch this, but
Ivy's did.
As a fix, this commit adds the declaration (but not the implementation) of
the Symbol.iterator function back to QueryList. This has no runtime effect,
so it doesn't affect tree-shaking of QueryList, but it ensures that
QueryList is assignable to NgIterable and thus usable with NgFor.
Fixes#29842
PR Close#33536
Previously, the compiler assumed that all TS files logically within a
project existed under one or more "root directories". If the TS compiler
option `rootDir` or `rootDirs` was set, they would dictate the root
directories in use, otherwise the current directory was used.
Unfortunately this assumption was unfounded - it's common for projects
without explicit `rootDirs` to import from files outside the current
working directory. In such cases the `LogicalProjectStrategy` would attempt
to generate imports into those files, and fail. This would lead to no
`ReferenceEmitStrategy` being able to generate an import, and end in a
compiler assertion failure.
This commit introduces a new strategy to use when there are no `rootDirs`
explicitly present, the `RelativePathStrategy`. It uses simpler, filesystem-
relative paths to generate imports, even to files above the current working
directory.
Fixes#33659Fixes#33562
PR Close#33828
This commit adds the ability to change directories using the compiler's
internal filesystem abstraction. This is a prerequisite for writing tests
which are sensitive to the current working directory.
In addition to supporting the `chdir()` operation, this commit also fixes
`getDefaultLibLocation()` for mock filesystems to not assume `node_modules`
is in the current directory, but to resolve it similarly to how Node does
by progressively looking higher in the directory tree.
PR Close#33828
TNode.inputs are initialised during directives resolution now so we know early
if a node has directives with inputs or no. We don't need to use undefined value
as an indicator that inputs were not resolved yet.
PR Close#33798
Before this change a public name of a directive's input
was stored in 2 places:
- as a key of an object on TNode.index;
- as a value of PropertyAliasValue at the index 1
This PR changes the data structure so the public name is stored
only once as a key on TNode.index. This saves one array entry
for each and every directive input.
PR Close#33798
Whenever cookies are disabled in the browser, `window.sessionStorage` is not avaialable to the app (i.e. even trying to access `window.sessionStorage` throws an error).
To avoid breaking the app, we use a no-op `Storage` implementation if `window.sessionStorage` is not available.
Fixes#33795
PR Close#33829
This refactorings clearly separates the first and subsequent creation execution
of the `template` instruction. This approach has the following benefits:
- it is clear what happens during the first vs. subsequent executions;
- we can avoid several memory reads and checks after the first creation pass
(there is measurable performance improvement on various benchmarks);
- the template instructions becomes smaller and should become a candidate
for optimisations / inlining faster;
PR Close#33856
Since `scripts/package-builder.js` gets run from the
`aio` folder sometimes, it is important to set the cwd
for the command that finds the bazel bin directory.
PR Close#33904
The ReflectionHost supports enumeration of constructor parameters, and one
piece of information it returns describes the origin of the parameter's
type. Parameter types come in two flavors: local (the type is not imported
from anywhere) or non-local (the type comes via an import).
ngcc incorrectly classified all type parameters as 'local', because in the
source files that ngcc processes the type parameter is a real ts.Identifer.
However, that identifier may still have come from an import and thus might
be non-local.
This commit changes ngcc's ReflectionHost(s) to properly recognize and
report these non-local type references.
Fixes#33677
PR Close#33901
`ng_package` rule has an implicitly optional depedency on terser a48573efe8/packages/bazel/src/ng_package/ng_package.bzl (L36)
When using this rule without terser being available we get the below error;
```
ERROR: /home/circleci/ng/modules/express-engine/BUILD.bazel:22:1: every rule of type ng_package implicitly depends upon the target '@npm//terser/bin:terser', but this target could not be found because of: no such package '@npm//terser/bin': BUILD file not found in directory 'terser/bin' of external repository @npm. Add a BUILD file to a directory to mark it as a package.
ERROR: Analysis of target '//modules/express-engine:npm_package' failed; build aborted: no such package '@npm//terser/bin': BUILD file not found in directory 'terser/bin' of external repository @npm. Add a BUILD file to a directory to mark it as a package.
```
PR Close#33891
Since i18n messages are mapped to `$localize` tagged template strings,
the "raw" version must be properly escaped. Otherwise TS will throw an
error such as:
```
Error: Debug Failure. False expression: Expected argument 'text' to be the normalized (i.e. 'cooked') version of argument 'rawText'.
```
This commit ensures that we properly escape these raw strings before creating
TS AST nodes from them.
PR Close#33820
The `:` char is used as a metadata marker in `$localize` messages.
If this char appears in the metadata it must be escaped, as `\:`.
Previously, although the `:` char was being escaped, the TS AST
being generated was not correct and so it was being output double
escaped, which meant that it appeared in the rendered message.
As of TS 3.6.2 the "raw" string can be specified when creating tagged
template AST nodes, so it is possible to correct this.
PR Close#33820
When asking for a ViewContainerRef on <ng-container> we do reuse <ng-container> comment
node as a LContainer's anachor. Before this fix the act of re-using a <ng-container>'s
comment node would result in this comment node being re-appended to the DOM in the wrong
place. With the fix in this PR we make sure that re-using <ng-container>'s comment node
doesn't result in unwanted DOM manipulation (ng-gontainer's comment node is already part
of the DOM and doesn't have to be re-created / re-appended).
PR Close#33816
In View Engine, providers which neither used `useValue`, `useClass`,
`useFactory` or `useExisting`, were interpreted differently.
e.g.
```
{provide: X} -> {provide: X, useValue: undefined}, // this is how it works in View Engine
{provide: X} -> {provide: X, useClass: X}, // this is how it works in Ivy
```
The missing-injectable migration should migrate such providers to the
explicit `useValue` provider. This ensures that there is no unexpected
behavioral change when updating to v9.
PR Close#33709
Fixes issue introduced in https://github.com/angular/angular/pull/33808 for ng_rollup_bundle with `-spawn_strategy=standalone`. Without the sandbox (if --spawn_strategy=standalone is set) rollup can resolve to the non-esm .js file generated by ts_library instead of the desired .mjs. This fixes the problem by prioritizing .mjs.
Issue observed is of the flavor:
```
ERROR: modules/benchmarks/src/views/BUILD.bazel:20:1: Bundling JavaScript modules/benchmarks/src/views/bundle.es2015.js
[rollup] failed (Exit 1)
[!] Error: 'enableProdMode' is not exported by bazel-out/darwin-fastbuild/bin/packages/core/index.js
https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module
bazel-out/darwin-fastbuild/bin/modules/benchmarks/src/views/index.mjs (12:9)
10: * found in the LICENSE file at https://angular.io/license
11: */
12: import { enableProdMode } from '@angular/core';
^
13: import { platformBrowser } from '@angular/platform-browser';
14: import { ViewsBenchmarkModuleNgFactory } from './views-benchmark.ngfactory';
Error: 'enableProdMode' is not exported by bazel-out/darwin-fastbuild/bin/packages/core/index.js
```
PR Close#33867
In #32902 a bug was supposedly fixed where internal classes as used
within `ModuleWithProviders` are publicly exported, even when the
typings file already contained the generic type on the
`ModuleWithProviders`. This fix turns out to have been incomplete, as
the `ModuleWithProviders` analysis is not done when not processing the
typings files.
The effect of this bug is that formats that are processed after the
initial format had been processed would not have exports for internal
symbols, resulting in "export '...' was not found in '...'" errors.
This commit fixes the bug by always running the `ModuleWithProviders`
analyzer. An integration test has been added that would fail prior to
this change.
Fixes#33701
PR Close#33875
ngcc has a basic integration test infrastructure that downlevels
TypeScript code into bundle formats that need to be processed by ngcc.
Until now, only ES5 bundles were created with a flat structure, however
more complex scenarios require an APF-like layout containing multiple
bundle formats.
PR Close#33875
Some declaration files may not be referenced from an entry-point's
main typings file, as it may declare types that are only used internally.
ngcc has logic to include declaration files based on all source files,
to ensure internal declaration files are available.
For packages following APF layout, however, this logic was insufficient.
Consider an entry-point with base path of `/esm2015/testing` and typings
residing in `/testing`, the file
`/esm2015/testing/src/nested/internal.js` has its typings file at
`/testing/src/nested/internal.d.ts`. Previously, the declaration was
assumed to be located at `/esm2015/testing/testing/internal.d.ts` (by
means of `/esm2015/testing/src/nested/../../testing/internal.d.ts`)
which is not where the declaration file can be found. This commit
resolves the issue by looking in the correct directory.
PR Close#33875
By adding the `bash` language to the code snippet it will no
longer be auto-linked, which was causing a false positive link
to be rendered.
Fixes#33859
PR Close#33877
Previously any code block, which was not marked with
`no-auto-link` css class would have its contents auto-linked to
API pages. Sometimes this results in false positive links being
generated.
This is problematic for triple backticked blocks, which cannot provide
the `no-auto-link` CSS class to prevent the linking.
This commit fixes the problem by allowing the auto-linker to be
configured not to auto-link code blocks that have been marked with an
"ignored" language. By default these are `bash` and `json`.
Triple backticked blocks are able to specify the language directly after
the first set of triple backticks.
Fixes#33859
PR Close#33877
In flat bundle formats, multiple classes that have the same name can be
suffixed to become unique. In ES5-like bundles this results in the outer
declaration from having a different name from the "implementation"
declaration within the class' IIFE, as the implementation declaration
may not have been suffixed.
As an example, the following code would fail to have a `Directive`
decorator as ngcc would search for `__decorate` calls that refer to
`AliasedDirective$1` by name, whereas the `__decorate` call actually
uses the `AliasedDirective` name.
```javascript
var AliasedDirective$1 = /** @class */ (function () {
function AliasedDirective() {}
AliasedDirective = tslib_1.__decorate([
Directive({ selector: '[someDirective]' }),
], AliasedDirective);
return AliasedDirective;
}());
```
This commit fixes the problem by not relying on comparing names, but
instead finding the declaration and matching it with both the outer
and inner declaration.
PR Close#33878
This fixes an issue bundling es2015 with ng_rollup_bundle that was covered up by a typo when refactoring ng_rollup_bundle to not use legacy rollup_bundle internals and to use the new terser_minified rule and npm_package_bin to call brotli.
Note: ng_rollup_bundle is only used in the angular repo and not externally so this issue does not affect users
PR Close#33808
In ccc76f749, `@angular/platform-webworker` and
`@angular/platform-webworker-dynamic` were deprecated (i.e. by
deprecating all their public APIs). However, some public
`@angular/platform-webworker` APIs were accidentally missed,
additionally resulting in the package itself not showing up as
deprecated on angular.io.
This commit fixes it by marking those remaining public APIs as
deprecated.
PR Close#33824
This commit fixes a bug whereby completions for attribute values are only
provided for directives that support the micro-syntax format, all other
bindings are ignored.
I'm not sure if this is a regresssion or a bug, because there were no
tests prior to this.
PR Close#33839
In #33823, `scripts/package-builds.sh` (which is used by both
`build-packages-dist.sh` and `build-ivy-npm-packages.sh`) was updated to
use `realpath`. It turns out that `realpath` does not exist on macOS, so
the build scripts do not work there.
In order to fix this (and also reduce the likelihood of introducing
similar issues in the future), this commit changes these bash scripts to
Node.js scripts (using [ShellJS](https://github.com/shelljs/shelljs) for
a cross-platform implementation of Unix shell commands where necessary).
PR Close#33854
This adds a `tools/ng_rollup_bundle/terser_config.json` file to override the default terser_minified config provided by the rule. After this change, the layer violation in rules_nodejs can be fixed by removing `"global_defs": {"ngDevMode": false, "ngI18nClosureMode": false},` from `terser_config.default.json` in rules_nodejs.
Change requested by Alex Rickabaugh in https://github.com/bazelbuild/rules_nodejs/pull/1338.
PR Close#33773
The earlier update to nodejs rules 0.40.0 fixes the cross-platform RBE issues with nodejs_binary. This commit adds a work-around for rules_webtesting cross-platform RBE issues.
PR Close#33708
This commit fixes a few issues with helper method
`getBuiltInTypeFromTsType`.
1. The function is wrongly named. It should be the other way round.
2. The ts.Type returned by the function should not contain any value.
This is because for some data types like Number and String, the
SourceFile (context.node) is not the correct value. Value is never
needed for program correctness in this case.
PR Close#33778
This commit fixes a bug brought up by @andrius-pra whereby the language
service host would recompute the analyzed modules even when none of the
source files changes. This is due to a bug in our unit test that
precludes non-TS files from incrementing the project version.
Consequently, when the external template is updated, the program remains
the same.
With the bug fixed, the next step is to figure out if any source files
have been added / changed / removed since the last computation. The
previously analyzed could be safely retained only when none of these
operations happen.
PR Close#33806
The method `getTemplateReferences()` appears in both the LanguageService
interface and LanguageServiceHost interface. It should belong in the
latter and not the former, since the former deals with the semantics of
the language and not the mechanics.
PR Close#33807
If the application is not running directly in the browser, e.g.
universal or app-shell, then the `$localize` import must be
adding to a different file than for normal browser applications.
This commit adds more information about this to avoid any
confusion.
// FW-1557
PR Close#33826
Now that terser_minified supports args as of nodejs rules 0.40.0, ng_rollup_bundle can updated to the pass —comments /a^/ to args can turn off all comments and maintain the current ng_rollup_bundle behavior with the latest version fo terser. //packages/core/test/bundling/todo:bundle.min.js size test passes with this fix.
Tho not strictly necessary to update terser, this will be a rough edge when someone does try it as it is not obvious why the //packages/core/test/bundling/todo:bundle.min.js size test fails. Updating now should save time in the future by not hitting this issue.\
This change also affect ng_package output as the default comments that are preserved by terser are now Comments with @preserve, @license, @cc_on as well as comments starting with /*! and /**! are now preserved by default.. (https://github.com/terser/terser/blob/master/CHANGELOG.md). Example ng_package golden file also updated as there are not some /*! comments preserved that were in older versions of terser.
PR Close#33835
In #33823, `scripts/package-builds.sh` (which is used by both
`build-packages-dist.sh` and `build-ivy-npm-packages.sh`) was updated to
use `realpath`. It turns out that `realpath` does not exist on macOS, so
the build scripts do not work there.
This commit fixes it by switching from `realpath $(pwd)/..` to
`dirname $(pwd)`, which does practically the same thing (in this
situation) and works on macOS as well.
PR Close#33843
Angular `9.0.0-rc.2` contains an update of CLDR data to `v36.0.0`. The localized data changed for some locales, and this is breaking tests that are checking the result of i18n applications. For example, the space separator used in numbers changed from `\xa0` to `\u202f`.
This commit adds a mention to this change in the release notes, so developers can more easily understand why some of their tests are failing when updating to v9.
PR Close#33848
Prior to this commit the assert that we have in `directiveInject` (assert introduced recently) didn't include IcuContainer TNode type and as a result, the error is thrown in case pipes with dependencies are used inside ICUs. This commit extends the assert to allow for IcuContainer TNode types.
PR Close#33832
This commit moves the `setLContainerActiveIndex` and `getLContainerActiveIndex` functions used in a few files to a common `util/view_util.ts` lib to avoid cyclical dependency while importing `instructions/container.ts` where these functions located originally.
PR Close#33831
The ng-add schematic for `@angular/bazel` should set up
the latest Bazel version v1.1.0 that contains fixes for
windows. e.g. 618e5a28f7
PR Close#33813
Updates Bazel to the latest stable version. Bazel 1.1.0
supposedly fixes a permission bug in Windows. Hence we
should try to update and see if that fixes the bug.
It's generally good to be up to date. See potential bug
fix commit:
618e5a28f7.
PR Close#33813
- Move "Building packages" log above actual work (computing targets).
- Print corrent script name (`build-ivy-npm-packages.sh` would claim to
be `build-packages-dist.sh`).
- Make logs of different operations a little more consistent.
PR Close#33823
The following files are consumed only by the language service and do not
have to be in compiler-cli:
1. expression_diagnostics.ts
2. expression_type.ts
3. typescript_symbols.ts
4. symbols.ts
PR Close#33809
Reference #33259
Removes figures elements as AIO is not typically using captions or image groups where figures would be necessary or appropriate
PR Close#33748
`<div class="hero-list" *ngIf="heroes else loading">` defines `heroes` as condition, but `hero-list` is used as condition in the transformed code `<ng-template [ngIf]="heroes" [ngIfElse]="loading">`.
PR Close#33425
The url_tree equalQueryParams and containsQueryParam methods did not handle query params that has arrays, which resulted in the routerLinkActive to not behave as expected, change was made to ensure query params with arrays are handled correctly
fixes#22223
PR Close#22666
Previously, ngcc's `Renderer` would add some constants in the processed
files which were emitted as ES2015 code (e.g. `const` declarations).
This would result in invalid ES5 generated code that would break when
run on browsers that do not support the emitted format.
This commit fixes it by adding a `printStatement()` method to
`RenderingFormatter`, which can convert statements to JavaScript code in
a suitable format for the corresponding `RenderingFormatter`.
Additionally, the `translateExpression()` and `translateStatement()`
ngtsc helper methods are augmented to accept an extra hint to know
whether the code needs to be translated to ES5 format or not.
Fixes#32665
PR Close#33514
While processing class metadata, ngtsc generates a `setClassMetadata()`
call which (among other things) contains info about property decorators.
Previously, processing getter/setter pairs with some of ngcc's
`ReflectionHost`s resulted in multiple metadata entries for the same
property, which resulted in duplicate object keys, which in turn causes
an error in ES5 strict mode.
This commit fixes it by ensuring that there are no duplicate property
names in the `setClassMetadata()` calls.
In addition, `generateSetClassMetadataCall()` is updated to treat
`ClassMember#decorators: []` the same as `ClassMember.decorators: null`
(i.e. omitting the `ClassMember` from the generated `setClassMetadata()`
call). Alternatively, ngcc's `ReflectionHost`s could be updated to do
this transformation (`decorators: []` --> `decorators: null`) when
reflecting on class members, but this would require changes in many
places and be less future-proof.
For example, given a class such as:
```ts
class Foo {
@Input() get bar() { return 'bar'; }
set bar(value: any) {}
}
```
...previously the generated `setClassMetadata()` call would look like:
```ts
ɵsetClassMetadata(..., {
bar: [{type: Input}],
bar: [],
});
```
The same class will now result in a call like:
```ts
ɵsetClassMetadata(..., {
bar: [{type: Input}],
});
```
Fixes#30569
PR Close#33514
Previously, due to a bug a `Context` with `isStatement: false` could be
returned in places where a `Context` with `isStatement: true` was
requested. As a result, some statements would be unnecessarily wrapped
in parenthesis.
This commit fixes the bug in `Context#withStatementMode` to always
return a `Context` with the correct `isStatement` value. Note that this
does not have any impact on the generated code other than avoiding some
superfluous parenthesis on certain statements.
PR Close#33514
Currently if a consumer does something like the following, the object literal will be shared across the two elements and any instances of the component template. The same applies to array literals:
```
<div [someDirective]="{}"></div>
<div [someDirective]="{}"></div>
```
These changes make it so that we generate a pure function even if an object is constant so that each instance gets its own object.
Note that the original design for this fix included moving the pure function factories into the `consts` array. In the process of doing so I realized that pure function are also used inside of directive host bindings which means that we don't have access to the `consts`.
These changes also:
* Fix an issue that meant that the `pureFunction0` instruction could only be run during creation mode.
* Make the `getConstant` utility slightly more convenient to use. This isn't strictly required for these changes to work, but I had made it as a part of a larger refactor that I ended up reverting.
PR Close#33705
This is a breaking change in nodejs rules 0.40.0 as part of the API review & cleanup for the 1.0 release. Their APIs are identical as ts_web_test was just karma_web_test without the config_file attribute.
PR Close#33802
In f78bda9ff, recommended configuration files were added to be used as
basis for setting up [Remote Development using docker containers][1] in
VSCode. Apparently, I had forgotten to commit the corresponding
`README.md` file.
This commit adds `.devcontainer/README.md` with more info on Remote
Development in VSCode.
[1]: https://code.visualstudio.com/docs/remote/containers
PR Close#33790
In order to speed up bazel build performance delete all rxjs d.ts files
that reference rxjs-compat.
For all ts_library and ng_module rules Bazel generates tsconfig.json file
that explicitly lists all d.ts files found in required npm package.
In case of rxjs, this means that tsconfig contains all d.ts files that
reference rxjs-compat package, which is an interop/backwards compatibility
package not installed in angular/angular repo.
But because tsconfig contains these d.ts files, tsc will try to resolve
them and silently fail. All these lookups are quite expensive and not
cached. This causes significant slowdown of the build under bazel.
This change removes all of these problematic rxjs d.ts files via an npm
postinstall hook. This is not ideal because it solves the problem only
for our repo, but it's a good start.
Build perf improvements per target:
//packages/core/src/reflect:reflect 5sec => 3 sec
//packages/core:core 17sec => 12 sec
//packages/router:router 30sec => 8 sec
PR Close#33786
Prior to this change, setting style prop value to undefined or empty string would not result in resetting prop value in case the style prop is defined using [style.prop.px] syntax. The problem is that the check for empty value (and thus reseting the value) considered successful only in case of `null` value. This commit updates the check to use `isStylingValueDefined` function that also checks for undefined and empty string.
PR Close#33780
The reflection hosts have been updated to support the following
code forms, which were found in some minified library code:
* The class IIFE not being wrapped in parentheses.
* Calls to `__decorate()` being combined with the IIFE return statement.
PR Close#33777
Previously we only removed `__decorate()` calls that looked like:
```
SomeClass = __decorate(...);
```
But in some minified scenarios this call gets wrapped up with the
return statement of the IIFE.
```
return SomeClass = __decorate(...);
```
This is now removed also, leaving just the return statement:
```
return SomeClass;
```
PR Close#33777
The `dist/` directory has a duplicate `package.json` pointing to the
same files, which (under certain configurations) can causes ngcc to try
to process the files twice and fail.
This commit adds a default ngcc config for `ng2-dragula` to ignore the
`dist/` entry-point.
Fixes#33718
PR Close#33797
Prior to this change, ComponentFactory.create function invocation in Ivy retained the content of the host element (in case host element reference or CSS seelctor is provided as an argument). This behavior is different in View Engine, where the content of the host element was cleared, except for the case when ShadowDom encapsulation is used (to make sure native slot projection works). This commit aligns Ivy and View Engine and makes sure the host element is cleared before component content insertion.
PR Close#33487
During incremental compilations, ngtsc needs to know which metadata
from a previous compilation can be reused, versus which metadata has to
be recomputed as some dependency was updated. Changes to
directives/components should cause the NgModule in which they are
declared to be recompiled, as the NgModule's compilation is dependent
on its directives/components.
When a dependent source file of a directive/component is updated,
however, a more subtle dependency should also cause to NgModule's source
file to be invalidated. During the reconciliation of state from a
previous compilation into the new program, the component's source file
is invalidated because one of its dependency has changed, ergo the
NgModule needs to be invalidated as well. Up until now, this implicit
dependency was not imposed on the NgModule. Additionally, any change to
a dependent file may influence the module scope to change, so all
components within the module must be invalidated as well.
This commit fixes the bug by introducing additional file dependencies,
as to ensure a proper rebuild of the module scope and its components.
Fixes#32416
PR Close#33522
When the Angular compiler is operated through the ngc binary in watch
mode, changing a template in an external file would not cause the
component to be recompiled if Ivy is enabled.
There was a problem with how a cached compiler host was present that was
unaware of the changed resources, therefore failing to trigger a
recompilation of a component whenever its template changes. This commit
fixes the issue by ensuring that information about modified resources is
correctly available to the cached compiler host.
Fixes#32869
PR Close#33551
The `ngInjectableDef` property was renamed to `ɵprov`, but core must
still support both because there are published libraries that use the
older term.
We are only interested in such properties that are defined directly on
the type being injected, not on base classes. So there is a check that
the defintion is specifically for the given type.
Previously if you tried to inject a class that had `ngInjectableDef` but
also inherited `ɵprov` then the check would fail on the `ɵprov` property
and never even try the `ngInjectableDef` property resulting in a failed
injection.
This commit fixes this by attempting to find each of the properties
independently.
Fixes https://github.com/angular/ngcc-validation/pull/526
PR Close#33732
Since #33321, Angular packages have been persisted on each build as
CircleCI build artifacts (`.tgz` files), which can be used to install
dependencies on a project (for the purpose of testing or trying out a
change before a PR being merged and without having to build the packages
from source locally).
Previously, only packages published to npm under the `@angular` scope
were persisted as build artifacts.
This commit adds the `zone.js` package to the list of persisted
packages.
Fixes#33686
PR Close#33733
In #33046, internal uses of `zone.js` were switched to reference it
directly from source (built with Bazel) instead of npm. As a result, the
necessary scripts were updated to build `zone.js` as necessary. However,
some `integration/**/debug-test.sh` scripts were missed (apparently
because they are not used on CI, but only locally as helpers for
debugging the integration projects).
This commit updates the `scripts/build-packages-dist.sh` script to also
build `zone.js`, so that other scripts (such as the various
`debug-test.sh` scripts) can use it.
PR Close#33733
switching to cldr-data package resulted in
loss of some locales, since by default only core locales are loaded.
This PR adds a flag to tell cldr-data to use full locale coverage
fixes: #33681
PR Close#33682
Most of the use of `document` in the framework is within
the DI so they just inject the `DOCUMENT` token and are done.
Ivy is special because it does not rely upon the DI and must
get hold of the document some other way. There are a limited
number of places relevant to ivy that currently consume a global
document object.
The solution is modelled on the `LOCALE_ID` approach, which has
`getLocaleId()` and `setLocaleId()` top-level functions for ivy (see
`core/src/render3/i18n.ts`). In the rest of Angular (i.e. using DI) the
`LOCALE_ID` token has a provider that also calls setLocaleId() to
ensure that ivy has the same value.
This commit defines `getDocument()` and `setDocument() `top-level
functions for ivy. Wherever ivy needs the global `document`, it calls
`getDocument()` instead. Each of the platforms (e.g. Browser, Server,
WebWorker) have providers for `DOCUMENT`. In each of those providers
they also call `setDocument()` accordingly.
Fixes#33651
PR Close#33712
It looks like there was a typo when it originally was
written. As it works right now, the `beforeEach` and
`afterEach` cancel each other out. But then
`ensureDocument()` is called anyway in the `withBody()`
function.
With this change there is no need to call `ensureDocument() in the
`withBody() function.
PR Close#33712
Previously the renderers were fixed so that they inserted extra
"adjacent" statements after the last static property of classes.
In order to help the build-optimizer (in Angular CLI) to be able to
tree-shake classes effectively, these statements should also appear
after any helper calls, such as `__decorate()`.
This commit moves the computation of this positioning into the
`NgccReflectionHost` via the `getEndOfClass()` method, which
returns the last statement that is related to the class.
FW-1668
PR Close#33689
While overriding providers in Ivy TestBed (via TestBed.overrideProvider call), the old providers were retained in the list, since the override takes precedence. However, presence of providers in the list might have side-effect: if a provider has the `ngOnDestroy` lifecycle hook, this hook will be registered and invoked later (when component is destroyed). This commit updates TestBed logic to clear provider list by removing the ones which have overrides.
PR Close#33706
Updates the commit we run the `material-unit-tests` job
against. The latest commit includes 1255139a38
This commit reduces the flakiness of a `MatMenu` test and therefore
improves the stability of the material-unit-tests job.
Example failing build: https://circleci.com/gh/angular/angular/521625
PR Close#33716
This commit removes one of the expected Ivy changes because we have
decided to change the behavior to be more backwards-compatible.
It also adds a bug fix that is technically breaking to the list of
expected changes.
PR Close#33675
Similar to https://github.com/angular/angular/pull/33633, this commit is
needed to fix an outage with the Angular Kythe indexer.
Crash logs:
```
TypeError: Cannot read property 'text' of undefined
at NodeObject.getFullText (typescript/stable/lib/typescript.js:121443:57)
at FactoryGenerator.generate (angular2/rc/packages/compiler-cli/src/ngtsc/shims/src/factory_generator.ts:67:34)
at GeneratedShimsHostWrapper.getSourceFile (angular2/rc/packages/compiler-cli/src/ngtsc/shims/src/host.ts:88:26)
at findSourceFile (typescript/stable/lib/typescript.js:90654:29)
at typescript/stable/lib/typescript.js:90553:85
at getSourceFileFromReferenceWorker (typescript/stable/lib/typescript.js:90520:34)
at processSourceFile (typescript/stable/lib/typescript.js:90553:13)
at processRootFile (typescript/stable/lib/typescript.js:90383:13)
at typescript/stable/lib/typescript.js:89399:60
at Object.forEach (typescript/stable/lib/typescript.js:280:30)
```
PR Close#33660
Prior to this patch all the styling benchmarks only tested for
template map-based style/class bindings. Because of each of the bindings
being only present in the template, there was no possibility of
there being any duplicate map-based styling bindings.
This benchmark introduces benchmarking for map-based style/class bindings
that are evaluated from both template bindings as well as directives.
This benchmark can be executed by calling:
```
bazel build //packages/core/test/render3/perf:duplicate_map_based_style_and_class_bindings_lib.min_debug.es2015.js
node dist/bin/packages/core/test/render3/perf/duplicate_map_based_style_and_class_bindings_lib.min_debug.es2015.js
```
The benchmark is also run via the `profile_all.js` script (found in
`packages/core/test/render3/perf/`)
PR Close#33608
When ngcc is configured to generate reexports for a package using the
`generateDeepReexports` configuration option, it could incorrectly
render the reexports as often as the number of compiled classes in the
declaration file. This would cause compilation errors due to duplicated
declarations.
PR Close#33658
When the Angular compiler is operated through the ngc binary in watch
mode, changing a template in an external file would not cause the
component to be recompiled if Ivy is enabled.
There was a problem with how a cached compiler host was present that was
unaware of the changed resources, therefore failing to trigger a
recompilation of a component whenever its template changes. This commit
fixes the issue by ensuring that information about modified resources is
correctly available to the cached compiler host.
Fixes#32869
PR Close#33551
Prior to this patch all the styling benchmarks only tested for
template-based style/class bindings. Because of each of the bindings
being only present in the template, there was no possibility of
there being any duplicate bindings. This benchmark introduces
style/class bindings being evaluated from both a template and from
various directives.
This benchmark can be executed by calling:
```
bazel build //packages/core/test/render3/perf:duplicate_style_and_class_bindings_lib.min_debug.es2015.js
node dist/bin/packages/core/test/render3/perf/duplicate_style_and_class_bindings_lib.min_debug.es2015.js
```
The benchmark is also run via the `profile_all.js` script (found in
`packages/core/test/render3/perf/`)
PR Close#33600
Prior to this change, namespaced elements such as SVG elements would not
participate correctly in directive matching as their namespace was not
ignored, which was the case with the View Engine compiler. This led to
incorrect behavior at runtime and template type checking.
This commit resolved the issue by ignoring the namespace of elements and
attributes like they were in View Engine.
Fixes#32061
PR Close#33555
This issue was found when debugging a test failure that was using lazy
loaded modules with the router. When doing this, the router calls
`NgModuleFactory.create` for the loaded module. This module gets a new
injector so the overrides provided in TestBed are not applied unless the
Injectable is in the providers list (which is not the case for
{providedIn...} Injectables).
PR Close#33606
When debugging `LView`s it is easy to get lost since all of them have
the same name. This change does three things:
1. It makes `TView` have an explicit type:
- `Host`: for the top level `TView` for bootstrap
- `Component`: for the `TView` which represents components template
- `Embedded`: for the `TView` which represents an embedded template
2. It changes the name of `LView` to `LHostView`, `LComponentView`, and
`LEmbeddedView` depending on the `TView` type.
3. For `LComponentView` and `LEmbeddedView` we also append the name of
of the `context` constructor. The result is that we have `LView`s which
are name as: `LComponentView_MyComponent` and `LEmbeddedView_NgIfContext`.
The above changes will make it easier to understand the structure of the
application when debugging.
NOTE: All of these are behind `ngDevMode` and will get removed in
production application.
PR Close#33449
Prior to this commit, i18n runtime logic used `elementAttributeInternal` function (that uses `setAttribute` function under the hood) for all elements where i18n attributes are present. However the `<ng-container>` elements in a template may also have i18n attributes and calling `setAttribute` fails, since they are represented as comment nodes in DOM. This commit ensures that we call `setAttribute` on nodes with TNodeType.Element type (that support that operation) only.
PR Close#33599
This adds a common configurations used when developing code in VSCode.
Specifically it adds support for launching these targets as tasks and
ind debugger.
- `packages/core/test`
- `packages/core/test/render3`
- `packages/core/test/acceptance`
PR Close#33544
Previously the compiler would ignore everything in the attribute
name after the first dot. For example
<div [attr.someAttr.attrSuffix]="var"></div>
is turned into <div someAttr="varValue"></div>.
This commit ensures that whole attribute name is captured.
Now <div [attr.someAttr.attrSuffix]="var"></div>
is turned into <div someAttr.attrSuffix="varValue"></div>
PR Close#32256
2019-11-07 01:02:57 +00:00
1722 changed files with 29929 additions and 17632 deletions
# VSCode Remote Development - Developing inside a Containers
This folder contains configuration files that can be used to opt into working on this repository in a [Docker container](https://www.docker.com/resources/what-container) via [VSCode](https://code.visualstudio.com/)'s Remote Development feature (see below).
Info on remote development and developing inside a container with VSCode:
- [VSCode: Developing inside a Container](https://code.visualstudio.com/docs/remote/containers)
- [VSCode: Remote Development FAQ](https://code.visualstudio.com/docs/remote/faq)
## Usage
_Prerequisite: [Install Docker](https://docs.docker.com/install) on your local environment._
To get started, read and follow the instuctions in [Developing inside a Container](https://code.visualstudio.com/docs/remote/containers). The [.devcontainer/](.) directory contains pre-configured `devcontainer.json` and `Dockerfile` files, which you can use to set up remote development with a docker container.
In a nutshell, you need to:
- Install the [Remote - Containers](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers) extension.
- Copy [recommended-Dockerfile](./recommended-Dockerfile) to `Dockerfile` (and optionally tweak to suit your needs).
- Copy [recommended-devcontainer.json](./recommended-devcontainer.json) to `devcontainer.json` (and optionally tweak to suit your needs).
- Open VSCode and bring up the [Command Palette](https://code.visualstudio.com/docs/getstarted/userinterface#_command-palette).
- Type `Remote-Containers: Open Folder in Container` and choose your local clone of [angular/angular](https://github.com/angular/angular).
The `.devcontainer/devcontainer.json` and `.devcontainer/Dockerfile` files are ignored by git, so you can have your own local versions. We may occasionally update the template files ([recommended-devcontainer.json](./recommended-devcontainer.json), [recommended-Dockerfile](./recommended-Dockerfile)), in which case you will need to manually update your local copies (if desired).
## Updating `recommended-devcontainer.json` and `recommended-Dockerfile`
You can update and commit the recommended config files (which people use as basis for their local configs), if you find that something is broken, out-of-date or can be improved.
Please, keep in mind that any changes you make will potentially be used by many people on different environments. Try to keep these config files cross-platform compatible and free of personal preferences.
This folder contains opt-in [Workspace Settings](https://code.visualstudio.com/docs/getstarted/settings) and [Extension Recommendations](https://code.visualstudio.com/docs/editor/extension-gallery#_workspace-recommended-extensions) that the Angular team recommends using when working on this repository.
This folder contains opt-in [Workspace Settings](https://code.visualstudio.com/docs/getstarted/settings), [Tasks](https://code.visualstudio.com/docs/editor/tasks), [Launch Configurations](https://code.visualstudio.com/Docs/editor/debugging#_launch-configurations) and [Extension Recommendations](https://code.visualstudio.com/docs/editor/extension-gallery#_workspace-recommended-extensions) that the Angular team recommends using when working on this repository.
## Usage
To use the recommended settings follow the steps below:
To use the recommended configurations follow the steps below:
- copy `.vscode/recommended-settings.json` to `.vscode/settings.json`
- install the recommneded extensions in `.vscode/extensions.json`
- copy (or link)`.vscode/recommended-settings.json` to `.vscode/settings.json`
- copy (or link) `.vscode/recommended-launch.json` to `.vscode/launch.json`
- copy (or link) `.vscode/recommended-tasks.json` to `.vscode/tasks.json`
- restart the editor
If you already have your custom workspace settings you should instead manually merge the file content.
If you already have your custom workspace settings you should instead manually merge the file contents.
This isn't an automatic process so you will need to repeat it when settings are updated.
To see the recommended extensions select "Extensions: Show Recommended Extensions" in the [Command Palette](https://code.visualstudio.com/docs/getstarted/userinterface#_command-palette).
## Editing `.vscode/recommended-settings.json`
## Editing `.vscode/recommended-*.json` files
If you wish to add extra configuration items please keep in mind any settings you add here will be used by many users.
If you wish to add extra configuration items please keep in mind any modifications you make here will be used by many users.
Try to keep these settings to things that help facilitate the development process and avoid altering the user workflow whenever possible.
Try to keep these settings/configuations to things that help facilitate the development process and avoid altering the user workflow whenever possible.
* **bazel:** ng_module should not emit shim files under bazel and Ivy ([#33765](https://github.com/angular/angular/issues/33765)) ([e24ed8d](https://github.com/angular/angular/commit/e24ed8d))
* **bazel:** update to tsickle 0.37.1 to fix peerDep warnings ([#33788](https://github.com/angular/angular/issues/33788)) ([719ca1d](https://github.com/angular/angular/commit/719ca1d))
* **core:** allow css custom variables/properties in the style sanitizer ([#33841](https://github.com/angular/angular/issues/33841)) ([61cc7a3](https://github.com/angular/angular/commit/61cc7a3)), closes [#23485](https://github.com/angular/angular/issues/23485) [#23485](https://github.com/angular/angular/issues/23485)
* **core:** remove deprecated and defunct wtf* apis ([#33949](https://github.com/angular/angular/issues/33949)) ([cf42019](https://github.com/angular/angular/commit/cf42019))
* **ivy:** avoid using stale cache in TestBed if module overrides are defined ([#33787](https://github.com/angular/angular/issues/33787)) ([fbd2133](https://github.com/angular/angular/commit/fbd2133))
* **ivy:** handle non-standard input/output names in template type checking ([#33741](https://github.com/angular/angular/issues/33741)) ([94257ac](https://github.com/angular/angular/commit/94257ac)), closes [#33590](https://github.com/angular/angular/issues/33590)
* **ivy:** i18n - ensure that escaped chars are handled in localized strings ([#34065](https://github.com/angular/angular/issues/34065)) ([00f8d6a](https://github.com/angular/angular/commit/00f8d6a))
* **ivy:** prevent unknown element check for AOT-compiled components ([#34024](https://github.com/angular/angular/issues/34024)) ([955a312](https://github.com/angular/angular/commit/955a312))
* **ivy:** remove TNodeType assertion from `directiveInject` instruction ([#33948](https://github.com/angular/angular/issues/33948)) ([90a9043](https://github.com/angular/angular/commit/90a9043))
* **ivy:** reset style property using ngStyle fix ([#33920](https://github.com/angular/angular/issues/33920)) ([b8ba6b0](https://github.com/angular/angular/commit/b8ba6b0))
* **ivy:** run pre-order hooks in injection order ([#34026](https://github.com/angular/angular/issues/34026)) ([ebe3229](https://github.com/angular/angular/commit/ebe3229)), closes [#32522](https://github.com/angular/angular/issues/32522)
* **ivy:** support ICUs without "other" cases ([#34042](https://github.com/angular/angular/issues/34042)) ([781003f](https://github.com/angular/angular/commit/781003f))
* **ivy:** support inserting a `viewRef` that is already present ([#34052](https://github.com/angular/angular/issues/34052)) ([978b500](https://github.com/angular/angular/commit/978b500)), closes [#33924](https://github.com/angular/angular/issues/33924)
* **ivy:** take styles extracted from template into account in JIT mode ([#34017](https://github.com/angular/angular/issues/34017)) ([b659aa3](https://github.com/angular/angular/commit/b659aa3))
* **ivy:** wrap functions from "providers" in parentheses in Closure mode ([#33609](https://github.com/angular/angular/issues/33609)) ([fc6ad19](https://github.com/angular/angular/commit/fc6ad19)), closes [/github.com/angular/tsickle/blob/d7974262571c8a17d684e5ba07680e1b1993afdd/src/jsdoc_transformer.ts#L1021](https://github.com//github.com/angular/tsickle/blob/d7974262571c8a17d684e5ba07680e1b1993afdd/src/jsdoc_transformer.ts/issues/L1021)
* **language-service:** determine index types accessed using dot notation ([#33884](https://github.com/angular/angular/issues/33884)) ([e8ec296](https://github.com/angular/angular/commit/e8ec296)), closes [#29811](https://github.com/angular/angular/issues/29811) [#29811](https://github.com/angular/angular/issues/29811)
* **language-service:** fix error of array-index out of bounds exception ([#33928](https://github.com/angular/angular/issues/33928)) ([b05ce85](https://github.com/angular/angular/commit/b05ce85))
* **language-service:** function.bind() should not be an error ([#34041](https://github.com/angular/angular/issues/34041)) ([#34046](https://github.com/angular/angular/issues/34046)) ([d22f3d6](https://github.com/angular/angular/commit/d22f3d6))
* **ngcc:** do not crash on packages that specify typings as an array ([#33973](https://github.com/angular/angular/issues/33973)) ([e456e58](https://github.com/angular/angular/commit/e456e58)), closes [#33646](https://github.com/angular/angular/issues/33646)
* **ngcc:** do not output duplicate ɵprov properties ([#34085](https://github.com/angular/angular/issues/34085)) ([5a8d25d](https://github.com/angular/angular/commit/5a8d25d))
* **ngcc:** render localized strings when in ES5 format ([#33857](https://github.com/angular/angular/issues/33857)) ([c6695fa](https://github.com/angular/angular/commit/c6695fa))
* **ngcc:** render UMD global imports correctly ([#34012](https://github.com/angular/angular/issues/34012)) ([83989b8](https://github.com/angular/angular/commit/83989b8))
* **ngcc:** report errors from `analyze` and `resolve` processing ([#33964](https://github.com/angular/angular/issues/33964)) ([ca5d772](https://github.com/angular/angular/commit/ca5d772)), closes [/github.com/angular/angular/issues/33685#issuecomment-557091719](https://github.com//github.com/angular/angular/issues/33685/issues/issuecomment-557091719)
* **router:** make routerLinkActive work with query params which contain arrays ([#22666](https://github.com/angular/angular/issues/22666)) ([f1bf5b2](https://github.com/angular/angular/commit/f1bf5b2)), closes [#22223](https://github.com/angular/angular/issues/22223)
* **service-worker:** allow creating post api requests after cache failure ([#33930](https://github.com/angular/angular/issues/33930)) ([63c9123](https://github.com/angular/angular/commit/63c9123)), closes [#33793](https://github.com/angular/angular/issues/33793)
* **service-worker:** throw when using the unsupported `versionedFiles` option in config ([#33903](https://github.com/angular/angular/issues/33903)) ([250e6fd](https://github.com/angular/angular/commit/250e6fd))
### Features
* **language-service:** completions support for indexed types ([#34047](https://github.com/angular/angular/issues/34047)) ([8a565c8](https://github.com/angular/angular/commit/8a565c8)), closes [angular/vscode-ng-language-service#110](https://github.com/angular/vscode-ng-language-service/issues/110) [angular/vscode-ng-language-service#277](https://github.com/angular/vscode-ng-language-service/issues/277)
* **language-service:** completions support for tuple array ([#33928](https://github.com/angular/angular/issues/33928)) ([7faa9bb](https://github.com/angular/angular/commit/7faa9bb))
### Performance Improvements
* **ivy:** do no work if moving a `viewRef` to the same position ([#34052](https://github.com/angular/angular/issues/34052)) ([d228801](https://github.com/angular/angular/commit/d228801))
* **ivy:** fix creation time micro-benchmarks ([#34031](https://github.com/angular/angular/issues/34031)) ([457ac3a](https://github.com/angular/angular/commit/457ac3a))
* **ivy:** R3TestBed - Do not process NgModuleDefs that have already been processed ([#33863](https://github.com/angular/angular/issues/33863)) ([05a18cc](https://github.com/angular/angular/commit/05a18cc))
* **core:** make QueryList implement Iterable in the type system ([#33536](https://github.com/angular/angular/issues/33536)) ([49571bf](https://github.com/angular/angular/commit/49571bf)), closes [#29842](https://github.com/angular/angular/issues/29842)
* **ivy:** always re-analyze the program during incremental rebuilds ([#33862](https://github.com/angular/angular/issues/33862)) ([30ddadc](https://github.com/angular/angular/commit/30ddadc)), closes [#32388](https://github.com/angular/angular/issues/32388)
* **ivy:** avoid cyclical dependency in imports ([#33831](https://github.com/angular/angular/issues/33831)) ([a61fb76](https://github.com/angular/angular/commit/a61fb76))
* **ivy:** constant object literals shared across element and component instances ([#33705](https://github.com/angular/angular/issues/33705)) ([93ba4c2](https://github.com/angular/angular/commit/93ba4c2))
* **ivy:** don't infer template context types when in full mode ([#33537](https://github.com/angular/angular/issues/33537)) ([595375f](https://github.com/angular/angular/commit/595375f)), closes [#33527](https://github.com/angular/angular/issues/33527)
* **ivy:** emit fs-relative paths when rootDir(s) aren't in effect ([#33828](https://github.com/angular/angular/issues/33828)) ([14156bd](https://github.com/angular/angular/commit/14156bd)), closes [#33659](https://github.com/angular/angular/issues/33659) [#33562](https://github.com/angular/angular/issues/33562)
* **ivy:** ExpressionChangedAfterItHasBeenCheckedError for SafeValue ([#33749](https://github.com/angular/angular/issues/33749)) ([cba6b7d](https://github.com/angular/angular/commit/cba6b7d)), closes [#33448](https://github.com/angular/angular/issues/33448)
* **ivy:** extend assertion in `directiveInject` function to support IcuContainers ([#33832](https://github.com/angular/angular/issues/33832)) ([8452458](https://github.com/angular/angular/commit/8452458))
* **ivy:** i18n - ensure that colons in i18n metadata are not rendered ([#33820](https://github.com/angular/angular/issues/33820)) ([bc28ca7](https://github.com/angular/angular/commit/bc28ca7))
* **ivy:** i18n - support "\", "`" and "${" sequences in i18n messages ([#33820](https://github.com/angular/angular/issues/33820)) ([b53a1ac](https://github.com/angular/angular/commit/b53a1ac))
* **ivy:** move setClassMetadata calls into a pure iife ([#33337](https://github.com/angular/angular/issues/33337)) ([213e3c3](https://github.com/angular/angular/commit/213e3c3))
* **ivy:** properly insert views before ng-container with injected ViewContainerRef ([#33853](https://github.com/angular/angular/issues/33853)) ([c7a3694](https://github.com/angular/angular/commit/c7a3694))
* **ivy:** properly insert views into ViewContainerRef injected by querying <ng-container> ([#33816](https://github.com/angular/angular/issues/33816)) ([f136dda](https://github.com/angular/angular/commit/f136dda))
* **ivy:** reset style property value defined using [style.prop.px] ([#33780](https://github.com/angular/angular/issues/33780)) ([de8cf75](https://github.com/angular/angular/commit/de8cf75))
* **ivy:** shadow all DOM properties in `DebugElement.properties` ([#33781](https://github.com/angular/angular/issues/33781)) ([5be23a3](https://github.com/angular/angular/commit/5be23a3)), closes [#33695](https://github.com/angular/angular/issues/33695)
* **ivy:** support for #id bootstrap selectors ([#33784](https://github.com/angular/angular/issues/33784)) ([9761ebe](https://github.com/angular/angular/commit/9761ebe)), closes [#33485](https://github.com/angular/angular/issues/33485)
* **language-service:** Function alias should be callable ([#33782](https://github.com/angular/angular/issues/33782)) ([ca63353](https://github.com/angular/angular/commit/ca63353))
* **language-service:** Provide completions for attribute values ([#33839](https://github.com/angular/angular/issues/33839)) ([0e20453](https://github.com/angular/angular/commit/0e20453))
* **language-service:** Recompute analyzed modules only when source files change ([#33806](https://github.com/angular/angular/issues/33806)) ([9882a82](https://github.com/angular/angular/commit/9882a82))
* **language-service:** Remove getTemplateReferences() from LanguageService API ([#33807](https://github.com/angular/angular/issues/33807)) ([0688a28](https://github.com/angular/angular/commit/0688a28))
* **ngcc:** correctly associate decorators with aliased classes ([#33878](https://github.com/angular/angular/issues/33878)) ([59a4b76](https://github.com/angular/angular/commit/59a4b76))
* **ngcc:** correctly include internal .d.ts files ([#33875](https://github.com/angular/angular/issues/33875)) ([0854dc8](https://github.com/angular/angular/commit/0854dc8))
* **ngcc:** do not emit ES2015 code in ES5 files ([#33514](https://github.com/angular/angular/issues/33514)) ([06e36e5](https://github.com/angular/angular/commit/06e36e5)), closes [#32665](https://github.com/angular/angular/issues/32665)
* **ngcc:** generate correct metadata for classes with getter/setter properties ([#33514](https://github.com/angular/angular/issues/33514)) ([21bd8c9](https://github.com/angular/angular/commit/21bd8c9)), closes [#30569](https://github.com/angular/angular/issues/30569)
* **router:** make routerLinkActive work with query params which contain arrays ([#22666](https://github.com/angular/angular/issues/22666)) ([8e5ed20](https://github.com/angular/angular/commit/8e5ed20)), closes [#22223](https://github.com/angular/angular/issues/22223)
* **bazel:** update ng-add to use bazel v1.1.0 ([#33813](https://github.com/angular/angular/issues/33813)) ([b1d0a4f](https://github.com/angular/angular/commit/b1d0a4f))
* **ivy:** don't store public input names in two places ([#33798](https://github.com/angular/angular/issues/33798)) ([105616c](https://github.com/angular/angular/commit/105616c))
* **common:** rerun cldr to remove <20> characters ([#33699](https://github.com/angular/angular/issues/33699)) ([011ecdf](https://github.com/angular/angular/commit/011ecdf))
* **common:** update CLDR generated files after change to npm sources ([#33634](https://github.com/angular/angular/issues/33634)) ([59b25da](https://github.com/angular/angular/commit/59b25da))
* **common:** update CLDR generated files to 36.0.0 ([#33584](https://github.com/angular/angular/issues/33584)) ([c1bd3bc](https://github.com/angular/angular/commit/c1bd3bc))
* **compiler:** correctly parse attributes with a dot in the name ([#32256](https://github.com/angular/angular/issues/32256)) ([687582f](https://github.com/angular/angular/commit/687582f))
* **core:** support `ngInjectableDef` on types with inherited `ɵprov` ([#33732](https://github.com/angular/angular/issues/33732)) ([4ec079f](https://github.com/angular/angular/commit/4ec079f))
* **ivy:** auto register NgModules with ID ([#33663](https://github.com/angular/angular/issues/33663)) ([4988094](https://github.com/angular/angular/commit/4988094))
* **ivy:** better support for i18n attributes on <ng-container>s ([#33599](https://github.com/angular/angular/issues/33599)) ([2046202](https://github.com/angular/angular/commit/2046202))
* **ivy:** ComponentFactory.create should clear host element content ([#33487](https://github.com/angular/angular/issues/33487)) ([d67a38b](https://github.com/angular/angular/commit/d67a38b))
* **ivy:** ensure module scope is rebuilt on dependent change ([#33522](https://github.com/angular/angular/issues/33522)) ([71238a9](https://github.com/angular/angular/commit/71238a9)), closes [#32416](https://github.com/angular/angular/issues/32416)
* **ivy:** ensure that the correct `document` is available ([#33712](https://github.com/angular/angular/issues/33712)) ([8362696](https://github.com/angular/angular/commit/8362696)), closes [#33651](https://github.com/angular/angular/issues/33651)
* **ivy:** Handle overrides for {providedIn: AModule} in R3TestBed ([#33606](https://github.com/angular/angular/issues/33606)) ([d09ad82](https://github.com/angular/angular/commit/d09ad82))
* **ivy:** match directives on namespaced elements ([#33555](https://github.com/angular/angular/issues/33555)) ([99ead47](https://github.com/angular/angular/commit/99ead47)), closes [#32061](https://github.com/angular/angular/issues/32061)
* **ivy:** properly determine the first native node of a view ([#33627](https://github.com/angular/angular/issues/33627)) ([811275c](https://github.com/angular/angular/commit/811275c))
* **ivy:** properly insert views in front of empty views ([#33647](https://github.com/angular/angular/issues/33647)) ([c5737f4](https://github.com/angular/angular/commit/c5737f4))
* **ivy:** properly insert views in front of views with an empty element container ([#33647](https://github.com/angular/angular/issues/33647)) ([0b99884](https://github.com/angular/angular/commit/0b99884))
* **ivy:** provider override via TestBed should remove old providers from the list ([#33706](https://github.com/angular/angular/issues/33706)) ([f45d5dc](https://github.com/angular/angular/commit/f45d5dc))
* **ivy:** recompile component when template changes in ngc watch mode ([#33551](https://github.com/angular/angular/issues/33551)) ([da01dbc](https://github.com/angular/angular/commit/da01dbc)), closes [#32869](https://github.com/angular/angular/issues/32869)
* **ivy:** recompile component when template changes in ngc watch mode ([#33551](https://github.com/angular/angular/issues/33551)) ([cd8333c](https://github.com/angular/angular/commit/cd8333c)), closes [#32869](https://github.com/angular/angular/issues/32869)
* **ivy:** Run ChangeDetection on transplanted views ([#33644](https://github.com/angular/angular/issues/33644)) ([37ae45e](https://github.com/angular/angular/commit/37ae45e)), closes [#33393](https://github.com/angular/angular/issues/33393)
* **language-service:** Resolve template variable in nested ngFor ([#33676](https://github.com/angular/angular/issues/33676)) ([6615743](https://github.com/angular/angular/commit/6615743))
* **ngcc:** add reexports only once ([#33658](https://github.com/angular/angular/issues/33658)) ([83b635c](https://github.com/angular/angular/commit/83b635c))
* **ngcc:** ensure that adjacent statements go after helper calls ([#33689](https://github.com/angular/angular/issues/33689)) ([c540061](https://github.com/angular/angular/commit/c540061))
* generate the new locale files ([#33682](https://github.com/angular/angular/issues/33682)) ([72796b9](https://github.com/angular/angular/commit/72796b9))
* resolve event listeners not correct when registered outside of ngZone ([#33711](https://github.com/angular/angular/issues/33711)) ([9045e3e](https://github.com/angular/angular/commit/9045e3e)), closes [#33687](https://github.com/angular/angular/issues/33687)
* use full cldr data to support all locales ([#33682](https://github.com/angular/angular/issues/33682)) ([ea83125](https://github.com/angular/angular/commit/ea83125)), closes [#33681](https://github.com/angular/angular/issues/33681)
* **ngcc:** remove `__decorator` calls even when part of the IIFE return statement ([#33777](https://github.com/angular/angular/issues/33777)) ([e1df98b](https://github.com/angular/angular/commit/e1df98b))
* **ngcc:** support minified ES5 scenarios ([#33777](https://github.com/angular/angular/issues/33777)) ([49e517d](https://github.com/angular/angular/commit/49e517d))
* "fix(ivy): recompile component when template changes in ngc watch mode ([#33551](https://github.com/angular/angular/issues/33551))" ([#33661](https://github.com/angular/angular/issues/33661)) ([cb55f60](https://github.com/angular/angular/commit/cb55f60))
* fix(ivy): Only restore registered modules if user compiles modules with TestBed ([#32944](https://github.com/angular/angular/issues/32944)) ([#33663](https://github.com/angular/angular/issues/33663)) ([f8e9c1e](https://github.com/angular/angular/commit/f8e9c1e))
* fix(ivy): R3TestBed should clean up registered modules after each test ([#32872](https://github.com/angular/angular/issues/32872)) ([#33663](https://github.com/angular/angular/issues/33663)) ([7c4366d](https://github.com/angular/angular/commit/7c4366d))
### BREAKING CHANGES
* **i18n:** The CLDR data has been updated to v36.0.0, which may cause some localized data strings to change. For example, the space separator used in numbers in the `fr` locales changed from `\xa0` to `\u202f` ([c1bd3bc](https://github.com/angular/angular/commit/c1bd3bc))
@ -52,7 +52,7 @@ The following options are available for configuring the AoT template compiler.
### `allowEmptyCodegenFiles`
When true, generate all possible files even if they are empty. Default is false. Used by the Bazel build rules to simplify how Bazel rules track file dependencies. Do not use this option outside of the Bazel rules.
When `true`, generate all possible files even if they are empty. Default is `false`. Used by the Bazel build rules to simplify how Bazel rules track file dependencies. Do not use this option outside of the Bazel rules.
### `annotationsAs`
@ -64,40 +64,48 @@ Modifies how Angular-specific annotations are emitted to improve tree-shaking. N
### `annotateForClosureCompiler`
When true, use [Tsickle](https://github.com/angular/tsickle) to annotate the emitted JavaScript with [JSDoc](http://usejsdoc.org/) comments needed by the
[Closure Compiler](https://github.com/google/closure-compiler). Default is false.
When `true`, use [Tsickle](https://github.com/angular/tsickle) to annotate the emitted JavaScript with [JSDoc](http://usejsdoc.org/) comments needed by the
[Closure Compiler](https://github.com/google/closure-compiler). Default is `false`.
### `disableExpressionLowering`
When true (the default), transforms code that is or could be used in an annotation, to allow it to be imported from template factory modules. See [metadata rewriting](guide/aot-compiler#metadata-rewriting) for more information.
When `true` (the default), transforms code that is or could be used in an annotation, to allow it to be imported from template factory modules. See [metadata rewriting](guide/aot-compiler#metadata-rewriting) for more information.
When `false`, disables this rewriting, requiring the rewriting to be done manually.
### `disableTypeScriptVersionCheck`
When `true`, the compiler does not check the TypeScript version and does not report an error when an unsupported version of TypeScript is used. Not recommended, as unsupported versions of TypeScript might have undefined behavior. Default is false.
When `true`, the compiler does not check the TypeScript version and does not report an error when an unsupported version of TypeScript is used. Not recommended, as unsupported versions of TypeScript might have undefined behavior. Default is `false`.
### `enableIvy`
Enables the [Ivy](guide/ivy) compilation and rendering pipeline. Default is `true`, as of version 9. In version 9, you can [opt out of Ivy](guide/ivy#opting-out-of-angular-ivy) to continue using the previous compiler, View Engine.
For library projects generated with the CLI, the `prod` configuration default is `false` in version 9.
### `enableResourceInlining`
When true, replaces the `templateUrl` and `styleUrls` property in all `@Component` decorators with inlined contents in `template` and `styles` properties.
When `true`, replaces the `templateUrl` and `styleUrls` property in all `@Component` decorators with inlined contents in `template` and `styles` properties.
When enabled, the `.js` output of `ngc` does not include any lazy-loaded template or style URLs.
For library projects generated with the CLI, the dev configuration default is `true`.
{@a enablelegacytemplate}
### `enableLegacyTemplate`
When true, enables use of the `<template>` element, which was deprecated in Angular 4.0, in favor of `<ng-template>` (to avoid colliding with the DOM's element of the same name). Default is false. Might be required by some third-party Angular libraries.
When `true`, enables use of the `<template>` element, which was deprecated in Angular 4.0, in favor of `<ng-template>` (to avoid colliding with the DOM's element of the same name). Default is `false`. Might be required by some third-party Angular libraries.
### `flatModuleId`
The module ID to use for importing a flat module (when `flatModuleOutFile` is true). References generated by the template compiler use this module name when importing symbols
from the flat module. Ignored if `flatModuleOutFile` is false.
The module ID to use for importing a flat module (when `flatModuleOutFile` is `true`). References generated by the template compiler use this module name when importing symbols
from the flat module. Ignored if `flatModuleOutFile` is `false`.
### `flatModuleOutFile`
When true, generates a flat module index of the given file name and the corresponding flat module metadata. Use to create flat modules that are packaged similarly to `@angular/core` and `@angular/common`. When this option is used, the `package.json` for the library should refer
When `true`, generates a flat module index of the given file name and the corresponding flat module metadata. Use to create flat modules that are packaged similarly to `@angular/core` and `@angular/common`. When this option is used, the `package.json` for the library should refer
to the generated flat module index instead of the library index file.
Produces only one `.metadata.json` file, which contains all the metadata necessary
@ -112,31 +120,31 @@ If more than one `.ts` file is supplied without a `libraryIndex`, an error is pr
A flat module index `.d.ts` and `.js` is created with the given `flatModuleOutFile` name in the same location as the library index `.d.ts` file.
For example, if a library uses the `public_api.ts` file as the library index of the module, the `tsconfig.json``files` field would be `["public_api.ts"]`.
The `flatModuleOutFile` options could then be set to (for example) `"index.js"`, which produces `index.d.ts` and `index.metadata.json` files.
The `flatModuleOutFile` option could then be set to (for example) `"index.js"`, which produces `index.d.ts` and `index.metadata.json` files.
The `module` field of the library's `package.json` would be `"index.js"` and the `typings` field
would be `"index.d.ts"`.
### `fullTemplateTypeCheck`
When true (recommended), enables the [binding expression validation](guide/aot-compiler#binding-expression-validation) phase of the template compiler, which uses TypeScript to validate binding expressions.
When `true` (recommended), enables the [binding expression validation](guide/aot-compiler#binding-expression-validation) phase of the template compiler, which uses TypeScript to validate binding expressions. For more information, see [Template type checking](guide/template-typecheck).
Default is currently false.
Default is `false`, but when you use the CLI command `ng new`, it is set to `true` by default in the generated project's configuration.
### `generateCodeForLibraries`
When true (the default), generates factory files (`.ngfactory.js` and `.ngstyle.js`)
When `true` (the default), generates factory files (`.ngfactory.js` and `.ngstyle.js`)
for `.d.ts` files with a corresponding `.metadata.json` file.
When false, factory files are generated only for `.ts` files. Do this when using factory summaries.
When `false`, factory files are generated only for `.ts` files. Do this when using factory summaries.
### `preserveWhitespaces`
When false (the default), removes blank text nodes from compiled templates, which results in smaller emitted template factory modules. Set to true to preserve blank text nodes.
When `false` (the default), removes blank text nodes from compiled templates, which results in smaller emitted template factory modules. Set to `true` to preserve blank text nodes.
### `skipMetadataEmit`
When true, does not to produce `.metadata.json` files. Default is `false`.
When `true`, does not produce `.metadata.json` files. Default is `false`.
The `.metadata.json` files contain information needed by the template compiler from a `.ts`
file that is not included in the `.d.ts` file produced by the TypeScript compiler.
@ -150,14 +158,16 @@ are not valid for this style of TypeScript output. However, we do not recommend
### `skipTemplateCodegen`
When true, does not emit `.ngfactory.js` and `.ngstyle.js` files. This turns off most of the template compiler and disables the reporting of template diagnostics.
When `true`, does not emit `.ngfactory.js` and `.ngstyle.js` files. This turns off most of the template compiler and disables the reporting of template diagnostics.
Can be used to instruct the template compiler to produce `.metadata.json` files for distribution with an `npm` package while avoiding the production of `.ngfactory.js` and `.ngstyle.js` files that cannot be distributed to `npm`.
For library projects generated with the CLI, the dev configuration default is `true`.
### `strictMetadataEmit`
When true, reports an error to the `.metadata.json` file if `"skipMetadataEmit"` is `false`.
Default is false. Use only when `"skipMetadataEmit"` is false and `"skipTemplateCodeGen"` is true.
When `true`, reports an error to the `.metadata.json` file if `"skipMetadataEmit"` is `false`.
Default is `false`. Use only when `"skipMetadataEmit"` is `false` and `"skipTemplateCodeGen"` is `true`.
This option is intended to validate the `.metadata.json` files emitted for bundling with an `npm` package. The validation is strict and can emit errors for metadata that would never produce an error when used by the template compiler. You can choose to suppress the error emitted by this option for an exported symbol by including `@dynamic` in the comment documenting the symbol.
@ -170,10 +180,21 @@ If the client of a library intends to use a symbol in an annotation, the templat
This option allows detection of these errors during the build phase of
the library and is used, for example, in producing Angular libraries themselves.
For library projects generated with the CLI, the dev configuration default is `true`.
### `strictInjectionParameters`
When true (recommended), reports an error for a supplied parameter whose injection type cannot be determined. When false (currently the default), constructor parameters of classes marked with `@Injectable` whose type cannot be resolved produce a warning.
When `true` (recommended), reports an error for a supplied parameter whose injection type cannot be determined. When `false` (currently the default), constructor parameters of classes marked with `@Injectable` whose type cannot be resolved produce a warning.
When you use the CLI command `ng new`, it is set to `true` by default in the generated project's configuration.
### `strictTemplates`
When `true`, enables [strict template type checking](guide/template-typecheck#strict-mode) in Angular version 9. Strict mode is only available when using [Ivy](guide/ivy).
Additional strictness flags allow you to enable and disable specific types of strict template type checking. See [troubleshooting template errors](guide/template-typecheck#troubleshooting-template-errors).
### `trace`
When true, prints extra information while compiling templates. Default is false.
When `true`, prints extra information while compiling templates. Default is `false`.
@ -69,11 +69,9 @@ Let's animate a simple transition that changes a single HTML element from one st
In HTML, these attributes are set using ordinary CSS styles such as color and opacity. In Angular, use the `style()` function to specify a set of CSS styles for use with animations. You can collect a set of styles in an animation state, and give the state a name, such as `open` or `closed`.
<figureclass="lightbox">
<divclass="card">
<imgsrc="generated/images/guide/animations/open-closed.png"alt="open and closed states">
</div>
</figure>
<divclass="lightbox">
<imgsrc="generated/images/guide/animations/open-closed.png"alt="open and closed states">
</div>
### Animation state and styles
@ -168,11 +166,9 @@ The `trigger()` function describes the property name to watch for changes. When
In this example, we'll name the trigger `openClose`, and attach it to the `button` element. The trigger describes the open and closed states, and the timings for the two transitions.
<figureclass="lightbox">
<divclass="card">
<imgsrc="generated/images/guide/animations/triggering-the-animation.png"alt="triggering the animation">
</div>
</figure>
<divclass="lightbox">
<imgsrc="generated/images/guide/animations/triggering-the-animation.png"alt="triggering the animation">
@ -51,11 +51,9 @@ You define a component's view with its companion template. A template is a form
Views are typically arranged hierarchically, allowing you to modify or show and hide entire UI sections or pages as a unit. The template immediately associated with a component defines that component's *host view*. The component can also define a *view hierarchy*, which contains *embedded views*, hosted by other components.
A view hierarchy can include views from components in the same NgModule, but it also can (and often does) include views from components that are defined in different NgModules.
@ -83,11 +81,9 @@ Angular supports *two-way data binding*, a mechanism for coordinating the parts
The following diagram shows the four forms of data binding markup. Each form has a direction: to the DOM, from the DOM, or both.
Data binding plays an important role in communication between a template and its component, and is also important for communication between parent and child components.
@ -35,21 +35,17 @@ Here's a simple root NgModule definition.
NgModules provide a *compilation context* for their components. A root NgModule always has a root component that is created during bootstrap, but any NgModule can include any number of additional components, which can be loaded through the router or created through the template. The components that belong to an NgModule share a compilation context.
A component and its template together define a *view*. A component can contain a *view hierarchy*, which allows you to define arbitrarily complex areas of the screen that can be created, modified, and destroyed as a unit. A view hierarchy can mix views defined in components that belong to different NgModules. This is often the case, especially for UI libraries.
@ -109,11 +109,10 @@ To learn more, see [Schematics Overview](guide/schematics) and [Schematicsfor
## Publishing your library
Use the Angular CLI and the npm package manager to build and publish your library as an npm package.
Libraries are built in [AoT mode](guide/aot-compiler) by default, so you do not need to specify the `-prod` flag when building for publication.
Use the Angular CLI and the npm package manager to build and publish your library as an npm package. It is not recommended to publish Ivy libraries to NPM repositories. Before publishing a library to NPM, build it using the `--prod` flag which will use the older compiler and runtime known as View Engine instead of Ivy.
@ -359,11 +347,9 @@ You learned about some other methods in [Dependency Providers](guide/dependency-
The following `HeroOfTheMonthComponent` example demonstrates many of the alternatives and why you need them.
It's visually simple: a few properties and the logs produced by a logger.
<figureclass="lightbox">
<divclass="card">
<imgsrc="generated/images/guide/dependency-injection-in-action/hero-of-month.png"alt="Hero of the month">
</div>
</figure>
<divclass="lightbox">
<imgsrc="generated/images/guide/dependency-injection-in-action/hero-of-month.png"alt="Hero of the month">
</div>
The code behind it customizes how and where the DI framework provides dependencies.
The use cases illustrate different ways to use the [*provide* object literal](guide/dependency-injection-providers#provide) to associate a definition object with a DI token.
@ -474,11 +460,9 @@ The following example puts `MinimalLogger` to use in a simplified version of `He
The `HeroOfTheMonthComponent` constructor's `logger` parameter is typed as `MinimalLogger`, so only the `logs` and `logInfo` members are visible in a TypeScript-aware editor.
Behind the scenes, Angular sets the `logger` parameter to the full service registered under the `LoggingService` token, which happens to be the `DateLoggerService` instance that was [provided above](guide/dependency-injection-in-action#useclass).
@ -488,11 +472,9 @@ Behind the scenes, Angular sets the `logger` parameter to the full service regis
This is illustrated in the following image, which displays the logging date.
@ -140,7 +140,7 @@ Check out [angular-cli-ghpages](https://github.com/angular-buch/angular-cli-ghpa
## Server configuration
This section covers changes you may have make to the server or to files deployed to the server.
This section covers changes you may have to make to the server or to files deployed on the server.
{@a fallback}
@ -230,7 +230,7 @@ modified to serve `index.html`:
http.ListenAndServe(":"+httpPort, nil)
}
```
* [Ruby](https://www.ruby-lang.org/): create a Ruby server using ([sinatra](http://sinatrarb.com/)) with a basic Ruby file that configures the server `server.rb`:
``` ruby
@ -434,11 +434,9 @@ showing exactly which classes are included in the bundle.
Here's the output for the _main_ bundle of an example app called `cli-quickstart`.
| [`ViewEncapsulation.Native`](api/core/ViewEncapsulation#Native) | [`ViewEncapsulation.ShadowDom`](api/core/ViewEncapsulation#ShadowDom) | v6 | Use the native encapsulation mechanism of the renderer. See [view.ts](https://github.com/angular/angular/blob/3e992e18ebf51d6036818f26c3d77b52d3ec48eb/packages/core/src/metadata/view.ts#L32).
| [`defineInjectable`](api/core/defineInjectable) | `ɵɵdefineInjectable` | v8 | Used only in generated code. No source code should depend on this API. |
| [`entryComponents`](api/core/NgModule#entryComponents) | none | v9 | See [`entryComponents`](#entryComponents) |
| [`ANALYZE_FOR_ENTRY_COMPONENTS`](api/core/ANALYZE_FOR_ENTRY_COMPONENTS) | none | v9 | See [`ANALYZE_FOR_ENTRY_COMPONENTS`](#entryComponents) |
| `ModuleWithProviders` without a generic | `ModuleWithProviders` with a generic | v9 | See [`ModuleWithProviders` section](#moduleWithProviders) |
@ -166,7 +156,7 @@ This section lists all of the currently-deprecated features, which includes temp
{@a wtf}
### Web Tracing Framework integration
Angular previously has supported an integration with the Web Tracing Framework (WTF) for performance testing of Angular applications. This integration has not been maintained and likely does not work for the majority of Angular applications today. As a result, we are deprecating the integration in Angular version 8.
Angular previously has supported an integration with the [Web Tracing Framework (WTF)](https://google.github.io/tracing-framework/) for performance testing of Angular applications. This integration has not been maintained and defunct. As a result, the integration was deprecated in Angular version 8 and due to no evidence of any existing usage removed in version 9.
{@a deep-component-style-selector}
@ -454,6 +444,11 @@ The following APIs have been removed starting with version 9.0.0*:
@ -1244,19 +1244,20 @@ Images should be specified in an `<img>` tag.
For accessibility, always set the `alt` attribute with a meaningful description of the image.
You should nest the `<img>` tag within a `<figure>` tag, which styles the image within a drop-shadow frame. You'll need the editor's permission to skip the `<figure>` tag.
You should nest the `<img>` tag within a `<div class="lightbox">` tag, which styles the image within a drop-shadow frame. You'll need the editor's permission to skip the `lightbox` class on its `div` encapsulation.
Wide images can be a problem. Most browsers try to rescale the image but wide images may overflow the document in certain viewports.
@ -1285,9 +1288,9 @@ Wide images can be a problem. Most browsers try to rescale the image but wide im
**Do not set a width greater than 700px**. If you wish to display a larger image, provide a link to the actual image that the user can click on to see the full size image separately as in this example of `source-map-explorer` output from the "Ahead-of-time Compilation" guide:
<ahref="generated/images/guide/docs-style-guide/toh-pt6-bundle.png"title="Click to view larger image">
@ -42,11 +42,9 @@ After you register your configured class with the browser's custom-element regis
When your custom element is placed on a page, the browser creates an instance of the registered class and adds it to the DOM. The content is provided by the component's template, which uses Angular template syntax, and is rendered using the component and DOM data. Input properties in the component correspond to input attributes for the element.
<figureclass="lightbox">
<divclass="card">
<imgsrc="generated/images/guide/elements/customElement1.png"alt="Custom element in browser"class="left">
</div>
</figure>
<divclass="lightbox">
<imgsrc="generated/images/guide/elements/customElement1.png"alt="Custom element in browser"class="left">
</div>
<hrclass="clear">
@ -64,11 +62,9 @@ Use a JavaScript function, `customElements.define()`, to register the configure
and its associated custom-element tag with the browser's `CustomElementRegistry`.
When the browser encounters the tag for the registered element, it uses the constructor to create a custom-element instance.
<figureclass="lightbox">
<divclass="card">
<imgsrc="generated/images/guide/elements/createElement.png"alt="Transform a component to a custom element"class="left">
</div>
</figure>
<divclass="lightbox">
<imgsrc="generated/images/guide/elements/createElement.png"alt="Transform a component to a custom element"class="left">
| `browserslist` | Configures sharing of target browsers and Node.js versions among various front-end tools. See [Browserslist on GitHub](https://github.com/browserslist/browserslist) for more information. |
| `tsconfig.app.json` | Application-specific [TypeScript](https://www.typescriptlang.org/) configuration, including TypeScript and Angular template compiler options. See [TypeScript Configuration](guide/typescript-configuration). |
| `tsconfig.app.json` | Application-specific [TypeScript](https://www.typescriptlang.org/) configuration, including TypeScript and Angular template compiler options. See [TypeScript Configuration](guide/typescript-configuration) and [Angular Compiler Options](guide/angular-compiler-options). |
| `tsconfig.spec.json` | [TypeScript](https://www.typescriptlang.org/) configuration for the application tests. See [TypeScript Configuration](guide/typescript-configuration). |
@ -67,11 +67,9 @@ Here's a component with an input field for a single control implemented using re
The source of truth provides the value and status of the form element at a given point in time. In reactive forms, the form model is the source of truth. In the example above, the form model is the `FormControl` instance.
<figureclass="lightbox">
<divclass="card">
<imgsrc="generated/images/guide/forms-overview/key-diff-reactive-forms.png"alt="Reactive forms key differences">
</div>
</figure>
<divclass="lightbox">
<imgsrc="generated/images/guide/forms-overview/key-diff-reactive-forms.png"alt="Reactive forms key differences">
</div>
With reactive forms, the form model is explicitly defined in the component class. The reactive form directive (in this case, `FormControlDirective`) then links the existing `FormControl` instance to a specific form element in the view using a value accessor (`ControlValueAccessor` instance).
@ -84,11 +82,9 @@ Here's the same component with an input field for a single control implemented u
In template-driven forms, the source of truth is the template.
<figureclass="lightbox">
<divclass="card">
<imgsrc="generated/images/guide/forms-overview/key-diff-td-forms.png"alt="Template-driven forms key differences">
</div>
</figure>
<divclass="lightbox">
<imgsrc="generated/images/guide/forms-overview/key-diff-td-forms.png"alt="Template-driven forms key differences">
</div>
The abstraction of the form model promotes simplicity over structure. The template-driven form directive `NgModel` is responsible for creating and managing the `FormControl` instance for a given form element. It's less explicit, but you no longer have direct control over the form model.
@ -102,11 +98,9 @@ When building forms in Angular, it's important to understand how the framework h
As described above, in reactive forms each form element in the view is directly linked to a form model (`FormControl` instance). Updates from the view to the model and from the model to the view are synchronous and aren't dependent on the UI rendered. The diagrams below use the same favorite color example to demonstrate how data flows when an input field's value is changed from the view and then from the model.
<figureclass="lightbox">
<divclass="card">
<imgsrc="generated/images/guide/forms-overview/dataflow-reactive-forms-vtm.png"alt="Reactive forms data flow - view to model"width="100%">
</div>
</figure>
<divclass="lightbox">
<imgsrc="generated/images/guide/forms-overview/dataflow-reactive-forms-vtm.png"alt="Reactive forms data flow - view to model"width="100%">
</div>
The steps below outline the data flow from view to model.
@ -116,11 +110,9 @@ The steps below outline the data flow from view to model.
1. The `FormControl` instance emits the new value through the `valueChanges` observable.
1. Any subscribers to the `valueChanges` observable receive the new value.
<figureclass="lightbox">
<divclass="card">
<imgsrc="generated/images/guide/forms-overview/dataflow-reactive-forms-mtv.png"alt="Reactive forms data flow - model to view"width="100%">
</div>
</figure>
<divclass="lightbox">
<imgsrc="generated/images/guide/forms-overview/dataflow-reactive-forms-mtv.png"alt="Reactive forms data flow - model to view"width="100%">
</div>
The steps below outline the data flow from model to view.
@ -133,11 +125,9 @@ The steps below outline the data flow from model to view.
In template-driven forms, each form element is linked to a directive that manages the form model internally. The diagrams below use the same favorite color example to demonstrate how data flows when an input field's value is changed from the view and then from the model.
<figureclass="lightbox">
<divclass="card">
<imgsrc="generated/images/guide/forms-overview/dataflow-td-forms-vtm.png"alt="Template-driven forms data flow - view to model"width="100%">
</div>
</figure>
<divclass="lightbox">
<imgsrc="generated/images/guide/forms-overview/dataflow-td-forms-vtm.png"alt="Template-driven forms data flow - view to model"width="100%">
</div>
The steps below outline the data flow from view to model when the input value changes from *Red* to *Blue*.
@ -150,11 +140,9 @@ The steps below outline the data flow from view to model when the input value ch
1. Because the component template uses two-way data binding for the `favoriteColor` property, the `favoriteColor` property in the component
is updated to the value emitted by the `ngModelChange` event (*Blue*).
<figureclass="lightbox">
<divclass="card">
<imgsrc="generated/images/guide/forms-overview/dataflow-td-forms-mtv.png"alt="Template-driven forms data flow - model to view"width="100%">
</div>
</figure>
<divclass="lightbox">
<imgsrc="generated/images/guide/forms-overview/dataflow-td-forms-mtv.png"alt="Template-driven forms data flow - model to view"width="100%">
</div>
The steps below outline the data flow from model to view when the `favoriteColor` changes from *Blue* to *Red*.
@ -951,7 +951,7 @@ by returning an observable of simulated events.
## Security: XSRF protection
[Cross-Site Request Forgery (XSRF)](https://en.wikipedia.org/wiki/Cross-site_request_forgery) is an attack technique by which the attacker can trick an authenticated user into unknowingly executing actions on your website.
[Cross-Site Request Forgery (XSRF or CSRF)](https://en.wikipedia.org/wiki/Cross-site_request_forgery) is an attack technique by which the attacker can trick an authenticated user into unknowingly executing actions on your website.
`HttpClient` supports a [common mechanism](https://en.wikipedia.org/wiki/Cross-site_request_forgery#Cookie-to-Header_Token) used to prevent XSRF attacks.
When performing HTTP requests, an interceptor reads a token from a cookie, by default `XSRF-TOKEN`, and sets it as an HTTP header, `X-XSRF-TOKEN`.
Since only code that runs on your domain could read the cookie, the backend can be certain that the HTTP request came from your client application and not an attacker.
@ -25,6 +25,16 @@ After you have set up your app to use i18n, the CLI can help you with the follow
* Building and serving the app for a given locale, using the translated text.
* Creating multiple language versions of your app.
{@a setting-up-cli}
## Setting up localization with the Angular CLI
The first step to setting up localization when using the Angular CLI is to add the `@angular/localize` package to the project. This will install the package within your project as well as
initialize the project to take advantage of Angular's localization features.
<code-examplelanguage="sh"class="code-shell">
ng add @angular/localize
</code-example>
{@a setting-up-locale}
## Setting up the locale of your app
@ -76,12 +86,12 @@ time of writing:
## i18n pipes
Angular pipes can help you with internationalization: the `DatePipe`, `CurrencyPipe`, `DecimalPipe`
and `PercentPipe` use locale data to format data based on the `LOCALE_ID`.
and `PercentPipe` use locale data to format data based on the `LOCALE_ID` dependency injection token.
By default, Angular only contains locale data for `en-US`. If you set the value of
`LOCALE_ID` to another locale, you must import locale data for that new locale.
The CLI imports the locale data for you when you use the parameter `--configuration` with `ng serve` and
`ng build`.
By default, Angular only contains locale data for `en-US`.
The CLI automatically includes the locale data and sets the `LOCALE_ID` value for you when you use the
parameter `--i18nLocale` or option `i18nLocale` with `ng serve` and`ng build`.
However, if you manually set the value of `LOCALE_ID` to another locale, you must import locale data for that new locale.
If you want to import locale data for other languages, you can do it manually:
@ -98,6 +108,7 @@ locale id "fr-FR" instead of "fr".
The files in `@angular/common/locales` contain most of the locale data that you
need, but some advanced formatting options might only be available in the extra dataset that you can
import from `@angular/common/locales/extra`. An error message informs you when this is the case.
Ivy will automatically include the extra locale data if the locale was configured via `i18nLocale`.
@ -126,10 +137,10 @@ The i18n template translation process has four phases:
3. Edit the generated translation file: Translate the extracted text into the target language.
4. Merge the completed translation file into the app. To do this, use the Angular CLI `build` command to compile the app, choosing a [locale-specific configuration](#merge-aot), or specifying the following command options.
4. Merge the completed translation file into the app. To do this, use the Angular CLI `build` command to compile the app, choosing a [locale-specific configuration](#merge), or specifying the following command options.
*`--i18nFile`=*path to the translation file*
*`--i18nFormat`=*format of the translation file*
*`--i18nFormat`=*format of the translation file (only required if using an earlier version of Angular, or if you [disable Ivy](guide/ivy#opting-out-of-ivy-in-version-9))*
*`--i18nLocale`= *locale id*
The command replaces the original messages with translated text, and generates a new version of the app in the target language.
@ -381,17 +392,6 @@ Open a terminal window at the root of the app project and run the CLI command `x
By default, the command creates a file named `messages.xlf` in your project's root directory.
<div class="alert is-helpful">
If you don't use the CLI, you have two options:
* You can use the `ng-xi18n` tool directly from the `@angular/compiler-cli` package.
For more information, see the [`ng xi18n` command documentation](cli/xi18n).
* You can use the CLI Webpack plugin `AngularCompilerPlugin` from the `@ngtools/webpack` package.
Set the parameters `i18nOutFile` and `i18nOutFormat` to trigger the extraction.
For more information, see the [Angular Ahead-of-Time Webpack Plugin documentation](https://github.com/angular/angular-cli/tree/master/packages/ngtools/webpack).
</div>
{@a other-formats}
### Output options
@ -412,13 +412,13 @@ The command can read and write files in three translation formats:
You can specify the translation format explicitly with the `--i18nFormat` command option, as illustrated in
You can specify the translation format explicitly with the `--format` command option, as illustrated in
these example commands:
<code-example language="sh" class="code-shell">
ng xi18n --i18n-format=xlf
ng xi18n --i18n-format=xlf2
ng xi18n --i18n-format=xmb
ng xi18n --format=xlf
ng xi18n --format=xlf2
ng xi18n --format=xmb
</code-example>
The sample in this guide uses the default XLIFF 1.2 format.
@ -454,8 +454,7 @@ file. This information is not used by Angular, but external translation tools ma
{@a translate}
## Translate the source text
The `ng xi18n` command generates a translation source file named `messages.xlf` in the project `src`
folder.
By default, the `ng xi18n` command generates a translation source file named `messages.xlf` in the project `src` folder.
The next step is to translate the display strings in this source file into language-specific
translation files. The example in this guide creates a French translation file.
@ -630,18 +629,17 @@ translation file.
The compilation process is the same whether the translation file is in `.xlf` format or in another
format that Angular understands, such as `.xtb`.
How you provide this information depends upon whether you compile with
the JIT compiler or the AOT compiler.
* With [AOT](guide/i18n#merge-aot), you pass the information as configuration settings.
* With [JIT](guide/i18n#merge-jit), you provide the information at bootstrap time.
{@a merge-aot}
### Merge with the AOT compiler
The [AOT compiler](guide/glossary#aot) is part of a build process that produces a small, fast,
ready-to-run application package, typically for production.
ready-to-run application package, with Ivy it is now used for both production and development.
<div class="alert is-important">
Ivy does not support merging i18n translations when using JIT mode.
If you [disable Ivy](guide/ivy#opting-out-of-ivy-in-version-9) and are using JIT mode,
additional information regarding translation merging can be found [here](https://v8.angular.io/guide/i18n#merge-with-the-jit-compiler).
</div>
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
@ -650,7 +648,7 @@ detection or URL parameters.
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.
* `i18nFormat`: the format of the translation file (only required if using an earlier version of Angular, or if you [disable Ivy](guide/ivy#opting-out-of-ivy-in-version-9)).
* `i18nLocale`: the locale id.
You should also direct the output to a locale-specific folder to keep it separate from other locale versions of your app, by setting the `outputPath` configuration option.
@ -689,8 +687,11 @@ sections of this guide:
ng serve --configuration=fr
</code-example>
For production builds, you define a separate `production-fr` build configuration in
the CLI configuration file, `angular.json`.
For production builds, you can use configuration composition to execute both configurations:
<code-example language="sh" class="code-shell">
ng build --configuration=production,fr
</code-example>
```
...
@ -733,34 +734,6 @@ The same configuration options can also be provided through the CLI with your ex
ng build --prod --i18n-file src/locale/messages.fr.xlf --i18n-format xlf --i18n-locale fr
</code-example>
{@a merge-jit}
### Merge with the JIT compiler
The [JITcompiler](guide/glossary#jit) compiles your app in the browser as the app loads.
To support translation with the JIT compiler, you must do the following:
1. Import the appropriate language translation file as a string constant.
2. Create corresponding translation providers for the JIT compiler.
3. Bootstrap the app with those providers.
Three providers tell the JIT compiler how to translate the template texts for a particular language
while compiling the app:
* `TRANSLATIONS` is a string containing the content of the translation file.
* `TRANSLATIONS_FORMAT` is the format of the file: `xlf`, `xlf2`, or `xtb`.
* `LOCALE_ID` is the locale of the target language.
The Angular `bootstrapModule` method has a second `compilerOptions` parameter that can influence the
behavior of the compiler. You can use it to specify the translation providers:
When you use the CLI `build` or `serve` command to build your application for different locales, change the output path using the `--outputPath` command option (along with the i18n-specific command options), so that the translation files are saved to different locations.
<div #foo></div> <!-- matches in both old runtime and new runtime -->
</comp>
```
{@a undecorated-classes}
## All Classes That Use Angular DI Must Have An Angular Class-level Decorator
### Basic example of change:
In the previous rendering engine, the following would work:
```
export class DataService {
constructor(@Inject('CONFIG') public config: DataConfig) {}
}
@Injectable()
export class AppService extends DataService {...}
```
In Ivy, it will throw an error because `DataService` is using Angular dependency injection, but is missing an `@Injectable` decorator.
The following would also work in the previous rendering engine, but in Ivy would require a `@Directive` decorator because it uses DI:
```
export class BaseMenu {
constructor(private vcr: ViewContainerRef) {}
}
@Directive({selector: '[settingsMenu]'})
export class SettingsMenu extends BaseMenu {}
```
The same is true if your directive class extends a decorated directive, but does not have a decorator of its own.
If you're using the CLI, there are two automated migrations that should transition your code for you ([this one](guide/migration-injectable) and [this one](guide/migration-undecorated-classes)).
However, as you're adding new code in version 9, you may run into this difference.
### Background
When a class has an Angular decorator like `@Injectable` or `@Directive`, the Angular compiler generates extra code to support injecting dependencies into the constructor of your class.
When using inheritance, Ivy needs both the parent class and the child class to apply a decorator to generate the correct code.
Otherwise, 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, and Angular won't have the dependency info it needs to create it properly.
In the previous rendering engine, the compiler had global knowledge, so in some cases (such as AOT mode or the presence of certain injection flags), it could look up the missing data.
However, the Ivy compiler only processes each class in isolation.
This means that compilation has the potential to be faster (and opens the framework up for optimizations and features going forward), but the compiler can't automatically infer the same information as before.
Adding the proper decorator explicitly provides this information.
### Example of error
In JIT mode, the framework will throw the following error:
```
ERROR: This constructor is not compatible with Angular Dependency Injection because dependency at index 'X' is invalid.
This can happen if the dependency type is a primitive like a string or if an ancestor of this class is missing an Angular decorator.
Please check that 1) the type for dependency X is correct and 2) the correct Angular decorators are defined for this class and its ancestors.
```
In AOT mode, you'll see something like:
```
X inherits its constructor from Y, but the latter does not have an Angular decorator of its own.
Dependency injection will not be able to resolve the parameters of Y's constructor. Either add a
@Directive decorator to Y, or add an explicit constructor to X.
```
In some cases, the framework may not be able to detect the missing decorator.
In these cases, you'll generally see a runtime error thrown when there is a property access attempted on the missing dependency.
If dependency was `foo`, you'd see an error when accessing something like `foo.bar`:
```
Uncaught TypeError: Cannot read property 'bar' of undefined
```
If you see an error like this, and the `undefined` value refers to something that should have been injected, it may be this change.
### Recommended fix
- Add an `@Injectable` decorator to anything you plan to provide or inject.
```
@Injectable()
export class DataService {
constructor(@Inject('CONFIG') public config: DataConfig) {}
}
@Injectable()
export class AppService extends DataService {...}
```
- Add a [selectorless `@Directive` decorator](guide/migration-undecorated-classes#what-does-it-mean-to-have-a-directive-decorator-with-no-metadata-inside-of-it) to any class that extends a directive or any class from which a directive inherits.
```
@Directive() // selectorless, so it's not usable directly
@ -11,9 +11,9 @@ That said, some applications will likely need to apply some manual updates.
In version 9, [a few deprecated APIs have been removed](guide/updating-to-version-9#removals) and there are a [few breaking changes](guide/updating-to-version-9#breaking-changes) unrelated to Ivy.
If you're seeing errors after updating to version 9, you'll first want to rule those changes out.
To do so, temporarily [turn off Ivy in your `tsconfig.json`](guide/ivy#opting-out-of-angular-ivy) and re-start your app.
To do so, temporarily [turn off Ivy](guide/ivy#opting-out-of-angular-ivy) in your `tsconfig.json` and re-start your app.
If you're still seeing the errors, they are not specific to Ivy. In this case, you may want to consult the [general version 9 guide](guide/updating-to-version-9).
If you're still seeing the errors, they are not specific to Ivy. In this case, you may want to consult the [general version 9 guide](guide/updating-to-version-9). If you've opted into any of the stricter type-checking settings that are new with v9, you may also want to check out the [template type-checking guide](guide/template-typecheck).
If the errors are gone, switch back to Ivy by removing the changes to the `tsconfig.json` and review the list of expected changes below.
@ -21,40 +21,39 @@ If the errors are gone, switch back to Ivy by removing the changes to the `tscon
{@a common-changes}
### Changes You May See
- By default, `@ContentChildren` queries will only search direct child nodes in the DOM hierarchy (previously, they would search any nesting level in the DOM as long as another directive wasn't matched above it). ([details](guide/ivy-compatibility-examples#content-children-descendants))
* By default, `@ContentChildren` queries will only search direct child nodes in the DOM hierarchy (previously, they would search any nesting level in the DOM as long as another directive wasn't matched above it). [details](guide/ivy-compatibility-examples#content-children-descendants)
- All classes that use Angular DI must have an Angular decorator like `@Directive()` or `@Injectable` (previously, undecorated classes were allowed if an ancestor class or subclass had a decorator).
- Unbound inputs for directives (e.g. name in `<my-comp name="">`) are now set upon creation of the view, before change detection runs (previously, all inputs were set during change detection).
* All classes that use Angular DI must have an Angular decorator like `@Directive()` or `@Injectable` (previously, undecorated classes were allowed in AOT mode only or if injection flags were used). [details](guide/ivy-compatibility-examples#undecorated-classes)
* Unbound inputs for directives (e.g. name in `<my-comp name="">`) are now set upon creation of the view, before change detection runs (previously, all inputs were set during change detection).
{@a less-common-changes}
### Less Common Changes
### Less Common Changes
- Properties like `host` inside `@Component` and `@Directive` decorators can be inherited (previously, only properties with explicit field decorators like `@HostBinding` would be inherited).
* Properties like `host` inside `@Component` and `@Directive` decorators can be inherited (previously, only properties with explicit field decorators like `@HostBinding` would be inherited).
- HammerJS support is opt-in through importing the `HammerModule` (previously, it was always included in production bundles regardless of whether the app used HammerJS).
* HammerJS support is opt-in through importing the `HammerModule` (previously, it was always included in production bundles regardless of whether the app used HammerJS).
-`@ContentChild` and `@ContentChildren` queries will no longer be able to match their directive's own host node (previously, these queries would match the host node in addition to its content children).
*`@ContentChild` and `@ContentChildren` queries will no longer be able to match their directive's own host node (previously, these queries would match the host node in addition to its content children).
- If a token is injected with the `@Host` or `@Self` flag, the module injector is not searched for that token (previously, tokens marked with these flags would still search at the module level).
* If a token is injected with the `@Host` or `@Self` flag, the module injector is not searched for that token (previously, tokens marked with these flags would still search at the module level).
-If a template is declared in one view but inserted into a different view, change detection will occur for that template only when its insertion point is checked (previously, change detection would also run when its declaration point was checked).
*When accessing multiple local refs with the same name in template bindings, the first is matched (previously, the last instance was matched).
-When accessing multiple local refs with the same name in template bindings, the first is matched (previously, the last instance was matched).
*Directives that are used in an exported module (but not exported themselves) are exported publicly (previously, the compiler would automatically write a private, aliased export that it could use its global knowledge to resolve downstream).
-Directives that are used in an exported module (but not exported themselves) are exported publicly (previously, the compiler would automatically write a private, aliased export that it could use its global knowledge to resolve downstream).
*Foreign functions or foreign constants in decorator metadata aren't statically resolvable (previously, you could import a constant or function from another compilation unit, like a library, and use that constant/function in your `@NgModule` definition).
- Foreign functions or foreign constants in decorator metadata aren't statically resolvable (previously, you could import a constant or function from another compilation unit, like a library, and use that constant/function in your `@NgModule` definition).
* Forward references to directive inputs accessed through local refs are no longer supported by default.
-Forward references to directive inputs accessed through local refs are no longer supported by default.
*If there is both an unbound class attribute and a `[class]` binding, the classes in the unbound attribute will also be added (previously, the class binding would overwrite classes in the unbound attribute).
- If there is both an unbound class attribute and a `[class]`binding, the classes in the unbound attribute will also be added (previously, the class binding would overwrite classes in the unbound attribute).
* It is now an error to assign values to template-only variables like `item` in`ngFor="let item of items"` (previously, the compiler would ignore these assignments).
- It is now an error to assign values to template-only variables like `item` in `ngFor="let item of items"` (previously, the compiler would ignore these assignments).
* It's no longer possible to overwrite lifecycle hooks with mocks on directive instances for testing (instead, modify the lifecycle hook on the directive type itself).
-It's no longer possible to overwrite lifecycle hooks with mocks on directive instances for testing (instead, modify the lifecycle hook on the directive type itself).
*Special injection tokens (such as `TemplateRef` or `ViewContainerRef`) return a new instance whenever they are requested (previously, instances of special tokens were shared if requested on the same node). This primarily affects tests that do identity comparison of these objects.
-Special injection tokens (e.g. `TemplateRef` or `ViewContainerRef`) return a new instance whenever they are requested (previously, instances of special tokens were shared if requested on the same node). This primarily affects tests that do identity comparison of these objects.
*ICU parsing happens at runtime, so only text, HTML tags and text bindings are allowed inside ICU cases (previously, directives were also permitted inside ICUs).
- ICU parsing happens at runtime, so only text, HTML tags and text bindings are allowed inside ICU cases (previously, directives were also permitted inside ICUs).
* Providers formatted as `{provide: X}` without a `useValue`, `useFactory`, `useExisting`, or `useClass` property are treated like `{provide: X, useClass: X}` (previously, it defaulted to `{provide: X, useValue: undefined}`).
"postinstall": "ngcc --properties es2015 browser module main --first-only --create-ivy-entry-points"
}
}
</code-example>
<divclass="alert is-important">
The `postinstall` script will run on every installation of `node_modules`, including those performed by `ng update` and `ng add`.
If you perform multiple installs in a row, this can end up being slower than letting Angular CLI run `ngcc` on builds.
</div>
{@a maintaining-library-compatibility}
### Maintaining library compatibility
If you are a library author, you should keep using the View Engine compiler as of version 9.
By having all libraries continue to use View Engine, you will maintain compatibility with default v9 applications that use Ivy, as well as with applications that have opted to continue using View Engine.
@ -60,7 +87,8 @@ Before disabling Ivy, check out the debugging recommendations in the [Ivy Compat
To opt out of Ivy, change the `angularCompilerOptions` in your project's TypeScript configuration, most commonly located at `tsconfig.app.json` at the root of the workspace.
The value of the `enableIvy` flag is set to `true` by default, as of version 9.
The value of the `enableIvy` flag is set to `true` by default, as of version 9.
The following example shows how to set the `enableIvy` option to `false` in order to opt out of Ivy.
@ -70,17 +98,105 @@ The following example shows how to set the `enableIvy` option to `false` in orde
"outDir": "./out-tsc/app",
"types": []
},
"files": [
"src/main.ts",
"src/polyfills.ts"
],
"include": [
"src/**/*.ts"
"src/**/*.d.ts"
],
"exclude": [
"src/test.ts",
"src/**/*.spec.ts"
],
"angularCompilerOptions": {
"enableIvy": false
}
"angularCompilerOptions": {
"enableIvy": false
}
}
</code-example>
If you disable Ivy, you might also want to reconsider whether to make AOT compilation the default for your application development, as described [above](#aot-and-ivy). To revert the compiler default, set the build option `aot: false` in the `angular.json` configuration file.
<divclass="alert is-important">
If you disable Ivy, you might also want to reconsider whether to make AOT compilation the default for your application development, as described [above](#aot-and-ivy).
To revert the compiler default, set the build option `aot: false` in the `angular.json` configuration file.
</div>
If you disable Ivy and the project uses internationalization, you can also remove the `@angular/localize` runtime component from the project's polyfills file located be default at `src/polyfills.ts`.
To remove, delete the `import '@angular/localize/init';` line from the polyfills file.
* Load `$localize` onto the global scope - used if i18n tags appear in Angular templates.
*/
import '@angular/localize/init';
</code-example>
{@a using-ssr-without-angular-ivy}
### Using SSR without Ivy
If you opt out of Ivy and your application uses [Angular Universal](guide/universal) to render Angular applications on the server, you must also change the way the server performs bootstrapping.
The following example shows how you modify the `server.ts` file to provide the `AppServerModuleNgFactory` as the bootstrap module.
* Import `AppServerModuleNgFactory` from the `app.server.module.ngfactory` virtual file.
* Set `bootstrap: AppServerModuleNgFactory` in the `ngExpressEngine` call.
@ -29,6 +29,13 @@ generates a file called `app-routing.module.ts`, which is one of
the files you need for setting up lazy loading for your feature module.
Navigate into the project by issuing the command `cd customer-app`.
<divclass="alert is-helpful">
The `--routing` option requires Angular/CLI version 8.1 or higher.
See [Keeping Up to Date](guide/updating).
</div>
## Create a feature module with routing
Next, you’ll need a feature module with a component to route to.
@ -91,11 +98,9 @@ ng serve
Then go to `localhost:4200` where you should see “customer-app” and three buttons.
<figureclass="lightbox">
<divclass="card">
<imgsrc="generated/images/guide/lazy-loading-ngmodules/three-buttons.png"width="300"alt="three buttons in the browser">
</div>
</figure>
<divclass="lightbox">
<imgsrc="generated/images/guide/lazy-loading-ngmodules/three-buttons.png"width="300"alt="three buttons in the browser">
</div>
These buttons work, because the CLI automatically added the routes to the feature modules to the `routes` array in `app.module.ts`.
@ -137,30 +142,24 @@ The other feature module's routing module is configured similarly.
You can check to see that a module is indeed being lazy loaded with the Chrome developer tools. In Chrome, open the dev tools by pressing `Cmd+Option+i` on a Mac or `Ctrl+Shift+j` on a PC and go to the Network Tab.
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.
To see it again, or to test after working in the project, clear everything out by clicking the circle with a line through it in the upper left of the Network Tab:
# Migration to Add Missing `@Injectable()` Decorators
## What does this schematic do?
### What does this schematic do?
This schematic adds an `@Injectable()` decorator to a class
if the class has been added as a provider anywhere in the application.
1.This schematic adds an `@Injectable()` decorator to classes which are provided in the
application but are not decorated.
2. The schematic updates providers which follow the `{provide: SomeToken}` pattern
to explicitly specify `useValue: undefined`.
**Example for missing `@Injectable()`**
An example diff might look like the following:
_Before migration:_
```typescript
exportclassMyService{...}
exportclassMyOtherService{...}
exportclassMyThirdClass{...}
exportclassMyFourthClass{...}
exportclassMyFifthClass{...}
**Before:**
```ts
exportclassTypeCase{...}
@NgModule({
providers:[
MyService,
{provide: SOME_TOKEN,useClass: MyOtherService},
// The following classes do not need to be decorated because they
// are never instantiated and just serve as DI tokens.
{provide: MyThirdClass,useValue: ...},
{provide: MyFourthClass,useFactory: ...},
{provide: MyFifthClass,useExisting: ...},
]
})
```
**After:**
_After migration:_
```ts
@Injectable()
exportclassTypeCase{...}
exportclassMyService{...}
@Injectable()
exportclassMyOtherService{...}
exportclassMyThirdClass{...}
exportclassMyFourthClass{...}
exportclassMySixthClass{...}
...
```
Note that `MyThirdClass`, `MyFourthClass` and `MyFifthClass` do not need to be decorated
with `@Injectable()` because they are never instantiated, but just used as a [DI token][DI_TOKEN].
There are a few cases where the decorator won't be added. For example:
**Example for provider needing `useValue: undefined`**
- It already has another decorator such as `@Component()`, `@Directive()` or `@Pipe()`. These decorators already cause the compiler to generate the necessary information.
- The provider definition has`useValue`, `useFactory`, or `useExisting`. In
these cases, the framework doesn't need the `@Injectable()` decorator to create the class
because it can just use the value,
factory function, or existing instance that was provided.
This example shows a provider following the `{provide: X}` pattern. The provider needs to be
migrated to a more explicit definition where`useValue: undefined` is specified.
For example, for the following module definition, the schematic will check
`TypeCase`, `ProvideCase`, `ExistingClass`, and `SomeClass` to ensure they
are marked with the `@Injectable()` decorator and add one if not.
_Before migration_:
```typescript
{provide: MyToken}
```
_After migration_:
```typescript
{provide: MyToken,useValue: undefined}
```
```ts
@NgModule({
providers: [
// TypeCase needs @Injectable()
TypeCase,
// ProvideCase needs @Injectable()
{provide: ProvideCase},
// No @Injectable() needed because the value will be used
{provide: ValueCase, useValue: 0},
// No @Injectable() needed because factory will be used
// No @Injectable() needed because it has a @Pipe() decorator
PipeCase,
]
})
```
## Why is this migration necessary?
### Why is adding `@Injectable()` necessary?
In our docs, we've always recommended adding `@Injectable()`
decorators to any class that is provided or injected in your application.
@ -71,15 +72,39 @@ to strictly require the decorator because doing so enables further
optimization of both the compiler and the runtime. This schematic
adds any `@Injectable()` decorators that may be missing to future-proof your app.
### Why is adding `useValue: undefined` necessary?
Consider the following pattern:
## When should I be adding `@Injectable()` decorators to classes?
```typescript
@NgModule({
providers:[{provide: MyService}]
})
```
Any class that is provided or injected somewhere must have an `@Injectable()` decorator. The decorator is necessary for the framework to properly create an instance of that class through DI.
Providers using this pattern will behave as if they provide `MyService` as [DI token][DI_TOKEN]
with the value of `undefined`. This is not the case in Ivy where such providers will be interpreted
as if `useClass: MyService` is specified. This means that these providers will behave differently
when updating to version 9 and above. To ensure that the provider behaves the same as before, the
DI value should be explicitly set to `undefined`.
However, as noted above, classes that already have another class decorator like `@Pipe` do not need both decorators. The existing class decorator will cause the compiler to generate the proper information.
### When should I be adding `@Injectable()` decorators to classes?
Any class that is provided must have an `@Injectable()` decorator. The decorator is necessary
for the framework to properly create an instance of that class through DI.
## Should I update my library?
However, classes which are already decorated with `@Pipe`, `@Component` or `@Directive` do not
need both decorators. The existing class decorator already instructs the compiler to generate the
needed information.
Yes, if your library has any tokens that are meant to be injected, they should be updated with the `@Injectable()` decorator. In a future version of Angular, a missing `@Injectable()` decorator will always throw an error.
### Should I update my library?
Yes, if your library has any classes that are meant to be injected, they should be updated with
the `@Injectable()` decorator. In a future version of Angular, a missing `@Injectable()` decorator
will always throw an error.
Additionally, providers in your library that follow the described `{provide: X}` pattern should be
updated to specify an explicit value. Without explicit value, these providers can behave
differently based on the Angular version in applications consuming your library.
This schematic adds an [Angular compatibility compiler](guide/ngcc), or `ngcc`, invocation to npm/yarn's `postinstall` script in the `package.json` of an Angular CLI workspace.
This script is invoked after each execution of `npm install` and modifies `node_modules` by converting any found Angular libraries to a format that is compatible with Angular version 9.
An example diff might look like the following:
**Before:**
```json
"scripts":{
"ng":"ng",
"start":"ng serve",
"build":"ng build",
"test":"ng test",
"lint":"ng lint",
"e2e":"ng e2e"
},
```
**After:**
```json
"scripts":{
"ng":"ng",
"start":"ng serve",
"build":"ng build",
"test":"ng test",
"lint":"ng lint",
"e2e":"ng e2e",
"postinstall":"ngcc --properties es2015 browser module main --first-only --create-ivy-entry-points"
},
```
If the `package.json` already contains a `postinstall` script, then the `ngcc` invocation will be prepended to the current command:
**Before:**
```json
"scripts":{
...
"postinstall":"some-command"
},
```
**After:**
```json
"scripts":{
...
"postinstall":"ngcc --properties es2015 browser module main --first-only --create-ivy-entry-points && some-command"
},
```
## Why is this migration necessary?
This migration is a build performance optimization that enables `ngcc` to parallelize the compilation of npm libraries.
An application build performed via CLI's `ng build` should succeed regardless of this `postinstall` script being installed, because the CLI has `ngcc` built-in.
However, this built-in `ngcc` can't parallelize the compilation of multiple libraries, and therefore often takes considerably longer to run.
## Can I customize the `ngcc` options in the `postinstall` script?
By default the `postinstall` script invokes `ngcc` with options to compile only the most commonly needed library formats.
For some projects, especially those that depend on the CommonJS distribution of Angular (for example, Angular Universal apps), it might be beneficial to modify the `postinstall` script to also compile the CommonJS distribution of the library:
```json
"scripts":{
...
"postinstall":"ngcc --properties es2015 browser module main --first-only --create-ivy-entry-points && ngcc --properties main --create-ivy-entry-points"
},
```
For the full set of options run `npx ngcc --help` or `yarn ngcc --help`.
## Will libraries compiled with `ngcc` still be compatible with Angular version 8?
Yes, the migration causes `ngcc` to be invoked with the `--create-ivy-entry-points` flag, which ensures that the `ngcc` compilation is non-destructive, so the same `node_modules` can be used with Angular version 8 and version 9.
@ -110,11 +108,9 @@ Update the template with a button to simulate a name update. When you click the
The form model is the source of truth for the control, so when you click the button, the value of the input is changed within the component class, overriding its current value.
The **Submit** button is disabled because `profileForm` is invalid due to the required `firstName` form control. After you fill out the `firstName` input, the form becomes valid and the **Submit** button is enabled.
@ -422,11 +412,9 @@ Add the template HTML below after the `<div>` closing the `formGroupName` elemen
The `*ngFor` directive iterates over each form control instance provided by the aliases form array instance. Because form array elements are unnamed, you assign the index to the `i` variable and pass it to each control to bind it to the `formControlName` input.
Each time a new alias instance is added, the new form array instance is provided its control based on the index. This allows you to track each individual control when calculating the status and value of the root control.
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.