Compare commits

...

219 Commits

Author SHA1 Message Date
d06b6de409 release: cut the v9.0.4 release 2020-02-27 13:42:19 -08:00
9b53054ea8 refactor(ngcc): guard against a crash if source-map flattening fails (#35718)
Source-maps in the wild could be badly formatted,
causing the source-map flattening processing to fail
unexpectedly. Rather than causing the whole of ngcc
to crash, we gracefully fallback to just returning the
generated source-map instead.

PR Close #35718
2020-02-27 16:09:37 -05:00
bfe7657006 fix(ngcc): handle mappings outside the content when flattening source-maps (#35718)
Previously when rendering flattened source-maps, it was assumed that no
mapping would come from a line that is outside the lines of the actual
source content. It turns out this is not a valid assumption.

Now the code that renders flattened source-maps will handle such
mappings, with the additional benefit that the rendered source-map
will only contain mapping lines up to the last mapping, rather than a
mapping line for every content line.

Fixes #35709

PR Close #35718
2020-02-27 16:09:37 -05:00
7ff845b72f fix(ngcc): handle missing sources when flattening source-maps (#35718)
If a package has a source-map but it does not provide
the actual content of the sources, then the source-map
flattening was crashing.

Now we ignore such mappings that have no source
since we are not able to compute the merged
mapping if there is no source file.

Fixes #35709

PR Close #35718
2020-02-27 16:09:37 -05:00
bf6fbf5a74 feat(docs-infra): add useful links if landed on 404 page and no search results found (#34978)
Added additional links which can help user find the things they are
looking for when there are no search results (when searching or on a 404
page).

Note:
This commit increases the main bundle's payload size due to the extra
content of the `aio-search-results` component.

Fixes #31532

PR Close #34978
2020-02-27 11:02:00 -08:00
e4f05d1952 ci(docs-infra): increase AIO ViewEngine payload size limit (#34978)
In #35702, the payload size limit for Ivy builds was bumped to account
for small incremental increases in recent PRs. The ViewEngine size has
also increased similarly (~500B), but it was not updated in #35702,
because its total increase was just below the 500B error threshold (by
6B).

This commit bumps the ViewEngine size limit too.

Note: Any investigation for the Ivy size increase (as a follow-up
to #35702) will most likely also apply to ViewEngine, since the size was
increased by the same amount.

PR Close #34978
2020-02-27 11:01:59 -08:00
f11fc1e3bd docs: correct spelling of 'detection' (#35723)
PR Close #35723
2020-02-27 10:49:16 -08:00
9064f4ecdb fix(ngcc): allow deep-import warnings to be ignored (#35683)
This commit adds a new ngcc configuration, `ignorableDeepImportMatchers`
for packages. This is a list of regular expressions matching deep imports
that can be safely ignored from that package. Deep imports that are not
ignored cause a warning to be logged.

// FW-1892

Fixes #35615

PR Close #35683
2020-02-27 10:48:49 -08:00
0eda98a28b test(docs-infra): fix tests with new topics property (#35539)
PR Close #35539
2020-02-27 10:47:52 -08:00
60921e8efd feat(docs-infra): add searchKeywords preprocessor (#35539)
This commit adds a new preprocessor to use `${@searchKeywords}`, allowing
the docs to use a list of custom search phrases that will be
prioritized over the keywords found in the content.

Closes #35449

PR Close #35539
2020-02-27 10:47:52 -08:00
c78df781f7 release: cut the v9.0.3 release 2020-02-26 20:37:08 -08:00
dc800b2f9e ci: increase AIO payload size limit (#35702)
This commit updates AIO payload size limit that is triggering a problem after merging 0bc35a71e2. That commit added some payload size, but all checks were "green" for the original PR (#34574), so it looks like it's an accumulated payload size increase from multiple changes. The goal of this commit is to bring the master branch back to "green" state.

PR Close #35702
2020-02-26 16:31:56 -08:00
79aaaa3254 fix(ivy): injecting incorrect provider when re-providing injectable with useClass (#34574)
If an injectable has a `useClass`, Ivy injects the token in `useClass`, rather than the original injectable, if the injectable is re-provided under a different token. The correct behavior is that it should inject the re-provided token, no matter whether it has `useClass`.

Fixes #34110.

PR Close #34574
2020-02-26 13:00:22 -08:00
c2dbcd36a6 fix(animations): Remove ɵAnimationDriver from private exports (#35690)
ɵAnimationDriver can be safely removed from private exports as AnimationDriver
is already a public export.  Since its already available, we can safely remove
its declaration and migrate its only usage in our repo to rely on the public
AnimationDriver symbol.

PR Close #35690
2020-02-26 12:59:31 -08:00
788d5d7046 test: run /integration/ng_elements_schematics test with bazel (#35669)
PR Close #35669
2020-02-26 12:58:36 -08:00
9ff778abe8 build: add npm package manifest to npm_integration_test (#35669)
PR Close #35669
2020-02-26 12:58:36 -08:00
d58b5ce486 build: polish up bazel karma saucelabs info tools/saucelabs/README.md (#35667)
PR Close #35667
2020-02-26 12:58:15 -08:00
f25d00a45d ci: add ayazhafiz to ownership of language-service code (#35651)
PR Close #35651
2020-02-26 12:57:29 -08:00
4c2bd64642 fix(ivy): better inference for circularly referenced directive types (#35622)
It's possible to pass a directive as an input to itself. Consider:

```html
<some-cmp #ref [value]="ref">
```

Since the template type-checker attempts to infer a type for `<some-cmp>`
using the values of its inputs, this creates a circular reference where the
type of the `value` input is used in its own inference:

```typescript
var _t0 = SomeCmp.ngTypeCtor({value: _t0});
```

Obviously, this doesn't work. To resolve this, the template type-checker
used to generate a `null!` expression when a reference would otherwise be
circular:

```typescript
var _t0 = SomeCmp.ngTypeCtor({value: null!});
```

This effectively asks TypeScript to infer a value for this context, and
works well to resolve this simple cycle. However, if the template
instead tries to use the circular value in a larger expression:

```html
<some-cmp #ref [value]="ref.prop">
```

The checker would generate:

```typescript
var _t0 = SomeCmp.ngTypeCtor({value: (null!).prop});
```

In this case, TypeScript can't figure out any way `null!` could have a
`prop` key, and so it infers `never` as the type. `(never).prop` is thus a
type error.

This commit implements a better fallback pattern for circular references to
directive types like this. Instead of generating a `null!` in place for the
reference, a type is inferred by calling the type constructor again with
`null!` as its input. This infers the widest possible type for the directive
which is then used to break the cycle:

```typescript
var _t0 = SomeCmp.ngTypeCtor(null!);
var _t1 = SomeCmp.ngTypeCtor({value: _t0.prop});
```

This has the desired effect of validating that `.prop` is legal for the
directive type (the type of `#ref`) while also avoiding a cycle.

Fixes #35372
Fixes #35603
Fixes #35522

PR Close #35622
2020-02-26 12:57:10 -08:00
e6c416fe74 fix(ivy): provide a more detailed error message for NG6002/NG6003 (#35620)
NG6002/NG6003 are errors produced when an NgModule being compiled has an
imported or exported type which does not have the proper metadata (that is,
it doesn't appear to be an @NgModule, or @Directive, etc. depending on
context).

Previously this error message was a bit sparse. However, Github issues show
that this is the most common error users receive when for whatever reason
ngcc wasn't able to handle one of their libraries, or they just didn't run
it. So this commit changes the error message to offer a bit more useful
context, instructing users differently depending on whether the class in
question is from their own project, from NPM, or from a monorepo-style local
dependency.

PR Close #35620
2020-02-26 12:56:48 -08:00
36dc1c7872 fix(core): support sanitizer value in the [style] bindings (#35564)
When binding to `[style]` we correctly sanitized/unwrapped properties but we did not do it for the object itself.

```
@HostBinding("style")
style: SafeStyle = this.sanitizer.bypassSecurityTrustStyle(
    "background: red; color: white; display: block;"
  );
```

Above code would fail since the `[style]` would not unwrap the `SafeValue` and would treat it as object resulting in incorrect behavior.

Fix #35476 (FW-1875)

PR Close #35564
2020-02-26 12:56:10 -08:00
c5ef307d95 fix(docs-infra): do not break when cookies are disabled in the browser (#35557)
Whenever cookies are disabled in the browser, `window.localStorage` is
not avaialable to the app (i.e. even trying to access
`window.localStorage` throws an error).

To avoid breaking the app, we use a no-op `Storage` implementation if
`window.localStorage` is not available.

(This is similar to #33829, but for `localStorage` instead of
`sessionStorage`.)

Fixes #35555

PR Close #35557
2020-02-26 12:54:55 -08:00
74afc2df82 feat(docs-infra): add entry-point label on api endpoint docs (#35427)
On API docs pages for Angular packages (e.g. https://angular.io/api/common), we show all primary and secondary entry-points. Following a link to one of the secondary entry-points (e.g. https://angular.io/api/common/http), navigates the docs page for the secondary entry-point, where it is incorrectly (and misleadingly) labelled as PACKAGE and not as an entry-point.

Implemented a new ENTRY-POINT label and add support for correctly differentiating between entry-points and packages.

Fixes #34081

PR Close #35427
2020-02-26 12:54:23 -08:00
0a8e8cd1f3 feat(ngcc): implement source-map flattening (#35132)
The library used by ngcc to update the source files (MagicString) is able
to generate a source-map but it is not able to account for any previous
source-map that the input text is already associated with.

There have been various attempts to fix this but none have been very
successful, since it is not a trivial problem to solve.

This commit contains a novel approach that is able to load up a tree of
source-files connected by source-maps and flatten them down into a single
source-map that maps directly from the final generated file to the original
sources referenced by the intermediate source-maps.

PR Close #35132
2020-02-26 12:51:36 -08:00
4f9798007d test(core): check dependency in extended child (#34767)
Related to https://github.com/angular/angular/issues/31337

PR Close #34767
2020-02-26 12:50:53 -08:00
0328e030b3 docs(common): update ngForTrackBy error URL (#34761)
Old URL is redirected to
`https://angular.io/api/common/NgForOf#!#change-propagation`
which is not exactly
`https://angular.io/api/common/NgForOf#change-propagation`

PR Close #34761
2020-02-26 12:47:49 -08:00
Zac
ae7b5f4dc3 docs(core): correct insertBefore's description (#34547)
Update the description of `refChild`
Based on https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore
PR Close #34547
2020-02-26 12:46:11 -08:00
Zac
a13bf202f6 docs(core): describe your change... (#34513)
According to https://angular.io/guide/lifecycle-hooks#ondestroy
"Put cleanup logic in ngOnDestroy(), the logic that must run before Angular destroys the directive."
PR Close #34513
2020-02-26 12:45:42 -08:00
19003a42f3 docs: more precise docs for template statement syntax (#34348)
PR Close #34348
2020-02-26 12:44:59 -08:00
1a4456d432 docs: add documentation of NgZone with zone.js (#34295)
PR Close #34295
2020-02-26 12:43:00 -08:00
406ce8c884 refactor(platform-browser): Hoist functions to workaround optimization bug. (#32230)
Technically, function definitions can live anywhere because they are
hoisted. However, in this case Closure optimizations break when exported
function definitions are referred in another static object that is
exported.

The bad pattern is:
```
exports const obj = {f};
export function f() {...}
```

which turns to the following in Closure's module system:
```
goog.module('m');

exports.obj = {f};

function f() {...}
exports.f = f;
```

which badly optimizes to (note module objects are collapsed)
```
var b = a; var a = function() {...};  // now b is undefined.
```

This is an optimizer bug and should be fixed in Closure, but in the
meantime this change is a noop and will unblock other changes we want to
make.

PR Close #32230
2020-02-26 09:04:41 -08:00
d6904882d0 fix(ivy): error when accessing NgModuleRef.componentFactoryResolver in constructor (#35637)
Currently we resolve the `NgModuleRef.componentFactoryResolver` by going through the injector, but the problem is that `ComponentFactoryResolver` has a dependency on `NgModuleRef`, which means that if the module that's attached to the ref tries to inject  `ComponentFactoryResolver` in its constructor, we'll create a circular dependency which throws at runtime.

These changes resolve the issue by creating the `ComponentFactoryResolver` manually ahead of time without going through the injector. We can do this safely, because the only dependency for the resolver is the current module ref which is providing it.

Aside from fixing the issue, another advantage to this approach is that it should reduce the amount of generated JS, because it removes a getter and a provider definitio.

Fixes #35580.

PR Close #35637
2020-02-25 13:19:14 -08:00
c9cac92628 build(packaging): add repository.directory field to package.jsons (#27544)
PR Close #27544
2020-02-25 13:12:46 -08:00
7403ba13d5 fix(language-service): get the right 'ElementAst' in the nested HTML tag (#35317)
For example, '<div><p string-model~{cursor}></p></div>', when provide the hover info for 'string-model', the 'path.head' is root tag 'div'. Use the parent of 'path.tail' instead.

PR Close #35317
2020-02-25 13:12:09 -08:00
349539e551 perf(core): avoid recursive scope recalculation when TestBed.overrideModule is used (#35454)
Currently if TestBed detects that TestBed.overrideModule was used for module X, transitive scopes are recalculated recursively for all modules that X imports and previously calculated data (stored in cache) is ignored. This behavior was introduced in https://github.com/angular/angular/pull/33787 to fix stale transitive scopes issue (cache was not updated if module overrides are present).

The perf issue comes from a "diamond" problem, where module X is overridden which imports modules A and B, which both import module C. Under previous logic, module C gets its transitive deps recomputed multiple times, during the recompute for both A and B. For deep graphs and big common/shared modules this can be super costly.

This commit updates the logic to recalculate ransitive scopes for the overridden module, while keeping previously calculated scopes of other modules untouched.

PR Close #35454
2020-02-25 13:11:43 -08:00
315ad6370a docs: update getting started topics to avoid duplicate topic names (#35457)
PR Close #35457
2020-02-25 13:10:31 -08:00
64a415b91c fix(service-worker): treat 503 as offline (#35595)
Prior to this commit the service worker only treated 504 errors as "effectively offline".
This commit changes the behaviour to treat both 503 (Service Unavailable) and 504 as "offline".

Fixes #35571

PR Close #35595
2020-02-25 13:10:11 -08:00
47d6ab9d92 test(compiler): add correct use case of ngFor in r3 ast (#35671)
The only test case for `ngFor` exercises an incorrect usage which causes
two bound attributes to be generated . This commit adds a canonical and
correct usage to show the difference between the two.

PR Close #35671
2020-02-25 13:09:09 -08:00
8cac5fec20 ci: move saucelabs_ivy & saucelabs_view_engine to the daily monitoring CircleCI workflow (#35516)
PR Close #35516
2020-02-24 17:27:22 -08:00
2b0c2a44d0 test: disable broken saucelabs tests with “fixme-saucelabs-ivy” & “fixme-saucelabs-ve” tags (#35516)
PR Close #35516
2020-02-24 17:27:22 -08:00
11f65c0c6c test: saucelab targets for all karma tests (#35516)
PR Close #35516
2020-02-24 17:27:22 -08:00
1d9e00ec38 build: fix unbound variable in sauce-service.sh script (#35516)
PR Close #35516
2020-02-24 17:27:22 -08:00
2f140f5118 fix(router): removed unused ApplicationRef dependency (#35642)
As a part of the process of setting up Router providers, we use `ApplicationRef` as a dependency while providing `Router` token. The thing is that `ApplicationRef` is actually unused (all referenced were removed in 5a849829c4 (diff-c0baae5e1df628e1a217e8dc38557fcb)), but it's still listed as dependency. This is causing problems in case `Router` is used as a dependency for factory functions provided as `APP_INITIALIZERS` multi-token (causing cyclic dependency). This commit removes unused `ApplicationRef` dependency in `Router`, so it can be used without causing cyclic dependency issue.

PR Close #35642
2020-02-24 17:27:02 -08:00
8f48dc0653 docs: add more relevant statistic for page load (#35649)
PR Close #35649
2020-02-24 17:26:41 -08:00
89f6b341a3 docs: add amazon s3 builder package (#34783)
PR Close #34783
2020-02-24 09:14:04 -08:00
d83f62d30a fix(ngcc): capture path-mapped entry-points that start with same string (#35592)
Previously if there were two path-mapped libraries that are in
different directories but the path of one started with same string
as the path of the other, we would incorrectly return the shorter
path - e.g. `dist/my-lib` and `dist/my-lib-second`. This was because
the list of `basePaths` was searched in ascending alphabetic order and
we were using `startsWith()` to match the path.

Now the `basePaths` are searched in reverse alphabetic order so the
longer path will be matched correctly.

// FW-1873

Fixes #35536

PR Close #35592
2020-02-24 09:11:44 -08:00
1112875981 fix(localize): improve placeholder mismatch error message (#35593)
The original error message was confusing since often it is the
translation that is at fault not the message.

PR Close #35593
2020-02-24 09:11:21 -08:00
a4572c3b12 docs: fix routing code to use navigate (#35176)
Previously, the example in the `router` guide was not
preserving the query params after logging in.

This commit fixes this by using `navigate` instead of
using `navigateByUrl`, which ignores any properties in
the `NavigationExtras` that would change the provided URL.

Fixes 34917

PR Close #35176
2020-02-24 09:00:03 -08:00
45bd6d6e40 build: add instructions for adding new integration tests to integration/README.md (#33927)
PR Close #33927
2020-02-24 08:59:21 -08:00
4caacf2aff build: optimize integration tests on CI (#33927)
PR Close #33927
2020-02-24 08:59:20 -08:00
9f53df8168 build: add new integration tests & bazel-in-bazel tests to … glob (#33927)
Move bazel-in-bazel them to test job & increase it is 2xlarge+. test_integration_bazel is removed. Overall CI credit usage is reduced.

test: include ng_elements_schematics in legacy integration tests temporarily

This test was recently added and use a new pattern that doesn't work with npm_integration_test out of the box. It needs some refactoring to work. Left a TODO for this

PR Close #33927
2020-02-24 08:59:20 -08:00
3ef4b079e4 build: use puppeteer in integration/bazel-schematics (#33927)
PR Close #33927
2020-02-24 08:59:20 -08:00
49db9eeb33 build: remove dep on tsickle from platform-server (#33927)
PR Close #33927
2020-02-24 08:59:20 -08:00
9efd7afd8a build: remove CI_CHROMEDIRVER_VERSION_ARG from integration/bazel-schematics (#33927)
This means we don't need the action_env. Borrowed from @gkalpak's changes in https://github.com/angular/angular/pull/35381.

PR Close #33927
2020-02-24 08:59:20 -08:00
0b33828970 ci: bump CircleCi test job to xlarge2 CI job (#33927)
Now that large integration tests are running locally in parallel (they can't run on RBE yet as they require network access for yarn install), this test is running out of memory consistently with the xlarge machine

PR Close #33927
2020-02-24 08:59:20 -08:00
97556fd2ca ci: install java runtime in test job (#33927)
Install java runtime which is required by some integration tests such as `//integration:hello_world__closure_test`, `//integration:i18n_test` and `//integration:ng_elements_test` to run the closure compiler.

PR Close #33927
2020-02-24 08:59:20 -08:00
d95b2f0100 build: no-remote-exec for integration tests (#33927)
For now until RBE actions can access network for `yarn install`

PR Close #33927
2020-02-24 08:59:20 -08:00
2f572772b0 build: add npm_integration_test && angular_integration_test (#33927)
* it's tricky to get out of the runfiles tree with `bazel test` as `BUILD_WORKSPACE_DIRECTORY` is not set but I employed a trick to read the `DO_NOT_BUILD_HERE` file that is one level up from `execroot` and that contains the workspace directory. This is experimental and if `bazel test //:test.debug` fails than `bazel run` is still guaranteed to work as  `BUILD_WORKSPACE_DIRECTORY` will be set in that context

* test //integration:bazel_test and //integration:bazel-schematics_test exclusively

* run "exclusive" and "manual" bazel-in-bazel integration tests in their own CI job as they take 8m+ to execute

```
//integration:bazel-schematics_test                                      PASSED in 317.2s
//integration:bazel_test                                                 PASSED in 167.8s
```

* Skip all integration tests that are now handled by angular_integration_test except the tests that are tracked for payload size; these are:
- cli-hello-world*
- hello_world__closure

* add & pin @babel deps as newer versions of babel break //packages/localize/src/tools/test:test

@babel/core dep had to be pinned to 7.6.4 or else //packages/localize/src/tools/test:test failed. Also //packages/localize uses @babel/generator, @babel/template, @babel/traverse & @babel/types so these deps were added to package.json as they were not being hoisted anymore from @babel/core transitive.

NB: integration/hello_world__systemjs_umd test must run with systemjs 0.20.0
NB: systemjs must be at 0.18.10 for legacy saucelabs job to pass
NB: With Bazel 2.0, the glob for the files to test `"integration/bazel/**"` is empty if integation/bazel is in .bazelignore. This glob worked under these conditions with 1.1.0. I did not bother testing with 1.2.x as not having integration/bazel in .bazelignore is correct.

PR Close #33927
2020-02-24 08:59:20 -08:00
bb09cd0e41 fix(ivy): error in AOT when pipe inherits constructor from injectable that uses DI (#35468)
When a pipe inherits its constructor, and as a result its factory, from an injectable in AOT mode, it can end up throwing an error, because the inject implementation hasn't been set yet. These changes ensure that the implementation is set before the pipe's factory is invoked.

Note that this isn't a problem in JIT mode, because the factory inheritance works slightly differently, hence why this test isn't going through `TestBed`.

Fixes #35277.

PR Close #35468
2020-02-21 12:37:09 -08:00
628f957c4a fix(ivy): add strictLiteralTypes to align Ivy + VE checking of literals (#35462)
Under View Engine's default (non-fullTemplateTypeCheck) checking, object and
array literals which appear in templates are treated as having type `any`.
This allows a number of patterns which would not otherwise compile, such as
indexing an object literal by a string:

```html
{{ {'a': 1, 'b': 2}[value] }}
```

(where `value` is `string`)

Ivy, meanwhile, has always inferred strong types for object literals, even
in its compatibility mode. This commit fixes the bug, and adds the
`strictLiteralTypes` flag to specifically control this inference. When the
flag is `false` (in compatibility mode), object and array literals receive
the `any` type.

PR Close #35462
2020-02-21 12:36:12 -08:00
02599e452a fix(ivy): emulate a View Engine type-checking bug with safe navigation (#35462)
In its default compatibility mode, the Ivy template type-checker attempts to
emulate the View Engine default mode as accurately as is possible. This
commit addresses a gap in this compatibility that stems from a View Engine
type-checking bug.

Consider two template expressions:

```html
{{ obj?.field }}
{{ fn()?.field }}
```

and suppose that the type of `obj` and `fn()` are the same - both return
either `null` or an object with a `field` property.

Under View Engine, these type-check differently. The `obj` case will catch
if the object type (when not null) does not have a `field` property, while
the `fn()` case will not. This is due to how View Engine represents safe
navigations:

```typescript
// for the 'obj' case
(obj == null ? null as any : obj.field)

// for the 'fn()' case
let tmp: any;
((tmp = fn()) == null ? null as any : tmp.field)
```

Because View Engine uses the same code generation backend as it does to
produce the runtime code for this expression, it uses a ternary for safe
navigation, with a temporary variable to avoid invoking 'fn()' twice. The
type of this temporary variable is 'any', however, which causes the
`tmp.field` check to be meaningless.

Previously, the Ivy template type-checker in compatibility mode assumed that
`fn()?.field` would always check for the presence of 'field' on the non-null
result of `fn()`. This commit emulates the View Engine bug in Ivy's
compatibility mode, so an 'any' type will be inferred under the same
conditions.

As part of this fix, a new format for safe navigation operations in template
type-checking code is introduced. This is based on the realization that
ternary based narrowing is unnecessary.

For the `fn()` case in strict mode, Ivy now generates:

```typescript
(null as any ? fn()!.field : undefined)
```

This effectively uses the ternary operator as a type "or" operation. The
resulting type will be a union of the type of `fn()!.field` with
`undefined`.

For the `fn()` case in compatibility mode, Ivy now emulates the bug with:

```typescript
(fn() as any).field
```

The cast expression includes the call to `fn()` and allows it to be checked
while still returning a type of `any` from the expression.

For the `obj` case in compatibility mode, Ivy now generates:

```typescript
(obj!.field as any)
```

This cast expression still returns `any` for its type, but will check for
the existence of `field` on the type of `obj!`.

PR Close #35462
2020-02-21 12:36:12 -08:00
0700279fb6 fix(language-service): provide hover for interpolation in attribute value (#35494)
I think the bug is introduced in my PR#34847. For example, 'model="{{title}}"', the attribute value cannot be parsed by 'parseTemplateBindings'.

PR Close #35494
2020-02-21 12:35:52 -08:00
a491f7e2af fix(language-service): infer context type of structural directives (#35537) (#35561)
PR Close #35561
2020-02-21 09:11:55 -08:00
af4fe3aa4e fix(ngcc): correctly detect emitted TS helpers in ES5 (#35191)
In ES5 code, TypeScript requires certain helpers (such as
`__spreadArrays()`) to be able to support ES2015+ features. These
helpers can be either imported from `tslib` (by setting the
`importHelpers` TS compiler option to `true`) or emitted inline (by
setting the `importHelpers` and `noEmitHelpers` TS compiler options to
`false`, which is the default value for both).

Ngtsc's `StaticInterpreter` (which is also used during ngcc processing)
is able to statically evaluate some of these helpers (currently
`__assign()`, `__spread()` and `__spreadArrays()`), as long as
`ReflectionHost#getDefinitionOfFunction()` correctly detects the
declaration of the helper. For this to happen, the left-hand side of the
corresponding call expression (i.e. `__spread(...)` or
`tslib.__spread(...)`) must be evaluated as a function declaration for
`getDefinitionOfFunction()` to be called with.

In the case of imported helpers, the `tslib.__someHelper` expression was
resolved to a function declaration of the form
`export declare function __someHelper(...args: any[][]): any[];`, which
allows `getDefinitionOfFunction()` to correctly map it to a TS helper.

In contrast, in the case of emitted helpers (and regardless of the
module format: `CommonJS`, `ESNext`, `UMD`, etc.)), the `__someHelper`
identifier was resolved to a variable declaration of the form
`var __someHelper = (this && this.__someHelper) || function () { ... }`,
which upon further evaluation was categorized as a `DynamicValue`
(prohibiting further evaluation by the `getDefinitionOfFunction()`).

As a result of the above, emitted TypeScript helpers were not evaluated
in ES5 code.

---
This commit changes the detection of TS helpers to leverage the existing
`KnownFn` feature (previously only used for built-in functions).
`Esm5ReflectionHost` is changed to always return `KnownDeclaration`s for
TS helpers, both imported (`getExportsOfModule()`) as well as emitted
(`getDeclarationOfIdentifier()`).

Similar changes are made to `CommonJsReflectionHost` and
`UmdReflectionHost`.

The `KnownDeclaration`s are then mapped to `KnownFn`s in
`StaticInterpreter`, allowing it to statically evaluate call expressions
involving any kind of TS helpers.

Jira issue: https://angular-team.atlassian.net/browse/FW-1689

PR Close #35191
2020-02-21 09:06:47 -08:00
6faaec60b1 refactor(compiler-cli): rename the BuiltinFn type to the more generic KnownFn (#35191)
This is in preparation of using the `KnownFn` type for known TypeScript
helpers (in addition to built-in functions/methods). This will in turn
allow simplifying the detection of both imported and emitted TypeScript
helpers.

PR Close #35191
2020-02-21 09:06:47 -08:00
12e3db8d6f fix(ngcc): handle imports in dts files when processing CommonJS (#35191)
When statically evaluating CommonJS code it is possible to find that we
are looking for the declaration of an identifier that actually came from
a typings file (rather than a CommonJS file).

Previously, the CommonJS reflection host would always try to use a
CommonJS specific algorithm for finding identifier declarations, but
when the id is actually in a typings file this resulted in the returned
declaration being the containing file of the declaration rather than the
declaration itself.

Now the CommonJS reflection host will check to see if the file
containing the identifier is a typings file and use the appropriate
stategy.

(Note: This is the equivalent of #34356 but for CommonJS.)

PR Close #35191
2020-02-21 09:06:47 -08:00
824d9a8cbf build: update cli packages to latest versions (#35608)
PR Close #35608
2020-02-21 08:31:19 -08:00
8a531e2917 fix(ivy): incorrectly generating shared pure function between null and object literal (#35481)
In #33705 we made it so that we generate pure functions for object/array literals in order to avoid having them be shared across elements/views. The problem this introduced is that further down the line the `ContantPool` uses the generated literal in order to figure out whether to share an existing factory or to create a new one. `ConstantPool` determines whether to share a factory by creating a key from the AST node and using it to look it up in the factory cache, however the key generation function didn't handle function invocations and replaced them with `null`. This means that the key for `{foo: pureFunction0(...)}` and `{foo: null}` are the same.

These changes rework the logic so that instead of generating a `null` key
for function invocations, we generate a variable called `<unknown>` which
shouldn't be able to collide with anything.

Fixes #35298.

PR Close #35481
2020-02-20 15:23:59 -08:00
afc5b3eede perf(ivy): remove unused event argument in listener instructions (#35097)
Currently Ivy always generates the `$event` function argument, even if it isn't being used by the listener expressions. This can lead to unnecessary bytes being generated, because optimizers won't remove unused arguments by default. These changes add some logic to avoid adding the argument when it isn't required.

PR Close #35097
2020-02-20 15:22:14 -08:00
7d2ea938ee feat: add an tickOptions parameter with property processNewMacroTasksSynchronously. (#33838)
This option will control whether to invoke the new macro tasks when ticking.

Close #33799

PR Close #33838
2020-02-20 15:15:00 -08:00
d63ba9cfd3 fix(ivy): Add style="{{exp}}" based interpolation (#34202)
Fixes #33575

Add support for interpolation in styles as shown:
```
<div style="color: {{exp1}}; width: {{exp2}};">
```

PR Close #34202
2020-02-20 15:13:11 -08:00
a4b388d4ec docs: clarify getting started deployment guide (#35510)
PR Close #35510
2020-02-20 15:12:30 -08:00
aebd6620d7 fix(ngcc): add default config for angular2-highcharts (#35527)
The package is deprecated (and thus not going to have a new release),
but still has ~7000 weekly downloads.

Fixes #35399

PR Close #35527
2020-02-20 15:12:09 -08:00
39bd9a7c94 fix(ngcc): correctly detect outer aliased class identifiers in ES5 (#35527)
In ES5 and ES2015, class identifiers may have aliases. Previously, the
`NgccReflectionHost`s recognized the following formats:
- ES5:
    ```js
    var MyClass = (function () {
      function InnerClass() {}
      InnerClass_1 = InnerClass;
      ...
    }());
    ```
- ES2015:
    ```js
    let MyClass = MyClass_1 = class MyClass { ... };
    ```

In addition to the above, this commit adds support for recognizing an
alias outside the IIFE in ES5 classes (which was previously not
supported):
```js
var MyClass = MyClass_1 = (function () { ... }());
```

Jira issue: [FW-1869](https://angular-team.atlassian.net/browse/FW-1869)

Partially addresses #35399.

PR Close #35527
2020-02-20 15:12:09 -08:00
4b93df06e0 refactor(ngcc): tighten method parameter type to avoid redundant check (#35527)
`Esm5ReflectionHost#getInnerFunctionDeclarationFromClassDeclaration()`
was already called with `ts.Declaration`, not `ts.Node`, so we can
tighten its parameter type and get rid of a redundant check.
`getIifeBody()` (called inside
`getInnerFunctionDeclarationFromClassDeclaration()`) will check whether
the given `ts.Declaration` is a `ts.VariableDeclaration`.

PR Close #35527
2020-02-20 15:12:08 -08:00
72664cac19 fix(compiler): use FatalDiagnosticError to generate better error messages (#35244)
Prior to this commit, decorator handling logic in Ngtsc used `Error` to throw errors. This commit replaces most of these instances with `FatalDiagnosticError` class, which provider a better diagnostics error (including location of the problematic code).

PR Close #35244
2020-02-20 11:25:24 -08:00
bc7a8a85f2 fix(localize): support minified ES5 $localize calls (#35562)
Some minification tooling modifies `$localize` calls
to contain a comma sequence of items, where the
cooked and raw values are assigned to variables.

This change improves our ability to recognize these
structures.

Fixes #35376

PR Close #35562
2020-02-20 10:55:54 -08:00
375aa7399d docs: add downgraded output kebab-case example (#35581)
PR Close #35581
2020-02-20 10:55:35 -08:00
7dbbe24ccf fix(docs-infra): highlight the currently active node in top-bar (#33351)
Related to #33239 and #33255.

PR Close #33351
2020-02-20 10:52:55 -08:00
677d277ccc fix(docs-infra): use .tooltip in aio-top-menu items (#33351)
The top-menu items have both a `title` and a `tooltip` property. The
`title` is used as text content, so there is little point in using it as
"tooltip" (via the HTMLElement's `title` property) too.

This commit switches to using the `tooltip` property to populate the
`title`. Note that in many cases, the `tooltip` property is derived from
`title` anyway (so there is no practical change in behavior in these
cases).

PR Close #33351
2020-02-20 10:52:54 -08:00
224aaae352 fix(animations): false positive when detecting Node in Webpack builds (#35134)
We have to do some extra work in the animations module when we identify a Node environment which we determine based on the `process` global. The problem is that by default Webpack will polyfill the `process`, causing us to incorrectly identify it. These changes make it so that the check isn't thrown off by Webpack.

Fixes #35117.

PR Close #35134
2020-02-20 10:51:16 -08:00
5cdf806126 docs: edit displaying-data page to introduce section (#35507)
PR Close #35507
2020-02-20 10:50:06 -08:00
3a97972e58 fix(docs-infra): improve focus styles in topnav and footer (#33255)
Fixes #33239

PR Close #33255
2020-02-19 12:51:28 -08:00
f5e1faa75e fix(core): make subclass inherit developer-defined data (#35105)
PR Close #35105
2020-02-19 12:50:49 -08:00
5bec534bfc build: remove dependency on @types/chokidar (#35371)
We recently updated chokidar to `3.0.0`. The latest version of
chokidar provides TypeScript types on its own and makes the extra
dependency on the `@types` unnecessary.

This seems to have caused the `build-packages-dist` script to fail with
an error like:

```
[strictDeps] transitive dependency on external/npm/node_modules/chokidar/types/index.d.ts
   not allowed. Please add the BUILD target to your rule's deps.
```

It's unclear why that happens, but a reasonable theory would be that
the TS compilation accidentally picked up the types from `chokidar`
instead of `@types/chokidar`, and the strict deps `@bazel/typescript`
check reported this as issue because it's not an explicit target dependency.

PR Close #35371
2020-02-19 12:49:53 -08:00
5edeee69dd release: cut the v9.0.2 release 2020-02-19 11:18:40 -08:00
ce85cbf2d3 Revert "feat(ngcc): pause async ngcc processing if another process has the lockfile (#35131)"
This reverts commit b970028057.

This is a feature commit and was improperly merged to the patch branch.
2020-02-19 11:14:31 -08:00
c305b5ca31 ci: increase AIO payload size limit (#35538)
This commit updates AIO payload size limit that is triggering a problem after merging f95b8ce07e. That commit added some payload size, but all checks were "green" for the PR (https://github.com/angular/angular/pull/34481) after rebase that happened a couple hours before the merge, so this is an accumulated payload size increase from multiple changes. The goal of this commit is to bring the master and patch branches back to "green" state.

PR Close #35538
2020-02-19 09:07:21 -08:00
b970028057 feat(ngcc): pause async ngcc processing if another process has the lockfile (#35131)
ngcc uses a lockfile to prevent two ngcc instances from executing at the
same time. Previously, if a lockfile was found the current process would
error and exit.

Now, when in async mode, the current process is able to wait for the previous
process to release the lockfile before continuing itself.

PR Close #35131
2020-02-18 17:20:42 -08:00
e67c69a782 refactor(compiler-cli): add invalidateCaches to CachedFileSystem (#35131)
This is needed by ngcc when reading volatile files that may
be changed by an external process (e.g. the lockfile).

PR Close #35131
2020-02-18 17:20:42 -08:00
03a8b16ec9 fix(ivy): add attributes and classes to host elements based on selector (#34481)
In View Engine, host element of dynamically created component received attributes and classes extracted from component's selector. For example, if component selector is `[attr] .class`, the `attr` attribute and `.class` class will be add to host element. This commit adds similar logic to Ivy, to make sure this behavior is aligned with View Engine.

PR Close #34481
2020-02-18 17:18:13 -08:00
fd4ce84584 fix(ivy): queries should match elements inside ng-container with the descendants: false option (#35384)
Before this change content queries with the `descendants: false` option, as implemented in ivy,
would not descendinto `<ng-container>` elements. This behaviour was different from the way the
View Engine worked. This change alligns ngIvy and VE behaviours when it comes to queries and the
`<ng-container>` elements and fixes a common bugs where a query target was placed inside the
`<ng-container>` element with a * directive on it.

Before:

```html
<needs-target>
  <ng-container *ngIf="condition">
    <div #target>...</div>  <!-- this node would NOT match -->
  </ng-container>
</needs-target>
```

After:

```html
<needs-target>
  <ng-container *ngIf="condition">
    <div #target>...</div>  <!-- this node WILL match -->
  </ng-container>
</needs-target>
```

Fixes #34768

PR Close #35384
2020-02-18 17:17:46 -08:00
0671e540c2 fix(ivy): wrong context passed to ngOnDestroy when resolved multiple times (#35249)
When the same provider is resolved multiple times on the same node, the first invocation had the correct context, but all subsequent ones were incorrect because we were registering the hook multiple times under different indexes in `destroyHooks`.

Fixes #35167.

PR Close #35249
2020-02-18 17:17:06 -08:00
45c7b23cc8 fix(docs-infra): set th/td to proper width (#35437)
Previously, the tables on the event page were misaligned. This commit
fixes this by setting the width of all `td`'s and `th`'s.

PR Close #35437
2020-02-18 12:48:31 -08:00
9b31f77c19 style(docs-infra): properly format files (#35318)
PR Close #35318
2020-02-18 12:45:07 -08:00
927d691d56 fix(docs-infra): preserves query and hash when switching angular versions (#35318)
Previously, when switching angular versions through the
version selector in the sidenav, the query and hash is lost.
The user has to manually navigate to the original location again.

This commit fixes this issue and preserves the query and hash
when navigating between different versions.

Closes #24495

PR Close #35318
2020-02-18 12:45:07 -08:00
4fb5e21426 fix(core): better handing of ICUs outside of i18n blocks (#35347)
Currently the logic that handles ICUs located outside of i18n blocks may throw exceptions at runtime. The problem is caused by the fact that we store incorrect TNode index for previous TNode (index that includes HEADER_OFFSET) and do not store a flag whether this TNode is a parent or a sibling node. As a result, the logic that assembles the final output uses incorrect TNodes and in some cases throws exceptions (when incompatible structure is extracted from tView.data due to the incorrect index). This commit adjusts the index and captures whether TNode is a parent to make sure underlying logic manipulates correct TNode.

PR Close #35347
2020-02-18 12:43:45 -08:00
6518dae45e fix(docs-infra): add fallback to web fonts so downloading does not block rendering (#35352)
Light house was reporting that 'Ensure text remains visible during webfont load' solution to this problem was adding &swap to the end of web fonts this leads to our first text showing before web-font download and improves the performance of site link to article: https://web.dev/font-display/\?utm_source\=lighthouse\&utm_medium\=lr

PR Close #35352
2020-02-18 12:43:17 -08:00
83d68b3521 ci: get rid of the CI_CHROMEDRIVER_VERSION_ARG env var (#35381)
Previously, we needed to manually specify a ChromeDriver version to
download on CI that would be compatible with the browser version
provided by the docker image used to run the tests. This was kept in the
`CI_CHROMEDRIVER_VERSION_ARG` environment variable.

With recent commits, we use the browser provided by `puppeteer` and can
determine the correct ChromeDriver version programmatically. Therefore,
we no longer need the `CI_CHROMEDRIVER_VERSION_ARG` environment
variable.

NOTE:
There is still one place (the `bazel-schematics` integration project)
where a hard-coded ChromeDriver version is necessary. Since I am not
sure what is the best way to refactor the tests to not rely on a
hard-coded version, I left it as a TODO for a follow-up PR.

PR Close #35381
2020-02-18 12:42:49 -08:00
cf28373629 build(docs-infra): use puppeteer to get a browser for docs examples tests (#35381)
In #35049, integration and AIO tests were changed to use the browser
provided by `puppeteer` in tests. This commit switches the docs examples
tests to use the same setup.

IMPLEMENTATION NOTE:
The examples are used to create ZIP archives that docs users can
download to experiment with. Since we want the downloaded projects to
resemble an `@angular/cli` generated project, we do not want to affect
the project's Protractor configuration in order to use `puppeteer`.

To achieve this, a second Protractor configuration is created (which is
ignored when creating the ZIP archives) that extends the original one
and passes the approperiate arguments to use the browser provided by
`puppeteer`. This new configuration (`protractor-puppeteer.conf.js`) is
used when running the docs examples tests (on CI or locally during
development).

PR Close #35381
2020-02-18 12:42:48 -08:00
598b3ff5d7 build: several minor fixes related to using puppeteer (#35381)
This is a follow-up to #35049 with a few minor fixes related to using
the browser provided by `puppeteer` to run tests. Included fixes:

- Make the `webdriver-manager-update.js` really portable. (Previously,
  it needed to be run from the directory that contained the
  `node_modules/` directory. Now, it can be executed from a subdirectory
  and will correctly resolve dependencies.)

- Use the `puppeteer`-based setup in AIO unit and e2e tests to ensure
  that the downloaded ChromeDriver version matches the browser version
  used in tests.

- Use the `puppeteer`-based setup in the `aio_monitoring_stable` CI job
  (as happens with `aio_monitoring_next`).

- Use the [recommended way][1] of getting the browser port when using
  `puppeteer` with `lighthouse` and avoid hard-coding the remote
  debugging port (to be able to handle multiple instances running
  concurrently).

[1]: https://github.com/GoogleChrome/lighthouse/blame/51df179a0/docs/puppeteer.md#L49

PR Close #35381
2020-02-18 12:42:48 -08:00
011937555f docs(upgrade): separate AngularJS Material typings to its own block (#35514)
PR Close #35514
2020-02-18 12:42:20 -08:00
f33d8fe11d docs(upgrade): add instructions for more AngularJS related typings (#35514)
angular-aria is a core AngularJS module packaged separately, and
angular-material is its own thing entirely.

PR Close #35514
2020-02-18 12:42:20 -08:00
c9d80b2fc8 docs(forms): remove outdated ngForm selector deprecation notice (#35435)
In https://github.com/angular/angular/pull/33058, we removed support
for the `ngForm` selector in the NgForm directive. We deleted most
of the deprecation notices in that PR, but we missed a paragraph
of documentation in the API docs for NgForm.

This commit removes the outdated paragraph that makes it seem like
the selector is still around and deprecated (as opposed to removed),
as it might confuse users.

PR Close #35435
2020-02-14 15:34:01 -08:00
81c40cb5e8 build: enable network for docker on remote executors (#35432)
This is being done as a pre-factor for running integration tests
with bazel on RBE.

PR Close #35432
2020-02-14 15:33:38 -08:00
822036362b fix(core): correctly concatenate static and dynamic binding to class when shadowed (#35350)
Given:
```
<div class="s1" [class]="null" [ngClass]="exp">
```
Notice that `[class]` binding is not a `string`. As a result the existing logic would not concatenate `[class]` with `class="s1"`. The resulting falsy value would than be sent to `ngClass` which would promptly clear all styles on the `<div>`

The new logic correctly handles falsy values for `[class]` bindings.

Fix #35335

PR Close #35350
2020-02-14 15:33:15 -08:00
eee8c7f718 docs: change item to items to match the code (#35433)
Closes #35368

PR Close #35433
2020-02-14 11:15:07 -08:00
1797390c8b fix(core): remove support for Map/Set in [class]/[style] bindings (#35392)
Close FW-1863

PR Close #35392
2020-02-14 11:14:44 -08:00
4a4b6be731 ci: update the browser test matrix to match supported browsers (#35202)
Updated to match https://angular.io/guide/browser-support#browser-support

PR Close #35202
2020-02-14 11:14:06 -08:00
4b1dcaf0f5 fix(ivy): LFrame needs to release memory on leaveView() (#35156)
Root cause is that for perf reasons we cache `LFrame` so that we don't have to allocate it all the time. To be extra fast we clear the `LFrame` on `enterView()` rather that on `leaveView()`. The implication of this strategy is that the deepest `LFrame` will retain objects until the `LFrame` allocation depth matches the deepest object.

The fix is to simply clear the `LFrame` on `leaveView()` rather then on `enterView()`

Fix #35148

PR Close #35156
2020-02-14 11:13:37 -08:00
4f8d30361a build: update to bazel_toolchains 2.1.0 (#35430)
Needed with @bazel/bazel 2.1.0 update

PR Close #35430
2020-02-13 16:29:34 -08:00
098ba19560 build: update to @bazel/bazel 2.1.0 (#35430)
Includes new feature to honor .bazelignore in external repositories. rules_nodejs 1.3.0 now generates a .bazelignore for the @npm repository so that Bazel ignores the @npm//:node_modules folder.

PR Close #35430
2020-02-13 16:29:33 -08:00
5149d98acc build: update to rules_nodejs 1.3.0 (#35430)
Brings in feat: builtin: expose @npm//foo__all_files filegroup that includes all files in the npm package (https://github.com/bazelbuild/rules_nodejs/commit/8d77827) that is needed for npm_integration_test @npm//puppeteer pkg_tar on OSX (as the OSX Chrrome libs are extracted to paths that contain spaces)

PR Close #35430
2020-02-13 16:29:33 -08:00
db693f482f docs: Fix minor typos and coding styles (#35325)
- Fix minor typos in the Getting Started, Forms and AOT Compiler guide.
- Fix minor typo in the Tour of Heroes app.
- Fix coding styles in the Getting Started guide and the Tour of Heroes app

PR Close #35325
2020-02-13 13:31:31 -08:00
84c9c6ecc2 docs: minor typo fix (#35423)
PR Close #35423
2020-02-13 10:08:24 -08:00
a52d103341 ci(docs-infra): update payload limits (#35379)
The update to Angular 9.0.0 appears to have lowered the main.js
file slightly, while the current master build of Angular appears
to have gone up slightly.

PR Close #35379
2020-02-13 10:07:58 -08:00
ec77bc4fc5 build(docs-infra): update to latest Angular Material (#35379)
PR Close #35379
2020-02-13 10:07:58 -08:00
1129f10f26 build(docs-infra): pin @webcomponents/custom-elements to 1.2.1 (#35379)
The previous range (^1.2.0) allowed the version 1.3.2 to be
installed which caused the ES2015 polyfills.js file to increase
in size unwantedly.

PR Close #35379
2020-02-13 10:07:57 -08:00
3006a560fd build(docs-infra): update AIO to Angular 9.0.0 (#35379)
PR Close #35379
2020-02-13 10:07:57 -08:00
8e9be6ce0d build(docs-infra): update to latest dgeni-packages (#35379)
After the previous update to yarn.lock a problem surfaced
with the `mkdir-promise` package. The latest version of
dgeni-packages (0.28.3) fixes this problem.

PR Close #35379
2020-02-13 10:07:57 -08:00
99e4daec94 build(docs-infra): refresh yarn.lock (#35379)
This file had not been updated for some time and lots of
the dependencies have new versions.

This is actually necessary because (at least on OS/X) there
is a problem with `chokidar` and `fsevent` that is solved by
bumping the versions here.

PR Close #35379
2020-02-13 10:07:57 -08:00
90c249bc78 docs: Update doc to use ng firebase schematics for deployment (#35355)
Previously, the `deployment` section, was using the `firebase`
CLI to deploy the angular project into firebase. With the better
integration through the `fire` schematics, it is now easier to
deploy angular applications into firebase. This commit takes
care of this, by outlined the required steps for deployment.

Closes #35274

PR Close #35355
2020-02-13 10:07:27 -08:00
83941d68df docs: update release.md and rename 'beta' releases to 'next' (#35276)
also clarify what 'next' releases are.

PR Close #35276
2020-02-13 10:00:52 -08:00
a30fd2993b fix(ivy): error if directive with synthetic property binding is on same node as directive that injects ViewContainerRef (#35343)
In the `loadRenderer` we make an assumption that the value will always be an `LView`, but if there's a directive on the same node which injects `ViewContainerRef` the `LView` will be wrapped in an `LContainer`. These changes add a call to unwrap the value before we try to read the value off of it.

Fixes #35342.

PR Close #35343
2020-02-12 17:14:25 -08:00
a84093a971 docs: remove service from region where it was added before it was created (#35354)
The message service was added in a section create message service but was impoted much before it removed those imports because they can be confusing

Fixes #35259

PR Close #35354
2020-02-12 16:46:23 -08:00
37e1c04e6a ci: use pipeline values to define the CI_COMMIT_RANGE (#35348)
PR Close #35348
2020-02-12 16:40:48 -08:00
985762b5bc docs: Rename FAQ to Useful Tips (#35316)
Previously, a section in the FAQ was not clear when discussing a
simple unit test. We also want to move away from question-based
sections. This commit clarified the confusing section and
changed all question-based sections.

Closes #35056

PR Close #35316
2020-02-12 16:40:18 -08:00
be0f994657 ci: update pullapprove config to ensure complete coverage of files (#35060)
PR Close #35060
2020-02-12 16:39:14 -08:00
6aa259246e ci: add verification of the pullapprove config (#35060)
Verify that all files in the repo are covered by the pullapprove config
and that all rules in the pullapprove config match at least one file
in the repo.

PR Close #35060
2020-02-12 16:39:14 -08:00
ad7850e4b8 ci: reenable draft mode conditioning for pullapprove (#35396)
Previously there was a regression in PullApprove which preventing draft mode
from being respected correctly for PullApprove processing.  This regression
has been remedied and we should be able to once again respect draft mode for
PRs.

PR Close #35396
2020-02-12 16:36:35 -08:00
c3b5ce4bb2 release: cut the v9.0.1 release 2020-02-12 10:35:56 -08:00
554c2cbd5c fix(forms): change Array.reduce usage to Array.forEach (#35349)
There is currently a bug in Chrome 80 that makes Array.reduce
not work according to spec. The functionality in forms that
retrieves controls from FormGroups and FormArrays (`form.get`)
relied on Array.reduce, so the Chrome bug broke forms for
many users.

This commit refactors our forms code to rely on Array.forEach
instead of Array.reduce to fix forms while we are waiting
for the Chrome fix to go live.

See https://bugs.chromium.org/p/chromium/issues/detail?id=1049982.

PR Close #35349
2020-02-11 17:02:53 -08:00
a245e9d0a3 refactor(ivy): compute ignoreFiles for compilation on initialization (#34792) (#35346)
This commit moves the calculation of `ignoreFiles` - the set of files to be
ignored by a consumer of the `NgCompiler` API - from its `prepareEmit`
operation to its initialization. It's now available as a field on
`NgCompiler`.

This will allow a consumer to skip gathering diagnostics for `ignoreFiles`
as well as skip emit.

PR Close #34792

PR Close #35346
2020-02-11 13:31:22 -08:00
e19eebcba1 docs: Repetition on getting started tutorial (#35290)
Fixes #35286
PR Close #35290
2020-02-11 13:20:17 -08:00
fe42930ddd test: use puppeteer in aio build instead to remove CI_CHROMEDRIVER_VERSION_ARG (#35049)
PR Close #35049
2020-02-11 13:16:54 -08:00
c99165f789 build: update lock files in other integration tests (#35049)
PR Close #35049
2020-02-11 13:16:54 -08:00
cd2ffea668 test: use puppeteer in integration tests and to download correct chromedriver (#35049)
This means integration tests no longer need to depend on a $CI_CHROMEDRIVER_VERSION_ARG environment variable to specify which chromedriver version to download to match the locally installed chrome. This was bad DX and not having it specified was not reliable as webdriver-manager would not always download the chromedriver version to work with the locally installed chrome.

webdriver-manager update --gecko=false --standalone=false $CI_CHROMEDRIVER_VERSION_ARG is now replaced with node webdriver-manager-update.js in the root package.json, which checks which version of chrome puppeteer has come bundled with & downloads informs webdriver-manager to download the corresponding chrome driver version.

Integration tests now use "webdriver-manager": "file:../../node_modules/webdriver-manager" so they don't have to waste time calling webdriver-manager update in postinstall

"// resolutions": "Ensure a single version of webdriver-manager which comes from root node_modules that has already run webdriver-manager update",
"resolutions": {
"**/webdriver-manager": "file:../../node_modules/webdriver-manager"
}
This should speed up each integration postinstall by a few seconds.

Further, integration test package.json files link puppeteer via file:../../node_modules/puppeteer which is the ideal situation as the puppeteer post-install won't download chrome if it is already downloaded. In CI, since node_modules is cached it should not need to download Chrome either unless the node_modules cache is busted.

NB: each version of puppeteer comes bundles with a specific version of chrome. Root package.json & yarn.lock currently pull down puppeteer 2.1.0 which comes with chrome 80. See https://github.com/puppeteer/puppeteer#q-which-chromium-version-does-puppeteer-use for more info.

Only two references to CI_CHROMEDRIVER_VERSION_ARG left in integration tests at integration/bazel-schematics/test.sh which I'm not entirely sure how to get rid of it

Use a lightweight puppeteer=>chrome version mapping instead of launching chrome and calling browser.version()

Launching puppeteer headless chrome and calling browser.version() was a heavy-handed approach to determine the Chrome version. A small and easy to update mappings file is a better solution and it means that the `yarn install` step does not require chrome shared libs available on the system for its postinstall step

PR Close #35049
2020-02-11 13:16:54 -08:00
94d002b64e fix(elements): schematics fails with schema.json not found error (#35211)
Fixes #35154

PR Close #35211
2020-02-11 11:42:52 -08:00
3cc24a9ac4 fix(language-service): Suggest ? and ! operator on nullable receiver (#35200)
Under strict mode, the language service fails to typecheck nullable
symbols that have already been verified to be non-null.

This generates incorrect (false positive) and confusing diagnostics
for users.

To work around this issue in the short term, this commit changes the
diagnostic message from an error to a suggestion, and prompts users to
use the safe navigation operator (?) or non-null assertion operator (!).

For example, instead of

```typescript
{{ optional && optional.toString() }}
```

the following is cleaner:

```typescript
{{ optional?.toString() }}
{{ optional!.toString() }}
```

Note that with this change, users who legitimately make a typo in their
code will no longer see an error. I think this is acceptable, since
false positive is worse than false negative. However, if users follow
the suggestion, add ? or ! to their code, then the error will be surfaced.
This seems a reasonable trade-off.

References:

1. Safe navigation operator (?)
   https://angular.io/guide/template-syntax#the-safe-navigation-operator----and-null-property-paths
2. Non-null assertion operator (!)
   https://angular.io/guide/template-syntax#the-non-null-assertion-operator---

PR closes https://github.com/angular/angular/pull/35070
PR closes https://github.com/angular/vscode-ng-language-service/issues/589

PR Close #35200
2020-02-10 16:43:46 -08:00
d13cab77fc fix(compiler): report errors for missing binding names (#34595)
Currently, would-be binding attributes that are missing binding names
are not parsed as bindings, and fall through as regular attributes. In
some cases, this can lead to a runtime error; trying to assign `#` as a
DOM attribute in an element like in `<div #></div>` fails because `#` is
not a valid attribute name.

Attributes composed of binding prefixes but not defining a binding
should be considered invalid, as this almost certainly indicates an
unintentional elision of a binding by the developer. This commit
introduces error reporting for attributes with a binding name prefix but
no actual binding name.

Closes https://github.com/angular/vscode-ng-language-service/issues/293.

PR Close #34595
2020-02-10 16:29:33 -08:00
91a2fd5c33 test(ngcc): add missing UmdReflectionHost#getExportsOfModule() tests (#35312)
Support for re-exports in UMD were added in e9fb5fdb8. This commit adds
some tests for re-exports (similar to the ones used for
`CommonJsReflectionHost`).

PR Close #35312
2020-02-10 16:13:42 -08:00
9251519a0e docs: fix nav to match new toh titles (#35126)
PR Close #35126
2020-02-10 16:12:55 -08:00
baf77e4adf docs: added description for novalidate form attribute. (#35166)
PR Close #35166
2020-02-10 16:11:58 -08:00
d9fcfd3b24 docs(forms): update the ngForm deprecation notice (#35263)
we should be documenting when an API is eligible for removal and not when it will be removed.

The actual removal depends on many factors, e.g. if we were able to automate the refactoring to
the recommended API in time or not.

PR Close #35263
2020-02-10 10:49:01 -08:00
bfcf6d09e1 fix(docs-infra): lighthouse reporting links to cross-origin destinations are unsafe (#35253)
Light house was reporting in best practices that our cross origin links are a unsafe so aded rel=noopener according to light houe suggestion link to the article https://web.dev/external-anchors-use-rel-noopener/\?utm_source\=lighthouse\&utm_medium\=lr

PR Close #35253
2020-02-10 09:23:31 -08:00
9f03a85694 ci: re-enable disabled components-repo-unit-tests job (#35123)
We temporarily disabled the components-repo-unit-tests job as part of
a ngcc PR: #35079. This was necessary because the components repository
used postinstall patches for `@angular/compiler-cli/ngcc`. Due to
changes in ngcc, these patches no longer worked and caused the
`components-repo-unit-tests` job to fail.

The postinstall patch has been removed in the components repo, so the
job can be re-enabled.

PR Close #35123
2020-02-10 09:22:56 -08:00
6d39a4a031 ci: update components-repo-unit-tests job commit (#35123)
Updates the commit the `components-repo-unit-tests` job runs against.
We need at least 2ec7254f88
which fixes a Ngcc postinstall patch conflict that required us to
temporarily disable the job in #35079.

PR Close #35123
2020-02-10 09:22:56 -08:00
480a4c3061 fix(ivy): set namespace for host elements of dynamically created components (#35136)
Prior to this change, element namespace was not set for host elements of dynamically created components that resulted in incorrect rendering in a browser. This commit adds the logic to pick and set correct namespace for host element when component is created dynamically.

PR Close #35136
2020-02-07 17:22:54 -08:00
18ed9dcd83 refactor(benchpress): delete outdated/unused folder (#35147)
PR Close #35147
2020-02-07 16:14:28 -08:00
411d4ad79a refactor(benchpress): added tsconfig to ts_library rules and awaited floating promises (#35147)
* Note: we specify our own tsconfig bc the default tsconfig we provide for ts_library disables the must-use-promises rule

PR Close #35147
2020-02-07 16:14:28 -08:00
b285630767 refactor(benchpress): linted (#35147)
PR Close #35147
2020-02-07 16:14:28 -08:00
32d103816e refactor(benchpress): made all it callbacks async (#35147)
PR Close #35147
2020-02-07 16:14:27 -08:00
5b5dc811c1 docs: add asset info to library guide (#34217)
PR Close #34217
2020-02-07 13:57:18 -08:00
dea1b962c7 fix(ivy): repeat template guards to narrow types in event handlers (#35193)
In Ivy's template type checker, event bindings are checked in a closure
to allow for accurate type inference of the `$event` parameter. Because
of the closure, any narrowing effects of template guards will no longer
be in effect when checking the event binding, as TypeScript assumes that
the guard outside of the closure may no longer be true once the closure
is invoked. For more information on TypeScript's Control Flow Analysis,
please refer to https://github.com/microsoft/TypeScript/issues/9998.

In Angular templates, it is known that an event binding can only be
executed when the view it occurs in is currently rendered, hence the
corresponding template guard is known to hold during the invocation of
an event handler closure. As such, it is desirable that any narrowing
effects from template guards are still in effect within the event
handler closure.

This commit tweaks the generated Type-Check Block (TCB) to repeat all
template guards within an event handler closure. This achieves the
narrowing effect of the guards even within the closure.

Fixes #35073

PR Close #35193
2020-02-07 13:06:01 -08:00
dce230eb00 docs: fix awkard space due to margin in sections with alert class (#35113)
PR Close #35113
2020-02-07 11:36:59 -08:00
672abb5871 build: remove the exit 0 on components-unit-tests (#35090)
PR Close #35090
2020-02-07 11:34:21 -08:00
b582bc26d7 docs: missing item variable in structural directives example (#35213)
PR Close #34762
PR Close #35213
2020-02-07 11:32:38 -08:00
c3c11403c0 fix(ngcc): ensure that path-mapped secondary entry-points are processed correctly (#35227)
The `TargetedEntryPointFinder` must work out what the
containing package is for each entry-point that it finds.

The logic for doing this was flawed in the case that the
package was in a path-mapped directory and not in a
node_modules folder. This meant that secondary entry-points
were incorrectly setting their own path as the package
path, rather than the primary entry-point path.

Fixes #35188

PR Close #35227
2020-02-07 11:32:05 -08:00
24ffe3745b docs(changelog): formatting fix (#35224)
PR Close #35224
2020-02-07 09:59:37 -08:00
dfa8356dc4 docs: improve description of providedIn any (#35192)
PR Close #35192
2020-02-07 09:59:11 -08:00
b6a3a739bf fix(ivy): ensure module imports are instantiated before the module being declared (#35172)
PR Close #35172
2020-02-07 09:58:50 -08:00
da85e733d7 fix(docs-infra): fix parameters with @Optional() decorator do not match declared, optional type (#35150)
PR Close #35150
2020-02-07 09:58:32 -08:00
f3f4195ec9 docs: Minor updates to Updating to Angular version 9 topic (#35135)
PR Close #35135
2020-02-07 09:57:57 -08:00
55cc2040d1 docs: fix typo in glossary (#35108)
PR Close #35108
2020-02-07 09:57:26 -08:00
8e3c0d6639 docs(ivy): add anchor-node insert before/after difference (#35207)
PR Close #35207
2020-02-07 09:56:38 -08:00
14fc1812f3 ci: re-enable android 7 saucelabs tests (#35171)
We fixed the tunnel connectivity issues by using a localhost domain
alias. Hence we can re-enable the Android 7.1 Saucelabs tests.

PR Close #35171
2020-02-06 15:36:28 -08:00
7c1fd91b8f ci: ensure saucelabs browsers can load karma test page (#35171)
In the past we had connecitivity issues on Saucelabs. Browsers on
mobile devices were not able to properly resolve the `localhost`
hostname through the tunnel. This is because the device resolves
`localhost` or `127.0.0.1` to the actual Saucelabs device, while it
should resolve to the tunnel host machine (in our case the CircleCI VM).

In the past, we simply disabled the failing devices and re-enabled the
devices later. At this point, the Saucelabs team claimed that the
connecitivy/proxy issues were fixed.

Saucelabs seems to have a process for VMs which ensures that requests to
`localhost` / `127.0.0.1` are properly resolved through the tunnel. This
process is not very reliable and can cause tests to fail. Related issues have been
observed/mentioned in the Saucelabs support docs. e.g.

https://support.saucelabs.com/hc/en-us/articles/115002212447-Unable-to-Reach-Application-on-localhost-for-Tests-Run-on-Safari-8-and-9-and-Edge
https://support.saucelabs.com/hc/en-us/articles/225106887-Safari-and-Internet-Explorer-Won-t-Load-Website-When-Using-Sauce-Connect-on-Localhost

In order to ensure that requests are always resolved through the tunnel,
we add our own domain alias in the CircleCI's hosts file, and enforce that
it is always resolved through the tunnel (using the `--tunnel-domains` SC flag).
Saucelabs devices by default will never resolve this domain/hostname to the
actual local Saucelabs device.

PR Close #35171
2020-02-06 15:36:28 -08:00
931338e9d8 docs: fix wrong link of tick() (#35168)
PR Close #35168
2020-02-06 15:35:51 -08:00
829f506732 fix(bazel): spawn prod server using port 4200 (#35160)
Currently the prod server uses a default port of 8080, with this change we align the port with the devserver.

PR Close #35160
2020-02-06 15:35:12 -08:00
727f92f75d fix(bazel): devserver shows blank page in Windows (#35159)
`additional_root_paths` should contain the workspace name see: d4200191c5/packages/typescript/src/internal/devserver/ts_devserver.bzl (L137-L140)

Fixes #35144

PR Close #35159
2020-02-06 15:34:31 -08:00
4e6d237e54 fix(bazel): update ibazel to 0.11.1 (#35158)
PR Close #35158
2020-02-06 15:33:27 -08:00
0599d6f7bc ci: remove components-repo-ci blocklist (#35115)
Previously we needed the `components-repo-ci` blocklist to disable
tests that were failing during the development of Ivy. Since we fixed
all those failing tests, and we don't want to regress, we can remove the
blocklist logic.

Resolves FW-1807

PR Close #35115
2020-02-06 15:32:34 -08:00
b81631e737 docs: Clarifies code section is a continuation from the section above (#35111)
PR Close #35111
2020-02-06 15:31:43 -08:00
acf8d49829 ci: Remove old vendoring solution in favor of relying on yarn-path (#35083)
Now that bazel respects the yarn-path value found in .yarnrc, we can
remove the last remaining reliances on our vendoring in
//third_party/github.com/yarnpkg/yarn/

PR Close #35083
2020-02-06 15:30:52 -08:00
60b887090c docs: consilidate release notes for the v8.0.0 release (#35197)
PR Close #35197
2020-02-06 14:58:11 -08:00
bcb539f6de docs: remove the release schedule from docs (#34474)
Removing for now, since the info is stale, and we need to determine how to adjust the schedule due to the unexpected and significant version 9 delay.

PR Close #34474
2020-02-06 14:29:21 -08:00
20237d2f1d feat(docs-infra): add v8 to the version picker in the navbar (#35196)
The v8.angular.io should be ready shortly.

PR Close #35196
2020-02-06 14:28:09 -08:00
f4b9d664f2 docs(ivy): add a not about compile-time constants to the ivy compatibility guide (#35194)
PR Close #35194
2020-02-06 13:53:50 -08:00
dd01329408 docs: consolidate and remove rc/next notes from the v9.0.0 release (#35195)
PR Close #35195
2020-02-06 13:46:17 -08:00
becab76c4a build: update scripts/release/post-check with the latest versions (#35151)
these files are used as a post-release smoke tests and haven't been updated to reflect recent depedency changes
and package additions.

PR Close #35151
2020-02-06 09:37:27 -08:00
bdda57c23c docs(ivy): add size debugging section (#35178)
PR Close #35178
2020-02-06 09:34:37 -08:00
1da1c3ca4d docs(ivy): add docs for styling priority order (#35066)
PR Close #35066
2020-02-06 09:33:30 -08:00
933bf53803 docs(ivy): update style binding docs to v9 behavior (#35066)
PR Close #35066
2020-02-06 09:33:30 -08:00
41f7db792f docs(ivy): clean up class binding docs and update to v9 behavior (#35066)
PR Close #35066
2020-02-06 09:33:29 -08:00
b72fce8acf release: cut the v9.0.0 release 2020-02-06 08:50:04 -08:00
483ba6aef7 docs(ivy): document breaking change with host attribute priority (#35175)
PR Close #35175
2020-02-05 18:22:17 -08:00
24555dbb2d build: update @angular/cli to rc 14 (#35162)
PR Close #35162
2020-02-05 17:20:31 -08:00
7de87728e2 ci: temporary disable the Android 7 SauceLab due to timeout (#35174)
PR Close #35174
2020-02-05 16:53:19 -08:00
cf3071f16a fix(ivy): template type-check errors from TS should not use NG error codes (#35146)
A bug previously caused the template type-checking diagnostics produced by
TypeScript for template expressions to use -99-prefixed error codes. These
codes are converted to "NG" errors instead of "TS" errors during diagnostic
printing. This commit fixes the issue.

PR Close #35146
2020-02-04 15:59:02 -08:00
cf1fa6039c docs: fix typo in router animation (#35100)
`output directive` should be written: `outlet directive`

PR Close #35100
2020-02-04 15:58:27 -08:00
eefafbd65a fix(docs-infra): fix CSS issues on home page and search results (#35098)
On home page, image size set to 400px, which make the page not render
properly on devices below the size of 400px width.

Also, when search results were scrolled, they interfered with the top
nav items. Added border at the top of the search results container so
that the results are not visible under the nav items during scrolling.

PR Close #35098
2020-02-04 15:58:00 -08:00
67b3c969c9 fix(docs-infra): size footer links to appropriate size for SEO (#35098)
Footer links did not have enough space between them, so lighthouse was
reporting that tap targets are not appropriately sized. Added the
required 8px space between links.

Also updated the margin of group headers accordingly.

Fixes #34901

PR Close #35098
2020-02-04 15:57:59 -08:00
d5eada64fc docs(animations): increase wait time for status-slider animation (#35089)
Because the animation completes in 2000ms, and browser.wait checks
every 100ms, there can be a race condition of if the final state has
actually been reached to read the color. By moving to 2101ms, we ensure
that we cheack after the 2000ms of the animation has completed.

PR Close #35089
2020-02-04 15:57:38 -08:00
a06a5741c5 feat(docs-infra): add stable to the list of api statuses (#34981)
Earlier api can be filtered based on security risk and deprecated now added stable as a status for better user experience

Fixes #30396

PR Close #34981
2020-02-04 15:57:15 -08:00
8e3d2460d5 refactor(ivy): Explicitly pass in TView (#35069)
- Adds `TView` into `LFrame`, read the `TView` from `LView` on `enterView`.
- Before this change the `TView` was ofter looked up from `LView` as `lView[TVIEW]`. This is suboptimal since reading from an Array, requires that the read checks array size before the read. This means that such a read has a much higher cost than reading from the property directly. By passing in the `TView` explicitly it makes the code more explicit and faster.
- Some rearrangements of arguments so that `TView` would come before `LView` for consistency.

PR Close #35069
2020-02-04 12:56:48 -08:00
6e595d92d8 test(ivy): fix broken tests (#35069)
PR Close #35069
2020-02-04 12:56:48 -08:00
1a23c79835 docs: changes AoT to AOT for consistency (#35112)
PR Close #35112
2020-02-04 10:43:34 -08:00
63868df49d fix(benchpress): formatted spec files (#35127)
PR Close #35127
2020-02-04 10:41:07 -08:00
ca95af10c6 refactor(benchpress): added tsconfig and fixed ts errors (#35127)
PR Close #35127
2020-02-04 10:41:07 -08:00
ad9ec5204c fix(ivy): support emitting a reference to interface declarations (#34849)
In #34021 the ngtsc compiler gained the ability to emit type parameter
constraints, which would generate imports for any type reference that
is used within the constraint. However, the `AbsoluteModuleStrategy`
reference emitter strategy did not consider interface declarations as a
valid declaration it can generate an import for, throwing an error
instead.

This commit fixes the issue by including interface declarations in the
logic that determines whether something is a declaration.

Fixes #34837

PR Close #34849
2020-02-04 10:40:46 -08:00
a5c9cd7e52 fix(ivy): recompile on template change in ngc watch mode on Windows (#34015)
In #33551, a bug in `ngc --watch` mode was fixed so that a component is
recompiled when its template file is changed. Due to insufficient
normalization of files paths, this fix did not have the desired effect
on Windows.

Fixes #32869

PR Close #34015
2020-02-04 10:40:23 -08:00
110289276c ci: properly validate commit messages locally (#35035)
PR Close #35035
2020-02-04 10:27:48 -08:00
3f7be7d608 ci: only lint commit messages in the PR (#35035)
PR Close #35035
2020-02-04 10:27:44 -08:00
f83be86f9d ci: move determineTargetRefAndSha to a new file for reusability (#35035)
PR Close #35035
2020-02-04 10:25:02 -08:00
537562ea19 ci: only lint commit messages on PRs (#35035)
As all commit messages are linted during the PR process, we
do not need to relint these previous commit messages on upstream
branches.

PR Close #35035
2020-02-04 10:25:02 -08:00
7dac29abd0 docs: update typescript version reference (#35120)
PR Close #35120
2020-02-04 10:22:48 -08:00
a320dc90f5 docs: fix animations example/remove 1st person (#35046)
Fixes #34940 and removes first person from transitions-triggers.md

PR Close #35046
2020-02-04 08:58:05 -08:00
7a09530d7f docs: restructure nav for beginner concepts (#34681)
PR Close #34681
2020-02-04 08:57:32 -08:00
152eec5543 release: cut the v9.0.0-rc.14 release 2020-02-03 15:06:16 -08:00
22357d4796 fix(ngcc): correctly invalidate cache when moving/removing files/directories (#35106)
One particular scenario where this was causing problems was when the
[BackupFileCleaner][1] restored a file (such as a `.d.ts` file) by
[moving the backup file][2] to its original location, but the modified
content was kept in the cache.

[1]: https://github.com/angular/angular/blob/4d36b2f6e/packages/compiler-cli/ngcc/src/writing/cleaning/cleaning_strategies.ts#L54
[2]: https://github.com/angular/angular/blob/4d36b2f6e/packages/compiler-cli/ngcc/src/writing/cleaning/cleaning_strategies.ts#L61

Fixes #35095

PR Close #35106
2020-02-03 14:25:47 -08:00
122b042f4d docs: update zone-bluebird patch document for angular (#34536)
PR Close #34536
2020-02-03 14:05:23 -08:00
c2ef5ac329 refactor(ngcc): remove unused function (#35122)
Since #35057, the `markNonAngularPackageAsProcessed()` function is no
longer used and can be removed.

PR Close #35122
2020-02-03 14:05:00 -08:00
31e9873373 fix(ivy): host-styling throws assert exception inside *ngFor (#35133)
Inside `*ngFor` the second run of the styling instructions can get into situation where it tries to read a value from a binding which has not yet executed. As a result the read is `NO_CHANGE` value and subsequent property read cause an exception as it is of wrong type.

Fix #35118

PR Close #35133
2020-02-03 14:03:41 -08:00
6a771d9659 refactor(language-service): dedupe diagnostics using ts utility function (#35086)
This commit makes a minor refactoring that replaces `uniqueBySpan` with
`ts.sortAndDeduplicateDiagnostics()`.

PR Close #35086
2020-02-03 08:57:59 -08:00
60823ae135 refactor(language-service): Replace TypeDiagnostic with ng.Diagnostic (#35085)
This commit cleans up `expression_type.ts` by

1. Removing the unnecessary `TypeDiagnostic` class. It's replaced by
`ng.Diagnostic`.
2. Consolidating `reportError()` and `reportWarning()` to
`reportDiagnostic()`.

This is prep work so that we could make some of the type diagnostics a
suggestion in later PRs.

PR Close #35085
2020-02-03 08:57:18 -08:00
54b5ec496e refactor(ivy): Remove TNode.directives in favor of TData (#35050)
`TNode.directives` was introduced in https://github.com/angular/angular/pull/34938. Turns out that it is unnecessary because the information is already present it `TData` when combining with `TNode.directiveStart` and `TNode.directiveEnd`

Mainly this is true (conceptually):
```
expect(tNode.directives).toEqual(
    tData.slice(
        tNode.directivesStart,
        tNode.directivesEnd - tNode.DirectivesStart -1
    )
);
```

The refactoring removes `TNode.directives` and adds `TNode.directiveStyling` as we still need to keep location in the directive in `TNode`

PR Close #35050
2020-02-03 08:56:52 -08:00
cac2d102a1 test(ivy): correct var count in perf benchmarks. (#35071)
These tests are used for perf testing and don't run as part of CI, as a result they bit-rotted. This fixes that. Long term these tests should be run as part of CI.

PR Close #35071
2020-02-03 08:48:41 -08:00
c30c518898 fix(ngcc): do not lock if the target is not compiled by Angular (#35057)
To support parallel CLI builds we instruct developers to pre-process
their node_modules via ngcc at the command line.

Despite doing this ngcc was still trying to set a lock when it was being
triggered by the CLI for packages that are not going to be processed,
since they are not compiled by Angular for instance.

This commit checks whether a target package needs to be compiled
at all before attempting to set the lock.

Fixes #35000

PR Close #35057
2020-02-03 08:46:44 -08:00
d21b7a458c feat: performance improvement for eventListeners (#34613)
PR Close #34613
2020-02-03 08:40:50 -08:00
563 changed files with 43013 additions and 178763 deletions

View File

@ -1,10 +1,97 @@
# Bazel does not yet support wildcards or other .gitignore semantics for
# .bazelignore. Two issues for this feature request are outstanding:
# https://github.com/bazelbuild/bazel/issues/7093
# https://github.com/bazelbuild/bazel/issues/8106
.git
node_modules
dist
aio/content
aio/node_modules
aio/tools/examples/shared/node_modules
integration/bazel
integration/bazel-schematics/demo
integration/platform-server/node_modules
packages/bazel/node_modules
integration/bazel/bazel-bazel
integration/bazel/bazel-bin
integration/bazel/bazel-out
integration/bazel/bazel-testlogs
integration/bazel-schematics/demo
# All integration test node_modules folders
integration/bazel/node_modules
integration/bazel-schematics/node_modules
integration/cli-hello-world/node_modules
integration/cli-hello-world-ivy-compat/node_modules
integration/cli-hello-world-ivy-i18n/node_modules
integration/cli-hello-world-ivy-minimal/node_modules
integration/cli-hello-world-lazy/node_modules
integration/cli-hello-world-lazy-rollup/node_modules
integration/dynamic-compiler/node_modules
integration/hello_world__closure/node_modules
integration/hello_world__systemjs_umd/node_modules
integration/i18n/node_modules
integration/injectable-def/node_modules
integration/ivy-i18n/node_modules
integration/language_service_plugin/node_modules
integration/ng_elements/node_modules
integration/ng_elements_schematics/node_modules
integration/ng_update/node_modules
integration/ng_update_migrations/node_modules
integration/ngcc/node_modules
integration/platform-server/node_modules
integration/service-worker-schema/node_modules
integration/side-effects/node_modules
integration/terser/node_modules
integration/typings_test_ts36/node_modules
integration/typings_test_ts37/node_modules
# All integration test .yarn_local_cache folders
integration/bazel/.yarn_local_cache
integration/bazel-schematics/.yarn_local_cache
integration/cli-hello-world/.yarn_local_cache
integration/cli-hello-world-ivy-compat/.yarn_local_cache
integration/cli-hello-world-ivy-i18n/.yarn_local_cache
integration/cli-hello-world-ivy-minimal/.yarn_local_cache
integration/cli-hello-world-lazy/.yarn_local_cache
integration/cli-hello-world-lazy-rollup/.yarn_local_cache
integration/dynamic-compiler/.yarn_local_cache
integration/hello_world__closure/.yarn_local_cache
integration/hello_world__systemjs_umd/.yarn_local_cache
integration/i18n/.yarn_local_cache
integration/injectable-def/.yarn_local_cache
integration/ivy-i18n/.yarn_local_cache
integration/language_service_plugin/.yarn_local_cache
integration/ng_elements/.yarn_local_cache
integration/ng_elements_schematics/.yarn_local_cache
integration/ng_update/.yarn_local_cache
integration/ng_update_migrations/.yarn_local_cache
integration/ngcc/.yarn_local_cache
integration/platform-server/.yarn_local_cache
integration/service-worker-schema/.yarn_local_cache
integration/side-effects/.yarn_local_cache
integration/terser/.yarn_local_cache
integration/typings_test_ts36/.yarn_local_cache
integration/typings_test_ts37/.yarn_local_cache
# All integration test NPM_PACKAGE_MANIFEST.json folders
integration/bazel/NPM_PACKAGE_MANIFEST.json
integration/bazel-schematics/NPM_PACKAGE_MANIFEST.json
integration/cli-hello-world/NPM_PACKAGE_MANIFEST.json
integration/cli-hello-world-ivy-compat/NPM_PACKAGE_MANIFEST.json
integration/cli-hello-world-ivy-i18n/NPM_PACKAGE_MANIFEST.json
integration/cli-hello-world-ivy-minimal/NPM_PACKAGE_MANIFEST.json
integration/cli-hello-world-lazy/NPM_PACKAGE_MANIFEST.json
integration/cli-hello-world-lazy-rollup/NPM_PACKAGE_MANIFEST.json
integration/dynamic-compiler/NPM_PACKAGE_MANIFEST.json
integration/hello_world__closure/NPM_PACKAGE_MANIFEST.json
integration/hello_world__systemjs_umd/NPM_PACKAGE_MANIFEST.json
integration/i18n/NPM_PACKAGE_MANIFEST.json
integration/injectable-def/NPM_PACKAGE_MANIFEST.json
integration/ivy-i18n/NPM_PACKAGE_MANIFEST.json
integration/language_service_plugin/NPM_PACKAGE_MANIFEST.json
integration/ng_elements/NPM_PACKAGE_MANIFEST.json
integration/ng_elements_schematics/NPM_PACKAGE_MANIFEST.json
integration/ng_update/NPM_PACKAGE_MANIFEST.json
integration/ng_update_migrations/NPM_PACKAGE_MANIFEST.json
integration/ngcc/NPM_PACKAGE_MANIFEST.json
integration/platform-server/NPM_PACKAGE_MANIFEST.json
integration/service-worker-schema/NPM_PACKAGE_MANIFEST.json
integration/side-effects/NPM_PACKAGE_MANIFEST.json
integration/terser/NPM_PACKAGE_MANIFEST.json
integration/typings_test_ts36/NPM_PACKAGE_MANIFEST.json
integration/typings_test_ts37/NPM_PACKAGE_MANIFEST.json

View File

@ -62,6 +62,16 @@ test --test_output=errors
# Bazel flags for CircleCI are in /.circleci/bazel.linux.rc and /.circleci/bazel.windows.rc
##################################
# Settings for integration tests #
##################################
# Trick bazel into treating BUILD files under integration/bazel as being regular files
# This lets us glob() up all the files inside this integration test to make them inputs to tests
# (Note, we cannot use common --deleted_packages because the bazel version command doesn't support it)
build --deleted_packages=integration/bazel,integration/bazel/src,integration/bazel/src/hello-world,integration/bazel/test,integration/bazel/test/e2e
query --deleted_packages=integration/bazel,integration/bazel/src,integration/bazel/src/hello-world,integration/bazel/test,integration/bazel/test/e2e
################################
# Temporary Settings for Ivy #
################################
@ -100,7 +110,6 @@ build:remote --javabase=@rbe_ubuntu1604_angular//java:jdk
build:remote --host_java_toolchain=@bazel_tools//tools/jdk:toolchain_hostjdk8
build:remote --java_toolchain=@bazel_tools//tools/jdk:toolchain_hostjdk8
build:remote --crosstool_top=@rbe_ubuntu1604_angular//cc:toolchain
build:remote --action_env=BAZEL_DO_NOT_DETECT_CPP_TOOLCHAIN=1
build:remote --extra_toolchains=@rbe_ubuntu1604_angular//config:cc-toolchain
build:remote --extra_execution_platforms=//tools:rbe_ubuntu1604-angular
build:remote --host_platform=//tools:rbe_ubuntu1604-angular

View File

@ -29,7 +29,7 @@ var_4_win: &cache_key_win_fallback v5-angular-win-node-12-
# Cache key for the `components-repo-unit-tests` job. **Note** when updating the SHA in the
# cache keys also update the SHA for the "COMPONENTS_REPO_COMMIT" environment variable.
var_5: &components_repo_unit_tests_cache_key v5-angular-components-97a7e2babbccd3dc58e7b3364004e45ed5bd9968
var_5: &components_repo_unit_tests_cache_key v5-angular-components-2ec7254f88c4865e0de251f74c27e64c9d00d40a
var_6: &components_repo_unit_tests_cache_key_fallback v5-angular-components-
# Workspace initially persisted by the `setup` job, and then enhanced by `build-npm-packages` and
@ -65,8 +65,8 @@ var_10: &only_on_master
# (Using the tag in not necessary when pinning by ID, but include it anyway for documentation purposes.)
# **NOTE 2**: If you change the version of the docker images, also change the `cache_key` suffix.
# **NOTE 3**: If you change the version of the `*-browsers` docker image, make sure the
# `CI_CHROMEDRIVER_VERSION_ARG` env var (in `.circleci/env.sh`) points to a ChromeDriver
# version that is compatible with the Chrome version in the image.
# `--versions.chrome` arg in `integration/bazel-schematics/test.sh` specifies a
# ChromeDriver version that is compatible with the Chrome version in the image.
executors:
default-executor:
parameters:
@ -78,20 +78,6 @@ executors:
resource_class: << parameters.resource_class >>
working_directory: ~/ng
browsers-executor:
parameters:
resource_class:
type: string
default: medium
docker:
# The browser docker image comes with Chrome and Firefox preinstalled. This is just
# needed for jobs that run tests without Bazel. Bazel runs tests with browsers that will be
# fetched by the Webtesting rules. Therefore for jobs that run tests with Bazel, we don't need a
# docker image with browsers pre-installed.
- image: circleci/node:12.14.1-browsers@sha256:792797ab9be3179be7c9fc38a0931a3349288e699467c8d646d7c54e148ae46c
resource_class: << parameters.resource_class >>
working_directory: ~/ng
windows-executor:
working_directory: ~/ng
resource_class: windows.medium
@ -120,25 +106,45 @@ commands:
- attach_workspace:
at: *workspace_location
# Overwrite the yarn installed in the docker container with our own version.
overwrite_yarn:
description: Overwrite yarn with our own version
# Install shared libs used by Chrome that is either provisioned by
# rules_webtesting or by puppeteer.
install_chrome_libs:
description: Install shared Chrome libs
steps:
- run:
name: Overwrite yarn
name: Install shared Chrome libs
command: |
localYarnPath=`node ./.circleci/get-vendored-yarn-path.js`
sudo chmod a+x $localYarnPath
sudo ln -fs $localYarnPath /usr/local/bin/yarn
- run: node --version
- run: yarn --version
sudo apt-get update
# Install GTK+ graphical user interface (libgtk-3-0), advanced linux sound architecture (libasound2)
# and network security service libraries (libnss3) & X11 Screen Saver extension library (libssx1)
# which are dependendies of chrome & needed for karma & protractor headless chrome tests.
# This is a very small install which takes around 7s in comparing to using the full
# circleci/node:x.x.x-browsers image.
sudo apt-get -y install libgtk-3-0 libasound2 libnss3 libxss1
# Install java runtime which is required by some integration tests such as
# //integration:hello_world__closure_test, //integration:i18n_test and
# //integration:ng_elements_test to run the closure compiler
install_java:
description: Install java
steps:
- run:
name: Install java
command: |
sudo apt-get update
# Install java runtime
sudo apt-get install default-jre
# Initializes the CI environment by setting up common environment variables.
init_environment:
description: Initializing environment (setting up variables, overwriting Yarn)
description: Initializing environment (setting up variables)
steps:
- run: ./.circleci/env.sh
- overwrite_yarn
- run:
name: Set up environment
environment:
CIRCLE_GIT_BASE_REVISION: << pipeline.git.base_revision >>
CIRCLE_GIT_REVISION: << pipeline.git.revision >>
command: ./.circleci/env.sh
- run:
# Configure git as the CircleCI `checkout` command does.
# This is needed because we only checkout on the setup job.
@ -150,6 +156,27 @@ commands:
git config --global url."ssh://git@github.com".insteadOf "https://github.com" || true
git config --global gc.auto 0 || true
init_saucelabs_environment:
description: Sets up a domain that resolves to the local host.
steps:
- run:
name: Preparing environment for running tests on Saucelabs.
command: |
# For SauceLabs jobs, we set up a domain which resolves to the machine which launched
# the tunnel. We do this because devices are sometimes not able to properly resolve
# `localhost` or `127.0.0.1` through the SauceLabs tunnel. Using a domain that does not
# resolve to anything on SauceLabs VMs ensures that such requests are always resolved
# through the tunnel, and resolve to the actual tunnel host machine (i.e. the CircleCI VM).
# More context can be found in: https://github.com/angular/angular/pull/35171.
setPublicVar SAUCE_LOCALHOST_ALIAS_DOMAIN "angular-ci.local"
setSecretVar SAUCE_ACCESS_KEY $(echo $SAUCE_ACCESS_KEY | rev)
- run:
# Sets up a local domain in the machine's host file that resolves to the local
# host. This domain is helpful in Saucelabs tests where devices are not able to
# properly resolve `localhost` or `127.0.0.1` through the sauce-connect tunnel.
name: Setting up alias domain for local host.
command: echo "127.0.0.1 $SAUCE_LOCALHOST_ALIAS_DOMAIN" | sudo tee -a /etc/hosts
# Normally this would be an individual job instead of a command.
# But startup and setup time for each invidual windows job are high enough to discourage
# many small jobs, so instead we use a command for setup unless the gain becomes significant.
@ -160,10 +187,6 @@ commands:
- custom_attach_workspace
# Install Bazel pre-requisites that aren't in the preconfigured CircleCI Windows VM.
- run: ./.circleci/windows-env.ps1
- run:
# Overwrite the yarn installed in the docker container with our own version.
name: Overwrite yarn with our own version
command: ./.circleci/windows-yarn-setup.ps1
- run: node --version
- run: yarn --version
- restore_cache:
@ -252,14 +275,21 @@ jobs:
(echo -e "\n.bzl files have lint errors. Please run ''yarn bazel:lint-fix''"; exit 1)'
- run: yarn gulp lint
- run: node tools/pullapprove/verify.js
test:
executor:
name: default-executor
resource_class: xlarge
# Now that large integration tests are running locally in parallel (they can't run on RBE yet
# as they require network access for yarn install), this test is running out of memory
# consistently with the xlarge machine.
# TODO: switch back to xlarge once integration tests are running on remote-exec
resource_class: 2xlarge+
steps:
- custom_attach_workspace
- init_environment
- install_chrome_libs
- install_java
- run:
command: yarn bazel test //... --build_tag_filters=-ivy-only --test_tag_filters=-ivy-only
no_output_timeout: 20m
@ -272,6 +302,7 @@ jobs:
steps:
- custom_attach_workspace
- init_environment
- install_chrome_libs
# We need to explicitly specify the --symlink_prefix option because otherwise we would
# not be able to easily find the output bin directory when uploading artifacts for size
# measurements.
@ -298,11 +329,7 @@ jobs:
path: dist/bin/packages/core/test/bundling/todo/bundle.min.js.br
destination: core/todo/bundle.br
# This job is currently a PoC for running tests on SauceLabs via bazel. It runs a subset of the
# tests in `legacy-unit-tests-saucelabs` (see
# [BUILD.bazel](https://github.com/angular/angular/blob/ef44f51d5/BUILD.bazel#L66-L92)).
#
# NOTE: This is currently limited to master builds only. See the `default_workflow` configuration.
# NOTE: This is currently limited to master builds only. See the `monitoring` configuration.
saucelabs_view_engine:
executor:
name: default-executor
@ -313,20 +340,20 @@ jobs:
steps:
- custom_attach_workspace
- init_environment
- init_saucelabs_environment
- run:
name: Preparing environment for running tests on Saucelabs.
command: setSecretVar SAUCE_ACCESS_KEY $(echo $SAUCE_ACCESS_KEY | rev)
- run:
name: Run Bazel tests on Saucelabs
name: Run Bazel tests on Saucelabs with ViewEngine
# See /tools/saucelabs/README.md for more info
command: |
yarn bazel run //tools/saucelabs:sauce_service_setup
yarn bazel test //:saucelabs_unit_tests_poc_suite --config=saucelabs
TESTS=$(./node_modules/.bin/bazel query --output label '(kind(karma_web_test, ...) intersect attr("tags", "saucelabs", ...)) except attr("tags", "ivy-only", ...) except attr("tags", "fixme-saucelabs-ve", ...)')
yarn bazel test --config=saucelabs ${TESTS}
yarn bazel run //tools/saucelabs:sauce_service_stop
no_output_timeout: 20m
no_output_timeout: 40m
- notify_webhook_on_fail:
webhook_url_env_var: SLACK_DEV_INFRA_CI_FAILURES_WEBHOOK_URL
# NOTE: This is currently limited to master builds only. See the `monitoring` configuration.
saucelabs_ivy:
executor:
name: default-executor
@ -337,24 +364,25 @@ jobs:
steps:
- custom_attach_workspace
- init_environment
- init_saucelabs_environment
- run:
name: Preparing environment for running tests on Saucelabs.
command: setSecretVar SAUCE_ACCESS_KEY $(echo $SAUCE_ACCESS_KEY | rev)
- run:
name: Run Bazel tests on Saucelabs
name: Run Bazel tests on Saucelabs with Ivy
# See /tools/saucelabs/README.md for more info
command: |
yarn bazel run //tools/saucelabs:sauce_service_setup
yarn bazel test //:saucelabs_unit_tests --config=saucelabs --config=ivy
TESTS=$(./node_modules/.bin/bazel query --output label '(kind(karma_web_test, ...) intersect attr("tags", "saucelabs", ...)) except attr("tags", "no-ivy-aot", ...) except attr("tags", "fixme-saucelabs-ivy", ...)')
yarn bazel test --config=saucelabs --config=ivy ${TESTS}
yarn bazel run //tools/saucelabs:sauce_service_stop
no_output_timeout: 20m
no_output_timeout: 40m
- notify_webhook_on_fail:
webhook_url_env_var: SLACK_DEV_INFRA_CI_FAILURES_WEBHOOK_URL
test_aio:
# Needed because the AIO tests and the PWA score test depend on Chrome being available.
executor: browsers-executor
executor: default-executor
steps:
- custom_attach_workspace
- init_environment
- install_chrome_libs
# Compile dependencies to ivy
# Running `ngcc` here (instead of implicitly via `ng build`) allows us to take advantage of
# the parallel, async mode speed-up (~20-25s on CI).
@ -377,11 +405,11 @@ jobs:
- run: yarn --cwd aio redirects-test
deploy_aio:
# Needed because before deploying the deploy-production script runs the PWA score tests.
executor: browsers-executor
executor: default-executor
steps:
- custom_attach_workspace
- init_environment
- install_chrome_libs
# Deploy angular.io to production (if necessary)
- run: setPublicVar_CI_STABLE_BRANCH
- run: yarn --cwd aio deploy-production
@ -391,11 +419,11 @@ jobs:
viewengine:
type: boolean
default: false
# Needed because the AIO tests and the PWA score test depend on Chrome being available.
executor: browsers-executor
executor: default-executor
steps:
- custom_attach_workspace
- init_environment
- install_chrome_libs
# Build aio (with local Angular packages)
- run: yarn --cwd aio build-local<<# parameters.viewengine >>-with-viewengine<</ parameters.viewengine >>-ci
# Run unit tests
@ -425,13 +453,13 @@ jobs:
type: boolean
default: false
executor:
# Needed because the example e2e tests depend on Chrome.
name: browsers-executor
name: default-executor
resource_class: xlarge
parallelism: 5
steps:
- custom_attach_workspace
- init_environment
- install_chrome_libs
# Install aio
- run: yarn --cwd aio install --frozen-lockfile --non-interactive
- when:
@ -466,11 +494,11 @@ jobs:
# This job should only be run on PR builds, where `CI_PULL_REQUEST` is not `false`.
test_aio_preview:
# Needed because the test-preview script runs e2e tests and the PWA score test with Chrome.
executor: browsers-executor
executor: default-executor
steps:
- custom_attach_workspace
- init_environment
- install_chrome_libs
- run: yarn --cwd aio install --frozen-lockfile --non-interactive
- run:
name: Wait for preview and run tests
@ -525,24 +553,18 @@ jobs:
paths:
- ng/dist/packages-dist-ivy-aot
# We run the integration tests outside of Bazel for now.
# They are a separate workflow job so that they can be easily re-run.
# When the tests are ported to bazel test targets, they should move to the "test"
# job above, as part of the bazel test command. That has flaky_test_attempts so the
# need to re-run manually should be alleviated.
# We run a subset of the integration tests outside of Bazel that track
# payload size.
# See comments inside the integration/run_tests.sh script.
# TODO(gregmagolan): move payload size tracking to Bazel and remove this job.
integration_test:
executor:
# Needed because the integration tests expect Chrome to be installed (e.g cli-hello-world)
name: browsers-executor
# Note: we run Bazel in one of the integration tests, and it can consume >2G
# of memory. Together with the system under test, this can exhaust the RAM
# on a 4G worker so we use a larger machine here too.
resource_class: xlarge
parallelism: 4
executor: default-executor
parallelism: 3
steps:
- custom_attach_workspace
- init_environment
- install_chrome_libs
- install_java
# Runs the integration tests in parallel across multiple CircleCI container instances. The
# amount of container nodes for this job is controlled by the "parallelism" option.
- run: ./integration/run_tests.sh ${CIRCLE_NODE_INDEX} ${CIRCLE_NODE_TOTAL}
@ -609,22 +631,19 @@ jobs:
- run: ./scripts/ci/publish-build-artifacts.sh
aio_monitoring_stable:
# This job needs Chrome to be globally installed because the tests run with Protractor
# which does not load the browser through the Bazel webtesting rules.
executor: browsers-executor
executor: default-executor
steps:
- custom_attach_workspace
- init_environment
- install_chrome_libs
- run: setPublicVar_CI_STABLE_BRANCH
- run:
name: Check out `aio/` and yarn from the stable branch
command: |
git fetch origin $CI_STABLE_BRANCH
git checkout --force origin/$CI_STABLE_BRANCH -- aio/ .yarn/ .yarnrc
# Overwrite yarn again to use the version from the checked out branch.
- overwrite_yarn
# Ignore yarn's engines check, because we checked out `aio/package.json` from the stable
# branch and there could be a node version skew, which is acceptable in this monitoring job.
# Ignore yarn's engines check, because we checked out `aio/package.json` from the stable
# branch and there could be a node version skew, which is acceptable in this monitoring job.
- run: yarn config set ignore-engines true
- run:
name: Run tests against https://angular.io/
@ -635,12 +654,11 @@ jobs:
webhook_url_env_var: SLACK_DEV_INFRA_CI_FAILURES_WEBHOOK_URL
aio_monitoring_next:
# This job needs Chrome to be globally installed because the tests run with Protractor
# which does not load the browser through the Bazel webtesting rules.
executor: browsers-executor
executor: default-executor
steps:
- custom_attach_workspace
- init_environment
- install_chrome_libs
- run:
name: Run tests against https://next.angular.io/
command: ./aio/scripts/test-production.sh https://next.angular.io/ $CI_AIO_MIN_PWA_SCORE
@ -659,11 +677,7 @@ jobs:
steps:
- custom_attach_workspace
- init_environment
- run:
name: Preparing environment for running tests on Saucelabs.
command: |
setPublicVar KARMA_JS_BROWSERS $(node -e 'console.log(require("./browser-providers.conf").sauceAliases.CI_REQUIRED.join(","))')
setSecretVar SAUCE_ACCESS_KEY $(echo $SAUCE_ACCESS_KEY | rev)
- init_saucelabs_environment
- run:
name: Starting Saucelabs tunnel service
command: ./tools/saucelabs/sauce-service.sh run
@ -675,7 +689,11 @@ jobs:
# Waiting on ready ensures that we don't run tests too early without Saucelabs not being ready.
name: Waiting for Saucelabs tunnel to connect
command: ./tools/saucelabs/sauce-service.sh ready-wait
- run: yarn karma start ./karma-js.conf.js --single-run --browsers=${KARMA_JS_BROWSERS}
- run:
name: Running tests on Saucelabs.
command: |
browsers=$(node -e 'console.log(require("./browser-providers.conf").sauceAliases.CI_REQUIRED.join(","))')
yarn karma start ./karma-js.conf.js --single-run --browsers=${browsers}
- run:
name: Stop Saucelabs tunnel service
command: ./tools/saucelabs/sauce-service.sh stop
@ -727,7 +745,7 @@ jobs:
command: node scripts/ci/update-deps-to-dist-packages.js ${COMPONENTS_REPO_TMP_DIR}/package.json dist/packages-dist/
- run:
name: "Running `angular/components` unit tests"
command: ./scripts/ci/run_angular_components_unit_tests.sh | exit 0
command: ./scripts/ci/run_angular_components_unit_tests.sh
test_zonejs:
executor:
@ -800,17 +818,6 @@ workflows:
- legacy-unit-tests-saucelabs:
requires:
- setup
- saucelabs_ivy:
requires:
- test_ivy_aot
- saucelabs_view_engine:
# This job is currently a PoC and a subset of `legacy-unit-tests-saucelabs`. Running on
# master only to avoid wasting resources.
# TODO: Run this job on all branches (including PRs) as soon as it is not a PoC and
# we can remove the legacy saucelabs job.
<<: *only_on_master
requires:
- setup
- test_aio:
requires:
- setup
@ -860,7 +867,6 @@ workflows:
- test
- test_ivy_aot
- integration_test
- saucelabs_ivy
# Only publish if `aio`/`docs` tests using the locally built Angular packages pass
- test_aio_local
- test_aio_local_viewengine
@ -871,10 +877,9 @@ workflows:
- build-npm-packages
- build-ivy-npm-packages
- legacy-unit-tests-saucelabs
# FIXME - uncomment this job once https://github.com/angular/components/pull/18355 lands
# - components-repo-unit-tests:
# requires:
# - build-npm-packages
- components-repo-unit-tests:
requires:
- build-npm-packages
- test_zonejs:
requires:
- setup
@ -893,7 +898,7 @@ workflows:
requires:
- test_ivy_aot
aio_monitoring:
monitoring:
jobs:
- setup
- aio_monitoring_stable:
@ -902,8 +907,26 @@ workflows:
- aio_monitoring_next:
requires:
- setup
- saucelabs_ivy:
# Testing saucelabs via Bazel currently taking longer than the legacy saucelabs job as it
# each karma_web_test target is provisioning and tearing down browsers which is adding
# a lot of overhead. Running once daily on master only to avoid wasting resources and
# slowing down CI for PRs.
# TODO: Run this job on all branches (including PRs) once karma_web_test targets can
# share provisioned browsers and we can remove the legacy saucelabs job.
requires:
- setup
- saucelabs_view_engine:
# Testing saucelabs via Bazel currently taking longer than the legacy saucelabs job as it
# each karma_web_test target is provisioning and tearing down browsers which is adding
# a lot of overhead. Running once daily on master only to avoid wasting resources and
# slowing down CI for PRs.
# TODO: Run this job on all branches (including PRs) once karma_web_test targets can
# share provisioned browsers and we can remove the legacy saucelabs job.
requires:
- setup
triggers:
- schedule:
<<: *only_on_master
# Runs AIO monitoring jobs at 10:00AM every day.
# Runs monitoring jobs at 10:00AM every day.
cron: "0 10 * * *"

View File

@ -19,19 +19,10 @@ setPublicVar CI_AIO_MIN_PWA_SCORE "95";
# This is the branch being built; e.g. `pull/12345` for PR builds.
setPublicVar CI_BRANCH "$CIRCLE_BRANCH";
setPublicVar CI_BUILD_URL "$CIRCLE_BUILD_URL";
# ChromeDriver version compatible with the Chrome version included in the docker image used in
# `.circleci/config.yml`. See http://chromedriver.chromium.org/downloads for a list of versions.
# This variable is intended to be passed as an arg to the `webdriver-manager update` command (e.g.
# `"postinstall": "webdriver-manager update $CI_CHROMEDRIVER_VERSION_ARG"`).
setPublicVar CI_CHROMEDRIVER_VERSION_ARG "--versions.chrome 79.0.3945.130";
setPublicVar CI_COMMIT "$CIRCLE_SHA1";
# `CI_COMMIT_RANGE` is only used on push builds (a.k.a. non-PR, non-scheduled builds and rerun
# workflows of such builds).
# NOTE: With [CircleCI Pipelines](https://circleci.com/docs/2.0/build-processing) enabled,
# `CIRCLE_COMPARE_URL` is no longer available and the commit range cannot be reliably
# detected. Fall back to only considering the last commit (which is accurate in the majority
# of cases for push builds).
setPublicVar CI_COMMIT_RANGE "`[[ ${CIRCLE_PR_NUMBER:-false} != false ]] && echo "" || echo "$CIRCLE_SHA1~1...$CIRCLE_SHA1"`";
setPublicVar CI_COMMIT_RANGE "$CIRCLE_GIT_BASE_REVISION..$CIRCLE_GIT_REVISION";
setPublicVar CI_PULL_REQUEST "${CIRCLE_PR_NUMBER:-false}";
setPublicVar CI_REPO_NAME "$CIRCLE_PROJECT_REPONAME";
setPublicVar CI_REPO_OWNER "$CIRCLE_PROJECT_USERNAME";
@ -65,6 +56,7 @@ setPublicVar SAUCE_TUNNEL_IDENTIFIER "angular-framework-${CIRCLE_BUILD_NUM}-${CI
# acquire CircleCI instances for too long if sauceconnect failed, we need a connect timeout.
setPublicVar SAUCE_READY_FILE_TIMEOUT 120
####################################################################################################
# Define environment variables for the `angular/components` repo unit tests job.
####################################################################################################
@ -76,7 +68,7 @@ setPublicVar COMPONENTS_REPO_TMP_DIR "/tmp/angular-components-repo"
setPublicVar COMPONENTS_REPO_URL "https://github.com/angular/components.git"
setPublicVar COMPONENTS_REPO_BRANCH "master"
# **NOTE**: When updating the commit SHA, also update the cache key in the CircleCI `config.yml`.
setPublicVar COMPONENTS_REPO_COMMIT "97a7e2babbccd3dc58e7b3364004e45ed5bd9968"
setPublicVar COMPONENTS_REPO_COMMIT "2ec7254f88c4865e0de251f74c27e64c9d00d40a"
####################################################################################################

View File

@ -1,166 +0,0 @@
#!/usr/bin/env node
/**
* **Usage:**
* ```
* node get-commit-range <build-number> [<compare-url> [<circle-token>]]
* ```
*
* Returns the commit range, either extracting it from `compare-url` (if defined), which is of the
* format of the `CIRCLE_COMPARE_URL` environment variable, or by retrieving the equivalent of
* `CIRCLE_COMPARE_URL` for jobs that are part of a rerun workflow and extracting it from there.
*
* > !!! WARNING !!!
* > !!
* > !! When [CircleCI Pipelines](https://circleci.com/docs/2.0/build-processing) is enabled, the
* > !! `CIRCLE_COMPARE_URL` environment variable is not available at all and this script does not
* > !! work.
* > !!!!!!!!!!!!!!!
*
* **Context:**
* CircleCI sets the `CIRCLE_COMPARE_URL` environment variable (from which we can extract the commit
* range) on push builds (a.k.a. non-PR, non-scheduled builds). Yet, when a workflow is rerun
* (either from the beginning or from failed jobs) - e.g. when a job flakes - CircleCI does not set
* the `CIRCLE_COMPARE_URL`.
*
* **Implementation details:**
* This script relies on the fact that all rerun workflows share the same CircleCI workspace and the
* (undocumented) fact that the workspace ID happens to be the same as the workflow ID that first
* created it.
*
* For example, for a job on push build workflows, the CircleCI API will return data that look like:
* ```js
* {
* compare: 'THE_COMPARE_URL_WE_ARE_LOOKING_FOR',
* //...
* previous: {
* // ...
* build_num: 12345,
* },
* //...
* workflows: {
* //...
* workflow_id: 'SOME_ID_A',
* workspace_id: 'SOME_ID_A', // Same as `workflow_id`.
* }
* }
* ```
*
* If the workflow is rerun, the data for jobs on the new workflow will look like:
* ```js
* {
* compare: null, // ¯\_(ツ)_/¯
* //...
* previous: {
* // ...
* build_num: 23456,
* },
* //...
* workflows: {
* //...
* workflow_id: 'SOME_ID_B',
* workspace_id: 'SOME_ID_A', // Different from current `workflow_id`.
* // Same as original `workflow_id`. \o/
* }
* }
* ```
*
* This script uses the `previous.build_num` (which points to the previous build number on the same
* branch) to traverse the jobs backwards, until it finds a job from the original workflow. Such a
* job (if found) should also contain the compare URL.
*
* **NOTE 1:**
* This is only useful on workflows which are created by rerunning a workflow for which
* `CIRCLE_COMPARE_URL` was defined.
*
* **NOTE 2:**
* The `circleToken` will be used for CircleCI API requests if provided, but it is not needed for
* accessing the read-only endpoints that we need (as long as the current project is FOSS and the
* corresponding setting is turned on in "Advanced Settings" in the project dashboard).
*
* ---
* Inspired by https://circleci.com/orbs/registry/orb/iynere/compare-url
* (source code: https://github.com/iynere/compare-url-orb).
*
* We are not using the `compare-url` orb for the following reasons:
* 1. (By looking at the code) it would only work if the rerun workflow is the latest workflow on
* the branch (which is not guaranteed to be true).
* 2. It is less efficient (e.g. makes unnecessary CircleCI API requests for builds on different
* branches, installs extra dependencies, persists files to the workspace (as a means of passing
* the result to the calling job), etc.).
* 3. It is slightly more complicated to setup and consume than our own script.
* 4. Its implementation is more complicated than needed for our usecase (e.g. handles different git
* providers, handles newly created branches, etc.).
*/
// Imports
const {get: httpsGet} = require('https');
// Constants
const API_URL_BASE = 'https://circleci.com/api/v1.1/project/github/angular/angular';
const COMPARE_URL_RE = /^.*\/([0-9a-f]+\.\.\.[0-9a-f]+)$/i;
// Run
_main(process.argv.slice(2));
// Helpers
async function _main([buildNumber, compareUrl = '', circleToken = '']) {
try {
if (!buildNumber || isNaN(buildNumber)) {
throw new Error(
'Missing or invalid arguments.\n' +
'Expected: buildNumber (number), compareUrl? (string), circleToken? (string)');
}
if (!compareUrl) {
compareUrl = await getCompareUrl(buildNumber, circleToken);
}
const commitRangeMatch = COMPARE_URL_RE.exec(compareUrl)
const commitRange = commitRangeMatch ? commitRangeMatch[1] : '';
console.log(commitRange);
} catch (err) {
console.error(err);
process.exit(1);
}
}
function getBuildInfo(buildNumber, circleToken) {
console.error(`BUILD ${buildNumber}`);
const url = `${API_URL_BASE}/${buildNumber}?circle-token=${circleToken}`;
return getJson(url);
}
async function getCompareUrl(buildNumber, circleToken) {
let info = await getBuildInfo(buildNumber, circleToken);
const targetWorkflowId = info.workflows.workspace_id;
while (info.workflows.workflow_id !== targetWorkflowId) {
info = await getBuildInfo(info.previous.build_num, circleToken);
}
return info.compare || '';
}
function getJson(url) {
return new Promise((resolve, reject) => {
const opts = {headers: {Accept: 'application/json'}};
const onResponse = res => {
const statusCode = res.statusCode || -1;
const isSuccess = (200 <= statusCode) && (statusCode < 400);
let responseText = '';
res.
on('error', reject).
on('data', d => responseText += d).
on('end', () => isSuccess ?
resolve(JSON.parse(responseText)) :
reject(`Error getting '${url}' (status ${statusCode}):\n${responseText}`));
};
httpsGet(url, opts, onResponse).
on('error', reject).
end();
});
}

View File

@ -1,36 +0,0 @@
#!/usr/bin/env node
'use strict';
/**
* **Usage:**
* ```
* node get-vendored-yarn-path
* ```
*
* Returns the path to the vendored `yarn.js` script, so that it can be used for setting up yarn
* aliases/symlinks and use the local, vendored yarn script instead of a globally installed one.
*
* **Context:**
* We keep a version of yarn in the repo, at `third_party/github.com/yarnpkg/`. All CI jobs should
* use that version for consistency (and easier updates). The path to the actual `yarn.js` script,
* however, changes depending on the version (e.g. `third_party/github.com/yarnpkg/v1.21.1/...`).
*
* This script infers the correct path, so that we don't have to update the path in several places,
* when we update the version of yarn in `third_party/github.com/yarnpkg/`.
*/
const {readdirSync} = require('fs');
const {normalize} = require('path');
const yarnDownloadDir = `${__dirname}/../third_party/github.com/yarnpkg/yarn/releases/download`;
const yarnVersionSubdirs = readdirSync(yarnDownloadDir);
// Based on our current process, there should be exactly one sub-directory inside
// `vendoredYarnDownloadDir` at all times. Throw, if that is not the case.
if (yarnVersionSubdirs.length !== 1) {
throw new Error(
`Expected exactly 1 yarn version in '${yarnDownloadDir}', but found ` +
`${yarnVersionSubdirs.length}: ${yarnVersionSubdirs.join(', ')}`);
}
console.log(normalize(`${yarnDownloadDir}/${yarnVersionSubdirs[0]}/bin/yarn.js`));

View File

@ -1,14 +0,0 @@
# Use our local, vendored yarn in the global `yarn` command.
$globalYarnDir = "$HOME\AppData\Roaming\yarn"
$localYarnPath = & ${Env:ProgramFiles}\nodejs\node.exe ".\.circleci\get-vendored-yarn-path.js"
# Create a directory to put the yarn PowerShell script.
New-Item -Path "$globalYarnDir" -ItemType "directory" >$null
# Create the yarn PowerShell script (using the inferred path to the local yarn script).
Get-Content -Path ".\.circleci\windows-yarn.ps1.template" |
%{$_ -replace "{{ LOCAL_YARN_PATH_PLACEHOLDER }}", "$localYarnPath"} |
Add-Content -Path "$globalYarnDir\yarn.ps1"
# Add the directory containing the yarn PowerShell script to `PATH`.
Add-Content -Path $profile -Value ('$Env:path = "{0};" + $Env:path' -f $globalYarnDir)

View File

@ -1,15 +0,0 @@
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
& "$basedir/node$exe" "{{ LOCAL_YARN_PATH_PLACEHOLDER }}" $args
$ret=$LASTEXITCODE
} else {
& "node$exe" "{{ LOCAL_YARN_PATH_PLACEHOLDER }}" $args
$ret=$LASTEXITCODE
}
exit $ret

View File

@ -40,6 +40,7 @@
# AndrewKushnir - Andrew Kushnir
# andrewseguin - Andrew Seguin
# atscott - Andrew Scott
# ayazhafiz - Ayaz Hafiz
# clydin - Charles Lyding
# crisbeto - Kristiyan Kostadinov
# dennispbrown - Denny Brown
@ -108,6 +109,9 @@ pullapprove_conditions:
- condition: "'PR state: WIP' not in labels"
unmet_status: pending
explanation: "Waiting to send reviews as PR is WIP"
- condition: "not draft"
unmet_status: pending
explanation: "Waiting to send reviews as PR is in draft"
groups:
@ -627,6 +631,7 @@ groups:
])
reviewers:
users:
- ayazhafiz
- kyliau
teams:
- ~framework-global-approvers
@ -640,7 +645,8 @@ groups:
conditions:
- >
contains_any_globs(files, [
'packages/zone.js/**'
'packages/zone.js/**',
'aio/content/guide/zone.md'
])
reviewers:
users:
@ -950,6 +956,7 @@ groups:
'tools/ng_rollup_bundle/**',
'tools/ngcontainer/**',
'tools/npm/**',
'tools/npm_integration_test/**',
'tools/public_api_guard/BUILD.bazel',
'tools/public_api_guard/public_api_guard.bzl',
'tools/pullapprove/**',
@ -961,6 +968,7 @@ groups:
'tools/testing/**',
'tools/ts-api-guardian/**',
'tools/tslint/**',
'tools/utils/**',
'tools/validate-commit-message/**',
'tools/yarn/**',
'tools/*',
@ -978,26 +986,6 @@ groups:
- ~framework-global-approvers
# =========================================================
# Material CI
# =========================================================
material-ci:
conditions:
- >
contains_any_globs(files, [
'tools/components-repo-ci/**'
])
reviewers:
users:
- alxhub
- AndrewKushnir
- kara
- mhevery
- pkozlowski-opensource
teams:
- ~framework-global-approvers
# =========================================================
# Public API
# =========================================================

View File

@ -1,7 +1,5 @@
package(default_visibility = ["//visibility:public"])
load("//tools:defaults.bzl", "karma_web_test")
exports_files([
"LICENSE",
"protractor-perf.conf.js",
@ -46,76 +44,3 @@ filegroup(
"@npm//:node_modules/angular-mocks-1.6/angular-mocks.js",
],
)
# To run manually:
# Setup your SAUCE_USERNAME, SAUCE_ACCESS_KEY & SAUCE_TUNNEL_IDENTIFIER.
# If on OSX, also set SAUCE_CONNECT to the path of your `sc` binary.
# environment variables and run:
# ```
# yarn bazel run //tools/saucelabs:sauce_service_setup
# yarn bazel test //:saucelabs_unit_tests --config=saucelabs --config=ivy
# ```
# See /tools/saucelabs/README.md for more info on karma Saucelabs tests under Bazel.
karma_web_test(
name = "saucelabs_unit_tests",
# Default timeout is moderate (5min). This causes the test to be terminated while
# Saucelabs browsers keep running. Ultimately resulting in failing tests and browsers
# unnecessarily being acquired. Our specified Saucelabs idle timeout is 10min, so we use
# Bazel's long timeout (15min). This ensures that Karma can shut down properly.
timeout = "long",
karma = "//tools/saucelabs:karma-saucelabs",
tags = [
"manual",
"no-remote-exec",
"saucelabs",
],
deps = [
"//packages/core/test/acceptance:acceptance_lib",
],
)
SAUCE_TEST_SUITE_TARGETS = [
"packages/common/http/test:test_lib",
"packages/common/http/testing/test:test_lib",
"packages/common/test:test_lib",
"packages/core/test:test_lib",
"packages/forms/test:test_lib",
"packages/http/test:test_lib",
]
[
# These target runs in CI with View Engine as a Saucelabs and Bazel proof-of-concept. It's a
# subset of the legacy saucelabs tests.
karma_web_test(
name = "saucelabs_unit_tests_poc_%s" % test.replace("/", "_").replace(":", "_").replace(".", "_"),
# Default timeout is moderate (5min). This causes the test to be terminated while
# Saucelabs browsers keep running. Ultimately resulting in failing tests and browsers
# unnecessarily being acquired. Our specified Saucelabs idle timeout is 10min, so we use
# Bazel's long timeout (15min). This ensures that Karma can shut down properly.
timeout = "long",
karma = "//tools/saucelabs:karma-saucelabs",
tags = [
"exclusive",
"manual",
"no-remote-exec",
"saucelabs",
],
deps = ["//%s" % test],
)
for test in SAUCE_TEST_SUITE_TARGETS
]
# To run manually:
# Setup your SAUCE_USERNAME, SAUCE_ACCESS_KEY & SAUCE_TUNNEL_IDENTIFIER.
# If on OSX, also set SAUCE_CONNECT to the path of your `sc` binary.
# environment variables and run:
# ```
# yarn bazel run //tools/saucelabs:sauce_service_setup
# yarn bazel test //:saucelabs_unit_tests_poc_suite --config=saucelabs
# ```
# See /tools/saucelabs/README.md for more info on karma Saucelabs tests under Bazel.
test_suite(
name = "saucelabs_unit_tests_poc_suite",
tags = ["manual"],
tests = ["//:saucelabs_unit_tests_poc_%s" % test.replace("/", "_").replace(":", "_").replace(".", "_") for test in SAUCE_TEST_SUITE_TARGETS],
)

File diff suppressed because it is too large Load Diff

View File

@ -8,8 +8,8 @@ load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
# Fetch rules_nodejs so we can install our npm dependencies
http_archive(
name = "build_bazel_rules_nodejs",
sha256 = "6bcef105e75cac3c5f8212e0d0431b6ec1aaa1963e093b0091474ab98ecf29d2",
urls = ["https://github.com/bazelbuild/rules_nodejs/releases/download/1.2.2/rules_nodejs-1.2.2.tar.gz"],
sha256 = "b6670f9f43faa66e3009488bbd909bc7bc46a5a9661a33f6bc578068d1837f37",
urls = ["https://github.com/bazelbuild/rules_nodejs/releases/download/1.3.0/rules_nodejs-1.3.0.tar.gz"],
)
# Check the bazel version and download npm dependencies
@ -18,6 +18,7 @@ load("@build_bazel_rules_nodejs//:index.bzl", "check_bazel_version", "check_rule
# Bazel version must be at least the following version because:
# - 0.26.0 managed_directories feature added which is required for nodejs rules 0.30.0
# - 0.27.0 has a fix for managed_directories after `rm -rf node_modules`
# - 2.1.0 feature added to honor .bazelignore in external repositories
check_bazel_version(
message = """
You no longer need to install Bazel on your machine.
@ -26,10 +27,10 @@ Try running `yarn bazel` instead.
(If you did run that, check that you've got a fresh `yarn install`)
""",
minimum_bazel_version = "2.0.0",
minimum_bazel_version = "2.1.0",
)
check_rules_nodejs_version(minimum_version_string = "1.2.2")
check_rules_nodejs_version(minimum_version_string = "1.3.0")
# Setup the Node.js toolchain
node_repositories(
@ -40,13 +41,13 @@ node_repositories(
},
node_version = "12.14.1",
package_json = ["//:package.json"],
# Label needs to explicitly specify the current workspace name because otherwise Bazel does
# not provide all needed data (like "workspace_root") to the repository context.
vendored_yarn = "@angular//:third_party/github.com/yarnpkg/yarn/releases/download/v1.21.1",
)
load("//integration:angular_integration_test.bzl", "npm_package_archives")
yarn_install(
name = "npm",
manual_build_file_contents = npm_package_archives(),
package_json = "//:package.json",
yarn_lock = "//:yarn.lock",
)

View File

@ -5,7 +5,8 @@
"packageManager": "yarn",
"warnings": {
"typescriptMismatch": false
}
},
"analytics": false
},
"newProjectRoot": "projects",
"projects": {
@ -192,4 +193,4 @@
}
},
"defaultProject": "site"
}
}

View File

@ -89,14 +89,14 @@ describe('Animation Tests', () => {
sleepFor(2000);
});
it('should be inactive with an orange background', async () => {
it('should be inactive with a blue background', async () => {
const toggleButton = statusSlider.getToggleButton();
const container = statusSlider.getComponentContainer();
let text = await container.getText();
if (text === 'Active') {
await toggleButton.click();
await browser.wait(async () => await container.getCssValue('backgroundColor') === inactiveColor, 2000);
await browser.wait(async () => await container.getCssValue('backgroundColor') === inactiveColor, 3000);
}
text = await container.getText();
@ -106,14 +106,14 @@ describe('Animation Tests', () => {
expect(bgColor).toBe(inactiveColor);
});
it('should be active with a blue background', async () => {
it('should be active with an orange background', async () => {
const toggleButton = statusSlider.getToggleButton();
const container = statusSlider.getComponentContainer();
let text = await container.getText();
if (text === 'Inactive') {
await toggleButton.click();
await browser.wait(async () => await container.getCssValue('backgroundColor') === activeColor, 2000);
await browser.wait(async () => await container.getCssValue('backgroundColor') === activeColor, 3000);
}
text = await container.getText();

View File

@ -12,10 +12,12 @@ Toggle All Animations <input type="checkbox" [checked]="!animationsDisabled" (cl
<a id="auto" routerLink="/auto" routerLinkActive="active">Auto Calculation</a>
<a id="heroes" routerLink="/heroes" routerLinkActive="active">Filter/Stagger</a>
<a id="hero-groups" routerLink="/hero-groups" routerLinkActive="active">Hero Groups</a>
<a id="insert-remove" routerLink="/insert-remove" routerLinkActive="active">Insert/Remove</a>
</nav>
<!-- #docregion route-animations-outlet -->
<div [@routeAnimations]="prepareRoute(outlet)" >
<router-outlet #outlet="outlet"></router-outlet>
</div>
<!-- #enddocregion route-animations-outlet -->
<!-- #enddocregion route-animations-outlet -->

View File

@ -35,6 +35,7 @@ import { InsertRemoveComponent } from './insert-remove.component';
{ path: 'hero-groups', component: HeroListGroupPageComponent },
{ path: 'enter-leave', component: HeroListEnterLeavePageComponent },
{ path: 'auto', component: HeroListAutoCalcPageComponent },
{ path: 'insert-remove', component: InsertRemoveComponent},
{ path: 'home', component: HomeComponent, data: {animation: 'HomePage'} },
{ path: 'about', component: AboutComponent, data: {animation: 'AboutPage'} },

View File

@ -1,4 +1,7 @@
<!-- #docplaster -->
<h2>Insert/Remove</h2>
<nav>
<button (click)="toggle()">Toggle Insert/Remove</button>
</nav>

View File

@ -9,10 +9,10 @@ import { trigger, transition, animate, style } from '@angular/animations';
trigger('myInsertRemoveTrigger', [
transition(':enter', [
style({ opacity: 0 }),
animate('5s', style({ opacity: 1 })),
animate('100ms', style({ opacity: 1 })),
]),
transition(':leave', [
animate('5s', style({ opacity: 0 }))
animate('100ms', style({ opacity: 0 }))
])
]),
// #enddocregion enter-leave-trigger

View File

@ -25,23 +25,12 @@ describe('Attribute binding example', function () {
});
it('should display a blue div with a red border', function () {
expect(element.all(by.css('div')).get(4).getCssValue('border')).toEqual('2px solid rgb(212, 30, 46)');
expect(element.all(by.css('div')).get(1).getCssValue('border')).toEqual('2px solid rgb(212, 30, 46)');
});
it('should display a div with replaced classes', function () {
expect(element.all(by.css('div')).get(5).getAttribute('class')).toEqual('new-class');
});
it('should display four buttons', function() {
let redButton = element.all(by.css('button')).get(1);
let saveButton = element.all(by.css('button')).get(2);
let bigButton = element.all(by.css('button')).get(3);
let smallButton = element.all(by.css('button')).get(4);
expect(redButton.getCssValue('color')).toEqual('rgba(255, 0, 0, 1)');
expect(saveButton.getCssValue('background-color')).toEqual('rgba(0, 255, 255, 1)');
expect(bigButton.getText()).toBe('Big');
expect(smallButton.getText()).toBe('Small');
it('should display a div with many classes', function () {
expect(element.all(by.css('div')).get(1).getAttribute('class')).toContain('special');
expect(element.all(by.css('div')).get(1).getAttribute('class')).toContain('clearance');
});
});

View File

@ -27,39 +27,41 @@
<hr />
<h2>Class binding</h2>
<h2>Styling precedence</h2>
<!-- #docregion is-special -->
<h3>toggle the "special" class on/off with a property:</h3>
<div [class.special]="isSpecial">The class binding is special.</div>
<!-- #docregion basic-specificity -->
<h3>Basic specificity</h3>
<h3>binding to class.special overrides the class attribute:</h3>
<div class="special" [class.special]="!isSpecial">This one is not so special.</div>
<!-- The `class.special` binding will override any value for the `special` class in `classExpr`. -->
<div [class.special]="isSpecial" [class]="classExpr">Some text.</div>
<h3>Using the bind- syntax:</h3>
<div bind-class.special="isSpecial">This class binding is special too.</div>
<!-- #enddocregion is-special -->
<!-- The `style.color` binding will override any value for the `color` property in `styleExpr`. -->
<div [style.color]="color" [style]="styleExpr">Some text.</div>
<!-- #enddocregion basic-specificity -->
<!-- #docregion add-class -->
<h3>Add a class:</h3>
<div class="item clearance special" [class.item-clearance]="itemClearance">Add another class</div>
<!-- #enddocregion add-class -->
<!-- #docregion source-specificity -->
<h3>Source specificity</h3>
<!-- #docregion class-override -->
<h3>Overwrite all existing classes with a new class:</h3>
<div class="item clearance special" [attr.class]="resetClasses">Reset all classes at once</div>
<!-- #enddocregion class-override -->
<!-- The `class.special` template binding will override any host binding to the `special` class set by `dirWithClassBinding` or `comp-with-host-binding`.-->
<comp-with-host-binding [class.special]="isSpecial" dirWithClassBinding>Some text.</comp-with-host-binding>
<hr />
<!-- The `style.color` template binding will override any host binding to the `color` property set by `dirWithStyleBinding` or `comp-with-host-binding`. -->
<comp-with-host-binding [style.color]="color" dirWithStyleBinding>Some text.</comp-with-host-binding>
<!-- #enddocregion source-specificity -->
<h2>Style binding</h2>
<!-- #docregion dynamic-priority -->
<h3>Dynamic vs static</h3>
<!-- If `classExpr` has a value for the `special` class, this value will override the `class="special"` below -->
<div class="special" [class]="classExpr">Some text.</div>
<!-- If `styleExpr` has a value for the `color` property, this value will override the `style="color: blue"` below -->
<div style="color: blue" [style]="styleExpr">Some text.</div>
<!-- #enddocregion dynamic-priority -->
<!-- #docregion style-delegation -->
<comp-with-host-binding dirWithHostBinding></comp-with-host-binding>
<!-- #enddocregion style-delegation -->
<!-- #docregion style-binding-->
<button [style.color]="isSpecial ? 'red': 'green'">Red</button>
<button [style.background-color]="canSave ? 'cyan': 'grey'" >Save</button>
<!-- #enddocregion style-binding -->
<!-- #docregion style-binding-condition-->
<button [style.font-size.em]="isSpecial ? 3 : 1" >Big</button>
<button [style.font-size.%]="!isSpecial ? 150 : 50" >Small</button>
<!-- #enddocregion style-binding-condition-->

View File

@ -8,8 +8,8 @@ import { Component } from '@angular/core';
export class AppComponent {
actionName = 'Go for it';
isSpecial = true;
itemClearance = true;
resetClasses = 'new-class';
canSave = true;
classExpr = 'special clearance';
styleExpr = 'color: red';
color = 'blue';
}

View File

@ -3,11 +3,13 @@ import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { CompWithHostBindingComponent } from './comp-with-host-binding.component';
@NgModule({
declarations: [
AppComponent
AppComponent,
CompWithHostBindingComponent
],
imports: [
BrowserModule

View File

@ -0,0 +1,16 @@
import { Component } from '@angular/core';
@Component({
selector: 'comp-with-host-binding',
template: 'I am a component!',
host: {
'[class.special]': 'isSpecial',
'[style.color]': 'color',
'[style.width]': 'width'
}
})
export class CompWithHostBindingComponent {
isSpecial = false;
color = 'green';
width = '200px';
}

View File

@ -4,9 +4,10 @@
"cmd": "yarn",
"args": [
"e2e",
"--protractor-config=e2e/protractor-puppeteer.conf.js",
"--no-webdriver-update",
"--port={PORT}"
]
}
]
}
}

View File

@ -23,7 +23,7 @@ export class HeroContactComponent {
@Host() // limit search for logger; hides the application-wide logger
@Optional() // ok if the logger doesn't exist
private loggerService: LoggerService
private loggerService?: LoggerService
// #enddocregion ctor-params
) {
if (loggerService) {

View File

@ -52,7 +52,7 @@ const templateC = `
export class CarolComponent {
name = 'Carol';
// #docregion carol-ctor
constructor( @Optional() public parent: Parent ) { }
constructor( @Optional() public parent?: Parent ) { }
// #enddocregion carol-ctor
}
// #enddocregion carol-class
@ -64,7 +64,7 @@ export class CarolComponent {
})
export class ChrisComponent {
name = 'Chris';
constructor( @Optional() public parent: Parent ) { }
constructor( @Optional() public parent?: Parent ) { }
}
////// Craig ///////////
@ -81,7 +81,7 @@ export class ChrisComponent {
</div>`
})
export class CraigComponent {
constructor( @Optional() public alex: Base ) { }
constructor( @Optional() public alex?: Base ) { }
}
// #enddocregion craig
@ -105,7 +105,7 @@ const templateB = `
export class BarryComponent implements Parent {
name = 'Barry';
// #docregion barry-ctor
constructor( @SkipSelf() @Optional() public parent: Parent ) { }
constructor( @SkipSelf() @Optional() public parent?: Parent ) { }
// #enddocregion barry-ctor
}
// #enddocregion barry
@ -117,7 +117,7 @@ export class BarryComponent implements Parent {
})
export class BobComponent implements Parent {
name = 'Bob';
constructor( @SkipSelf() @Optional() public parent: Parent ) { }
constructor( @SkipSelf() @Optional() public parent?: Parent ) { }
}
@Component({
@ -129,7 +129,7 @@ export class BobComponent implements Parent {
})
export class BethComponent implements Parent {
name = 'Beth';
constructor( @SkipSelf() @Optional() public parent: Parent ) { }
constructor( @SkipSelf() @Optional() public parent?: Parent ) { }
}
///////// A - Grandparent //////
@ -200,7 +200,7 @@ export class AliceComponent implements Parent
</div>`
})
export class CathyComponent {
constructor( @Optional() public alex: AlexComponent ) { }
constructor( @Optional() public alex?: AlexComponent ) { }
}
// #enddocregion cathy

View File

@ -4,9 +4,10 @@
"cmd": "yarn",
"args": [
"e2e",
"--protractor-config=e2e/protractor-puppeteer.conf.js",
"--no-webdriver-update",
"--port={PORT}"
]
}
]
}
}

View File

@ -247,7 +247,7 @@ let some_message = 'Hello from the injected logger';
export class Provider10Component implements OnInit {
log: string;
// #docregion provider-10-ctor
constructor(@Optional() private logger: Logger) {
constructor(@Optional() private logger?: Logger) {
if (this.logger) {
this.logger.log(some_message);
}

View File

@ -39,10 +39,10 @@ export class CartComponent implements OnInit {
// #enddocregion props-services
onSubmit(customerData) {
// Process checkout data here
console.warn('Your order has been submitted', customerData);
this.items = this.cartService.clearCart();
this.checkoutForm.reset();
console.warn('Your order has been submitted', customerData);
}
// #docregion props-services, inject-form-builder, checkout-form, checkout-form-group
}

View File

@ -39,8 +39,8 @@ export class ProductDetailsComponent implements OnInit {
// #enddocregion props-methods, get-product
// #docregion add-to-cart
addToCart(product) {
window.alert('Your product has been added to the cart!');
this.cartService.addToCart(product);
window.alert('Your product has been added to the cart!');
}
// #docregion props-methods, get-product, inject-cart-service
}

View File

@ -5,9 +5,10 @@
"cmd": "yarn",
"args": [
"e2e",
"--protractor-config=e2e/protractor-puppeteer.conf.js",
"--no-webdriver-update",
"--port={PORT}"
]
}
]
}
}

View File

@ -14,7 +14,7 @@ import { UserServiceConfig } from './user.service';
})
export class GreetingModule {
// #docregion ctor
constructor (@Optional() @SkipSelf() parentModule: GreetingModule) {
constructor (@Optional() @SkipSelf() parentModule?: GreetingModule) {
if (parentModule) {
throw new Error(
'GreetingModule is already loaded. Import it in the AppModule only');

View File

@ -15,7 +15,7 @@ export class UserService {
private _userName = 'Sherlock Holmes';
// #docregion ctor
constructor(@Optional() config: UserServiceConfig) {
constructor(@Optional() config?: UserServiceConfig) {
if (config) { this._userName = config.userName; }
}
// #enddocregion ctor

View File

@ -24,7 +24,7 @@ export class ChildComponent {
// inspector is in the content.
// constructor( public flower: FlowerService, @Optional() @Host() public animal: AnimalService) { }
// constructor( public flower: FlowerService, @Optional() @Host() public animal?: AnimalService) { }
// Comment out the above constructor and alternately
// uncomment the two following constructors to see the
@ -32,11 +32,11 @@ export class ChildComponent {
// constructor(
// @Host() public animal : AnimalService,
// @Host() @Optional() public flower : FlowerService) { }
// @Host() @Optional() public flower ?: FlowerService) { }
// constructor(
// @SkipSelf() @Host() public animal : AnimalService,
// @SkipSelf() @Host() @Optional() public flower : FlowerService) { }
// @SkipSelf() @Host() @Optional() public flower ?: FlowerService) { }
// #docregion provide-animal-service
}

View File

@ -11,7 +11,7 @@ import { FlowerService } from '../flower.service';
})
export class HostComponent {
// use @Host() in the constructor when injecting the service
constructor(@Host() @Optional() public flower: FlowerService) { }
constructor(@Host() @Optional() public flower?: FlowerService) { }
}
// #enddocregion host-component

View File

@ -9,7 +9,7 @@ import { OptionalService } from '../optional.service';
// #docregion optional-component
export class OptionalComponent {
constructor(@Optional() public optional: OptionalService) {}
constructor(@Optional() public optional?: OptionalService) {}
}
// #enddocregion optional-component

View File

@ -8,7 +8,7 @@ import { LeafService } from '../leaf.service';
styleUrls: ['./self-no-data.component.css']
})
export class SelfNoDataComponent {
constructor(@Self() @Optional() public leaf: LeafService) { }
constructor(@Self() @Optional() public leaf?: LeafService) { }
}
// #enddocregion self-no-data-component

View File

@ -1,6 +1,6 @@
// #docregion
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from '../auth.service';
@Component({
@ -25,12 +25,12 @@ export class LoginComponent {
this.authService.login().subscribe(() => {
this.setMessage();
if (this.authService.isLoggedIn) {
// Get the redirect URL from our auth service
// If no redirect has been set, use the default
let redirect = this.authService.redirectUrl ? this.router.parseUrl(this.authService.redirectUrl) : '/admin';
// Usually you would use the redirect URL from the auth service.
// However to keep the example simple, we will always redirect to `/admin`.
const redirectUrl = '/admin';
// Redirect the user
this.router.navigateByUrl(redirect);
this.router.navigate([redirectUrl]);
}
});
}

View File

@ -1,8 +1,7 @@
// #docregion
import { Component } from '@angular/core';
import { Router,
NavigationExtras } from '@angular/router';
import { AuthService } from '../auth.service';
import { Component } from '@angular/core';
import { NavigationExtras, Router } from '@angular/router';
import { AuthService } from '../auth.service';
@Component({
selector: 'app-login',
@ -26,9 +25,9 @@ export class LoginComponent {
this.authService.login().subscribe(() => {
this.setMessage();
if (this.authService.isLoggedIn) {
// Get the redirect URL from our auth service
// If no redirect has been set, use the default
let redirect = this.authService.redirectUrl ? this.router.parseUrl(this.authService.redirectUrl) : '/admin';
// Usually you would use the redirect URL from the auth service.
// However to keep the example simple, we will always redirect to `/admin`.
const redirectUrl = '/admin';
// #docregion preserve
// Set our navigation extras object
@ -39,7 +38,7 @@ export class LoginComponent {
};
// Redirect the user
this.router.navigateByUrl(redirect, navigationExtras);
this.router.navigate([redirectUrl], navigationExtras);
// #enddocregion preserve
}
});

View File

@ -1,7 +1,7 @@
{
"projectType": "service-worker",
"e2e": [
{"cmd": "yarn", "args": ["e2e", "--no-webdriver-update", "--port={PORT}"]},
{"cmd": "yarn", "args": ["e2e", "--protractor-config=e2e/protractor-puppeteer.conf.js", "--no-webdriver-update", "--port={PORT}"]},
{"cmd": "yarn", "args": ["build", "--prod"]},
{"cmd": "node", "args": ["--eval", "assert(fs.existsSync('./dist/ngsw.json'), 'ngsw.json is missing')"]},
{"cmd": "node", "args": ["--eval", "assert(fs.existsSync('./dist/ngsw-worker.js'), 'ngsw-worker.js is missing')"]},

View File

@ -15,7 +15,7 @@ import { throwIfAlreadyLoaded } from './module-import-guard';
providers: [LoggerService]
})
export class CoreModule {
constructor( @Optional() @SkipSelf() parentModule: CoreModule) {
constructor( @Optional() @SkipSelf() parentModule?: CoreModule) {
throwIfAlreadyLoaded(parentModule, 'CoreModule');
}
}

View File

@ -25,21 +25,21 @@ describe('Angular async helper', () => {
async(() => { setTimeout(() => { actuallyDone = true; }, 0); }));
it('should run async test with task', async(() => {
const id = setInterval(() => {
actuallyDone = true;
clearInterval(id);
}, 100);
}));
const id = setInterval(() => {
actuallyDone = true;
clearInterval(id);
}, 100);
}));
it('should run async test with successful promise', async(() => {
const p = new Promise(resolve => { setTimeout(resolve, 10); });
p.then(() => { actuallyDone = true; });
}));
const p = new Promise(resolve => { setTimeout(resolve, 10); });
p.then(() => { actuallyDone = true; });
}));
it('should run async test with failed promise', async(() => {
const p = new Promise((resolve, reject) => { setTimeout(reject, 10); });
p.catch(() => { actuallyDone = true; });
}));
const p = new Promise((resolve, reject) => { setTimeout(reject, 10); });
p.catch(() => { actuallyDone = true; });
}));
// Use done. Can also use async or fakeAsync.
it('should run async test with successful delayed Observable', (done: DoneFn) => {
@ -48,56 +48,84 @@ describe('Angular async helper', () => {
});
it('should run async test with successful delayed Observable', async(() => {
const source = of (true).pipe(delay(10));
source.subscribe(val => actuallyDone = true, err => fail(err));
}));
const source = of (true).pipe(delay(10));
source.subscribe(val => actuallyDone = true, err => fail(err));
}));
it('should run async test with successful delayed Observable', fakeAsync(() => {
const source = of (true).pipe(delay(10));
source.subscribe(val => actuallyDone = true, err => fail(err));
const source = of (true).pipe(delay(10));
source.subscribe(val => actuallyDone = true, err => fail(err));
tick(10);
}));
tick(10);
}));
});
describe('fakeAsync', () => {
// #docregion fake-async-test-tick
it('should run timeout callback with delay after call tick with millis', fakeAsync(() => {
let called = false;
setTimeout(() => { called = true; }, 100);
tick(100);
expect(called).toBe(true);
}));
let called = false;
setTimeout(() => { called = true; }, 100);
tick(100);
expect(called).toBe(true);
}));
// #enddocregion fake-async-test-tick
// #docregion fake-async-test-tick-new-macro-task-sync
it('should run new macro task callback with delay after call tick with millis',
fakeAsync(() => {
function nestedTimer(cb: () => any): void { setTimeout(() => setTimeout(() => cb())); }
const callback = jasmine.createSpy('callback');
nestedTimer(callback);
expect(callback).not.toHaveBeenCalled();
tick(0);
// the nested timeout will also be triggered
expect(callback).toHaveBeenCalled();
}));
// #enddocregion fake-async-test-tick-new-macro-task-sync
// #docregion fake-async-test-tick-new-macro-task-async
it('should not run new macro task callback with delay after call tick with millis',
fakeAsync(() => {
function nestedTimer(cb: () => any): void { setTimeout(() => setTimeout(() => cb())); }
const callback = jasmine.createSpy('callback');
nestedTimer(callback);
expect(callback).not.toHaveBeenCalled();
tick(0, {processNewMacroTasksSynchronously: false});
// the nested timeout will not be triggered
expect(callback).not.toHaveBeenCalled();
tick(0);
expect(callback).toHaveBeenCalled();
}));
// #enddocregion fake-async-test-tick-new-macro-task-async
// #docregion fake-async-test-date
it('should get Date diff correctly in fakeAsync', fakeAsync(() => {
const start = Date.now();
tick(100);
const end = Date.now();
expect(end - start).toBe(100);
}));
const start = Date.now();
tick(100);
const end = Date.now();
expect(end - start).toBe(100);
}));
// #enddocregion fake-async-test-date
// #docregion fake-async-test-rxjs
it('should get Date diff correctly in fakeAsync with rxjs scheduler', fakeAsync(() => {
// need to add `import 'zone.js/dist/zone-patch-rxjs-fake-async'
// to patch rxjs scheduler
let result = null;
of ('hello').pipe(delay(1000)).subscribe(v => { result = v; });
expect(result).toBeNull();
tick(1000);
expect(result).toBe('hello');
// need to add `import 'zone.js/dist/zone-patch-rxjs-fake-async'
// to patch rxjs scheduler
let result = null;
of ('hello').pipe(delay(1000)).subscribe(v => { result = v; });
expect(result).toBeNull();
tick(1000);
expect(result).toBe('hello');
const start = new Date().getTime();
let dateDiff = 0;
interval(1000).pipe(take(2)).subscribe(() => dateDiff = (new Date().getTime() - start));
const start = new Date().getTime();
let dateDiff = 0;
interval(1000).pipe(take(2)).subscribe(() => dateDiff = (new Date().getTime() - start));
tick(1000);
expect(dateDiff).toBe(1000);
tick(1000);
expect(dateDiff).toBe(2000);
}));
tick(1000);
expect(dateDiff).toBe(1000);
tick(1000);
expect(dateDiff).toBe(2000);
}));
// #enddocregion fake-async-test-rxjs
});

View File

@ -248,7 +248,7 @@ export class TestViewProvidersComponent {
export class ExternalTemplateComponent implements OnInit {
serviceValue: string;
constructor(@Optional() private service: ValueService) { }
constructor(@Optional() private service?: ValueService) { }
ngOnInit() {
if (this.service) { this.serviceValue = this.service.getValue(); }

View File

@ -5,9 +5,9 @@ import { Observable } from 'rxjs';
class DummyHeroesComponent {
heroes: Observable<Hero[]>;
// #docregion ctor
constructor(private heroService: HeroService) {}
// #enddocregion ctor
// #docregion getHeroes
getHeroes(): void {
// #docregion get-heroes

View File

@ -5,8 +5,8 @@ import { Component, OnInit } from '@angular/core';
import { Hero } from '../hero';
// #docregion hero-service-import
import { HeroService } from '../hero.service';
import { MessageService } from '../message.service';
// #enddocregion hero-service-import
import { MessageService } from '../message.service';
@Component({
selector: 'app-heroes',

View File

@ -21,7 +21,7 @@ export class HeroService {
constructor(
private http: HttpClient,
private messageService: MessageService,
@Optional() @Inject(APP_BASE_HREF) origin: string) {
@Optional() @Inject(APP_BASE_HREF) origin?: string) {
this.heroesUrl = `${origin}${this.heroesUrl}`;
}
// #enddocregion ctor

View File

@ -1,6 +1,6 @@
# Angular compiler options
When you use [AoT compilation](guide/aot-compiler), you can control how your application is compiled by specifying *template* compiler options in the `tsconfig.json` [TypeScript configuration file](guide/typescript-configuration).
When you use [AOT compilation](guide/aot-compiler), you can control how your application is compiled by specifying *template* compiler options in the `tsconfig.json` [TypeScript configuration file](guide/typescript-configuration).
The template options object, `angularCompilerOptions`, is a sibling to the `compilerOptions` object that supplies standard options to the TypeScript compiler.
@ -21,7 +21,7 @@ The template options object, `angularCompilerOptions`, is a sibling to the `comp
{@a tsconfig-extends}
## Configuration inheritance with extends
Like the TypeScript compiler, The Angular AoT compiler also supports `extends` in the `angularCompilerOptions` section of the TypeScript configuration file, `tsconfig.json`.
Like the TypeScript compiler, The Angular AOT compiler also supports `extends` in the `angularCompilerOptions` section of the TypeScript configuration file, `tsconfig.json`.
The `extends` property is at the top level, parallel to `compilerOptions` and `angularCompilerOptions`.
A TypeScript configuration can inherit settings from another file using the `extends` property.
@ -48,7 +48,7 @@ For more information, see the [TypeScript Handbook](https://www.typescriptlang.o
## Template options
The following options are available for configuring the AoT template compiler.
The following options are available for configuring the AOT template compiler.
### `allowEmptyCodegenFiles`

View File

@ -6,7 +6,7 @@ The Angular [ahead-of-time (AOT) compiler](guide/glossary#aot) converts your Ang
This guide explains how to specify metadata and apply available compiler options to compile your applications efficiently using the AOT compiler.
<div class="alert is-helpful"
<div class="alert is-helpful">
<a href="https://www.youtube.com/watch?v=kW9cJsvcsGo">Watch compiler author Tobias Bosch explain the Angular compiler</a> at AngularConnect 2016.
@ -570,7 +570,7 @@ In the template type-checking phase, the Angular template compiler uses the Type
Enable this phase explicitly by adding the compiler option `"fullTemplateTypeCheck"` in the `"angularCompilerOptions"` of the project's `tsconfig.json`
(see [Angular Compiler Options](guide/angular-compiler-options)).
<div class="alert is-helpful>
<div class="alert is-helpful">
In [Angular Ivy](guide/ivy), the template type checker has been completely rewritten to be more capable as well as stricter, meaning it can catch a variety of new errors that the previous type checker would not detect.

View File

@ -518,7 +518,7 @@ const raw = String.raw`A tagged template ${expression} string`;
[`String.raw()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/raw)
is a _tag function_ native to JavaScript ES2015.
The AoT compiler does not support tagged template expressions; avoid them in metadata expressions.
The AOT compiler does not support tagged template expressions; avoid them in metadata expressions.
<hr>

View File

@ -1,55 +1,90 @@
# Next steps: tools and techniques
After you understand the basic Angular building blocks, you can begin to learn more
about the features and tools that are available to help you develop and deliver Angular applications.
Here are some key features.
After you understand the basic Angular building blocks, you can learn more
about the features and tools that can help you develop and deliver Angular applications.
* Work through the [Tour of Heroes](tutorial/index) tutorial to get a feel for how to fit the basic building blocks together to create a well-designed application.
* Check out the [Glossary](guide/glossary) to understand Angular-specific terms and usage.
* Use the documentation to learn about key features in more depth, according to your stage of development and areas of interest.
## Application architecture
* The [Components and templates](guide/displaying-data) guide explains how to connect the application data in your [components](guide/glossary#component) to your page-display [templates](guide/glossary#template), to create a complete interactive application.
* The [NgModules](guide/ngmodules) guide provides in-depth information on the modular structure of an Angular application.
* The [Routing and navigation](guide/router) guide provides in-depth information on how to construct applications that allow a user to navigate to different [views](guide/glossary#view) within your single-page app.
* The [Dependency injection](guide/dependency-injection) guide provides in-depth information on how to construct an application such that each component class can acquire the services and objects it needs to perform its function.
## Responsive programming
The **Components and Templates** guide provides guidance and details of the [template syntax](guide/template-syntax) that you use to display your component data when and where you want it within a view, and to collect input from users that you can respond to.
Additional pages and sections describe some basic programming techniques for Angular apps.
* [Lifecycle hooks](guide/lifecycle-hooks): Tap into key moments in the lifetime of a component, from its creation to its destruction, by implementing the lifecycle hook interfaces.
* [Observables and event processing](guide/observables): How to use observables with components and services to publish and subscribe to messages of any type, such as user-interaction events and asynchronous operation results.
## Client-server interaction
* [Angular elements](guide/elements): How to package components as *custom elements* using Web Components, a web standard for defining new HTML elements in a framework-agnostic way.
* [HTTP](guide/http): Communicate with a server to get data, save data, and invoke server-side actions with an HTTP client.
* [Server-side Rendering](guide/universal): Angular Universal generates static application pages on the server through server-side rendering (SSR). This allows you to run your Angular app on the server in order to improve performance and show the first page quickly on mobile and low-powered devices, and also facilitate web crawlers.
* [Service Workers](guide/service-worker-intro): Use a service worker to reduce dependency on the network
significantly improving the user experience.
## Domain-specific libraries
* [Forms](guide/forms-overview): Support complex data entry scenarios with HTML-based input validation.
* [Animations](guide/animations): Use Angular's animation library to animate component behavior
without deep knowledge of animation techniques or CSS.
* [Forms](guide/forms): Support complex data entry scenarios with HTML-based validation and dirty checking.
## Client-server interaction
Angular provides a framework for single-page apps, where most of the logic and data resides on the client.
Most apps still need to access a server using the `HttpClient` to access and save data.
For some platforms and applications, you might also want to use the PWA (Progressive Web App) model to improve the user experience.
* [HTTP](guide/http): Communicate with a server to get data, save data, and invoke server-side actions with an HTTP client.
* [Server-side rendering](guide/universal): Angular Universal generates static application pages on the server through server-side rendering (SSR). This allows you to run your Angular app on the server in order to improve performance and show the first page quickly on mobile and low-powered devices, and also facilitate web crawlers.
* [Service workers and PWA](guide/service-worker-intro): Use a service worker to reduce dependency on the network and significantly improve the user experience.
* [Web workers](guide/web-worker): Learn how to run CPU-intensive computations in a background thread.
## Support for the development cycle
The **Development Workflow** section describes the tools and processes you use to compile, test, and and deploy Angular applications.
* [CLI Command Reference](cli): The Angular CLI is a command-line tool that you use to create projects, generate application and library code, and perform a variety of ongoing development tasks such as testing, bundling, and deployment.
* [Compilation](guide/aot-compiler): Angular provides just-in-time (JIT) compilation for the development environment, and ahead-of-time (AOT) compilation for the production environment.
* [Testing platform](guide/testing): Run unit tests on your application parts as they interact with the Angular framework.
* [Internationalization](guide/i18n): Make your app available in multiple languages with Angular's internationalization (i18n) tools.
* [Deployment](guide/deployment): Learn techniques for deploying your Angular application to a remote server.
* [Security guidelines](guide/security): Learn about Angular's built-in protections against common web-app vulnerabilities and attacks such as cross-site scripting attacks.
## Setup, build, and deployment configuration
* [Internationalization](guide/i18n): Make your app available in multiple languages with Angular's internationalization (i18n) tools.
* [CLI Command Reference](cli): The Angular CLI is a command-line tool that you use to create projects, generate application and library code, and perform a variety of ongoing development tasks such as testing, bundling, and deployment.
* [Accessibility](guide/accessibility): Make your app accessible to all users.
* [Workspace and File Structure](guide/file-structure): Understand the structure of Angular workspace and project folders.
* [npm Packages](guide/npm-packages): The Angular Framework, Angular CLI, and components used by Angular applications are packaged as [npm](https://docs.npmjs.com/) packages and distributed via the npm registry. The Angular CLI creates a default `package.json` file, which specifies a starter set of packages that work well together and jointly support many common application scenarios.
## File structure, configuration, and dependencies
* [Workspace and file structure](guide/file-structure): Understand the structure of Angular workspace and project folders.
* [Building and serving](guide/build): Learn to define different build and proxy server configurations for your project, such as development, staging, and production.
* [npm packages](guide/npm-packages): The Angular Framework, Angular CLI, and components used by Angular applications are packaged as [npm](https://docs.npmjs.com/) packages and distributed via the npm registry. The Angular CLI creates a default `package.json` file, which specifies a starter set of packages that work well together and jointly support many common application scenarios.
* [TypeScript configuration](guide/typescript-configuration): TypeScript is the primary language for Angular application development.
* [Browser support](guide/browser-support): Make your apps compatible across a wide range of browsers.
* [Building and Serving](guide/build): Learn to define different build and proxy server configurations for your project, such as development, staging, and production.
## Extending Angular
* [Deployment](guide/deployment): Learn techniques for deploying your Angular application to a remote server.
* [Angular libraries](guide/libraries): Learn about using and creating re-usable libraries.
* [Schematics](guide/schematics): Learn about customizing and extending the CLI's generation capabilities.
* [CLI builders](guide/cli-builder): Learn about customizing and extending the CLI's ability to apply tools to perform complex tasks, such as building and testing applications.

View File

@ -1,11 +1,13 @@
# Architecture overview
# Introduction to Angular concepts
Angular is a platform and framework for building client applications in HTML and TypeScript.
Angular is written in TypeScript. It implements core and optional functionality as a set of TypeScript libraries that you import into your apps.
Angular is a platform and framework for building single-page client applications in HTML and TypeScript.
Angular is written in TypeScript.
It implements core and optional functionality as a set of TypeScript libraries that you import into your apps.
The basic building blocks of an Angular application are *NgModules*, which provide a compilation context for *components*. NgModules collect related code into functional sets; an Angular app is defined by a set of NgModules. An app always has at least a *root module* that enables bootstrapping, and typically has many more *feature modules*.
The architecture of an Angular application relies on certain fundamental concepts.
The basic building blocks are *NgModules*, which provide a compilation context for *components*. NgModules collect related code into functional sets; an Angular app is defined by a set of NgModules. An app always has at least a *root module* that enables bootstrapping, and typically has many more *feature modules*.
* Components define *views*, which are sets of screen elements that Angular can choose among and modify according to your program logic and data.
* Components define *views*, which are sets of screen elements that Angular can choose among and modify according to your program logic and data.
* Components use *services*, which provide specific functionality not directly related to views. Service providers can be *injected* into components as *dependencies*, making your code modular, reusable, and efficient.
@ -17,6 +19,12 @@ Both components and services are simply classes, with *decorators* that mark the
An app's components typically define many views, arranged hierarchically. Angular provides the `Router` service to help you define navigation paths among views. The router provides sophisticated in-browser navigational capabilities.
<div class="alert is-helpful>
See the [Angular Glossary](guide/glossary) for basic definitions of important Angular terms and usage.
</div>
## Modules
Angular *NgModules* differ from and complement JavaScript (ES2015) modules. An NgModule declares a compilation context for a set of components that is dedicated to an application domain, a workflow, or a closely related set of capabilities. An NgModule can associate its components with related code, such as services, to form functional units.
@ -58,7 +66,7 @@ There are two types of data binding:
Before a view is displayed, Angular evaluates the directives and resolves the binding syntax in the template to modify the HTML elements and the DOM, according to your program data and logic. Angular supports *two-way data binding*, meaning that changes in the DOM, such as user choices, are also reflected in your program data.
Your templates can use *pipes* to improve the user experience by transforming values for display.
Your templates can use *pipes* to improve the user experience by transforming values for display.
For example, use pipes to display dates and currency values that are appropriate for a user's locale.
Angular provides predefined pipes for common transformations, and you can also define your own pipes.

View File

@ -48,7 +48,7 @@ You can build, test, and lint the project with CLI commands:
</code-example>
Notice that the configured builder for the project is different from the default builder for app projects.
This builder, among other things, ensures that the library is always built with the [AoT compiler](guide/aot-compiler), without the need to specify the `--prod` flag.
This builder, among other things, ensures that the library is always built with the [AOT compiler](guide/aot-compiler), without the need to specify the `--prod` flag.
To make library code reusable you must define a public API for it. This "user layer" defines what is available to consumers of your library. A user of your library should be able to access public functionality (such as NgModules, service providers and general utility functions) through a single import path.
@ -119,6 +119,7 @@ npm publish
If you've never published a package in npm before, you must create a user account. Read more in [Publishing npm Packages](https://docs.npmjs.com/getting-started/publishing-npm-packages).
## Linked libraries
While working on a published library, you can use [npm link](https://docs.npmjs.com/cli/link) to avoid reinstalling the library on every build.
@ -156,6 +157,7 @@ List all the peer dependencies that your library uses in the workspace TypeScrip
This mapping ensures that your library always loads the local copies of the modules it needs.
## Using your own library in apps
You don't have to publish your library to the npm package manager in order to use it in your own apps, but you do have to build it first.
@ -213,3 +215,14 @@ For this reason, an app that depends on a library should only use TypeScript pat
TypeScript path mappings should *not* point to the library source `.ts` files.
</div>
{@a lib-assets}
### Managing library assets with ng-packagr
Starting with version 9.x of the [ng-packagr](https://github.com/ng-packagr/ng-packagr/blob/master/README.md) tool, you can configure the tool to automatically copy assets into your library package as part of the build process.
You can use this feature when your library needs to publish optional theming files, Sass mixins, or documentation (like a changelog).
* Learn how to [copy assets into your library as part of the build](https://github.com/ng-packagr/ng-packagr/blob/master/docs/copy-assets.md).
* Learn more about how to use the tool to [embed assets in CSS](https://github.com/ng-packagr/ng-packagr/blob/master/docs/embed-assets-css.md).

View File

@ -80,6 +80,7 @@ In the table below, you can find a list of packages which implement deployment f
| [Netlify](https://www.netlify.com/) | [`@netlify-builder/deploy`](https://npmjs.org/package/@netlify-builder/deploy) |
| [GitHub pages](https://pages.github.com/) | [`angular-cli-ghpages`](https://npmjs.org/package/angular-cli-ghpages) |
| [NPM](https://npmjs.com/) | [`ngx-deploy-npm`](https://npmjs.org/package/ngx-deploy-npm) |
| [Amazon Cloud S3](https://aws.amazon.com/s3/?nc2=h_ql_prod_st_s3) | [`@jefiozie/ngx-aws-deploy`](https://www.npmjs.com/package/@jefiozie/ngx-aws-deploy) |
If you're deploying to a self-managed server or there's no builder for your favorite cloud platform, you can either create a builder that allows you to use the `ng deploy` command, or read through this guide to learn how to manually deploy your app.

View File

@ -1,11 +1,20 @@
# Displaying data
# Displaying data in views
You can display data by binding controls in an HTML template to properties of an Angular component.
Angular [components](guide/glossary#component) form the data structure of your application.
The HTML [template](guide/glossary#template) associated with a component provides the means to display that data in the context of a web page.
Together, a component's class and template form a [view](guide/glossary#view) of your application data.
In this page, you'll create a component with a list of heroes.
You'll display the list of hero names and
conditionally show a message below the list.
The process of combining data values with their representation on the page is called [data binding](guide/glossary#data-binding).
You display your data to a user (and collect data from the user) by *binding* controls in the HTML template to the data properties of the component class.
In addition, you can add logic to the template by including [directives](guide/glossary#directive), which tell Angular how to modify the page as it is rendered.
Angular defines a *template language* that expands HTML notation with syntax that allows you to define various kinds of data binding and logical directives.
When the page is rendered, Angular interprets the template syntax to update the HTML according to your logic and current data state.
Before you read the complete [template syntax guide](guide/template-syntax), the exercises on this page give you a quick demonstration of how template syntax works.
In this demo, you'll create a component with a list of heroes.
You'll display the list of hero names and conditionally show a message below the list.
The final UI looks like this:
<div class="lightbox">
@ -14,20 +23,14 @@ The final UI looks like this:
<div class="alert is-helpful">
The <live-example></live-example> demonstrates all of the syntax and code
snippets described in this page.
The <live-example></live-example> demonstrates all of the syntax and code snippets described in this page.
</div>
{@a interpolation}
## Showing component properties with interpolation
The easiest way to display a component property
is to bind the property name through interpolation.
The easiest way to display a component property is to bind the property name through interpolation.
With interpolation, you put the property name in the view template, enclosed in double curly braces: `{{myHero}}`.
Use the CLI command [`ng new displaying-data`](cli/new) to create a workspace and app named `displaying-data`.
@ -39,63 +42,43 @@ changing the template and the body of the component.
When you're done, it should look like this:
<code-example path="displaying-data/src/app/app.component.1.ts" header="src/app/app.component.ts"></code-example>
You added two properties to the formerly empty component: `title` and `myHero`.
The template displays the two component properties using double curly brace
interpolation:
<code-example path="displaying-data/src/app/app.component.1.ts" header="src/app/app.component.ts (template)" region="template"></code-example>
<div class="alert is-helpful">
The template is a multi-line string within ECMAScript 2015 backticks (<code>\`</code>).
The backtick (<code>\`</code>)&mdash;which is *not* the same character as a single
quote (`'`)&mdash;allows you to compose a string over several lines, which makes the
HTML more readable.
</div>
Angular automatically pulls the value of the `title` and `myHero` properties from the component and
inserts those values into the browser. Angular updates the display
when these properties change.
<div class="alert is-helpful">
More precisely, the redisplay occurs after some kind of asynchronous event related to
the view, such as a keystroke, a timer completion, or a response to an HTTP request.
</div>
Notice that you don't call **new** to create an instance of the `AppComponent` class.
Angular is creating an instance for you. How?
The CSS `selector` in the `@Component` decorator specifies an element named `<app-root>`.
That element is a placeholder in the body of your `index.html` file:
<code-example path="displaying-data/src/index.html" header="src/index.html (body)" region="body"></code-example>
When you bootstrap with the `AppComponent` class (in <code>main.ts</code>), Angular looks for a `<app-root>`
in the `index.html`, finds it, instantiates an instance of `AppComponent`, and renders it
inside the `<app-root>` tag.
@ -109,45 +92,44 @@ Now run the app. It should display the title and hero name:
The next few sections review some of the coding choices in the app.
## Template inline or template file?
## Choosing the template source
The `@Component` metadata tells Angular where to find the component's template.
You can store your component's template in one of two places.
You can define it *inline* using the `template` property, or you can define
the template in a separate HTML file and link to it in
the component metadata using the `@Component` decorator's `templateUrl` property.
The choice between inline and separate HTML is a matter of taste,
circumstances, and organization policy.
Here the app uses inline HTML because the template is small and the demo
is simpler without the additional HTML file.
* You can define the template *inline* using the `template` property of the `@Component` decorator. An inline template is useful for a small demo or test.
* Alternatively, you can define the template in a separate HTML file and link to that file in the `templateUrl` property of the `@Component` decorator. This configuration is typical for anything more complex than a small test or demo, and is the default when you generate a new component.
In either style, the template data bindings have the same access to the component's properties.
Here the app uses inline HTML because the template is small and the demo is simpler without the additional HTML file.
<div class="alert is-helpful">
By default, the Angular CLI command [`ng generate component`](cli/generate) generates components with a template file. You can override that with:
By default, the Angular CLI command [`ng generate component`](cli/generate) generates components with a template file.
You can override that by adding the "-t" (short for `inlineTemplate=true`) option:
<code-example hideCopy language="sh" class="code-shell">
ng generate component hero -it
ng generate component hero -t
</code-example>
</div>
## Constructor or variable initialization?
Although this example uses variable assignment to initialize the components, you could instead declare and initialize the properties using a constructor:
## Initialization
The following example uses variable assignment to initialize the components.
<code-example path="displaying-data/src/app/app-ctor.component.1.ts" region="class"></code-example>
You could instead declare and initialize the properties using a constructor.
This app uses more terse "variable assignment" style simply for brevity.
This app uses more terse "variable assignment" style simply for brevity.
{@a ngFor}
## Showing an array property with ***ngFor**
## Add logic to loop through data
The `*ngFor` directive (predefined by Angular) lets you loop through data. The following example uses the directive to show all of the values in an array property.
To display a list of heroes, begin by adding an array of hero names to the component and redefine `myHero` to be the first name in the array.
@ -155,15 +137,12 @@ To display a list of heroes, begin by adding an array of hero names to the compo
<code-example path="displaying-data/src/app/app.component.2.ts" header="src/app/app.component.ts (class)" region="class"></code-example>
Now use the Angular `ngFor` directive in the template to display
each item in the `heroes` list.
Now use the Angular `ngFor` directive in the template to display each item in the `heroes` list.
<code-example path="displaying-data/src/app/app.component.2.ts" header="src/app/app.component.ts (template)" region="template"></code-example>
This UI uses the HTML unordered list with `<ul>` and `<li>` tags. The `*ngFor`
in the `<li>` element is the Angular "repeater" directive.
It marks that `<li>` element (and its children) as the "repeater template":
@ -171,20 +150,13 @@ It marks that `<li>` element (and its children) as the "repeater template":
<code-example path="displaying-data/src/app/app.component.2.ts" header="src/app/app.component.ts (li)" region="li"></code-example>
<div class="alert is-important">
Don't forget the leading asterisk (\*) in `*ngFor`. It is an essential part of the syntax.
For more information, see the [Template Syntax](guide/template-syntax#ngFor) page.
</div>
Notice the `hero` in the `ngFor` double-quoted instruction;
it is an example of a template input variable. Read
more about template input variables in the [microsyntax](guide/template-syntax#microsyntax) section of
@ -194,18 +166,13 @@ Angular duplicates the `<li>` for each item in the list, setting the `hero` vari
to the item (the hero) in the current iteration. Angular uses that variable as the
context for the interpolation in the double curly braces.
<div class="alert is-helpful">
In this case, `ngFor` is displaying an array, but `ngFor` can
repeat items for any [iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) object.
</div>
Now the heroes appear in an unordered list.
<div class="lightbox">
@ -228,13 +195,11 @@ of hero names into an array of `Hero` objects. For that you'll need a `Hero` cla
ng generate class hero
</code-example>
With the following code:
This command creates the following code.
<code-example path="displaying-data/src/app/hero.ts" header="src/app/hero.ts"></code-example>
You've defined a class with a constructor and two properties: `id` and `name`.
It might not look like the class has properties, but it does.
@ -245,8 +210,6 @@ Consider the first parameter:
<code-example path="displaying-data/src/app/hero.ts" header="src/app/hero.ts (id)" region="id"></code-example>
That brief syntax does a lot:
* Declares a constructor parameter and its type.
@ -254,7 +217,6 @@ That brief syntax does a lot:
* Initializes that property with the corresponding argument when creating an instance of the class.
### Using the Hero class
After importing the `Hero` class, the `AppComponent.heroes` property can return a _typed_ array
@ -273,7 +235,6 @@ Fix that to display only the hero's `name` property.
<code-example path="displaying-data/src/app/app.component.3.ts" header="src/app/app.component.ts (template)" region="template"></code-example>
The display looks the same, but the code is clearer.
{@a ngIf}
@ -291,46 +252,35 @@ To see it in action, add the following paragraph at the bottom of the template:
<code-example path="displaying-data/src/app/app.component.ts" header="src/app/app.component.ts (message)" region="message"></code-example>
<div class="alert is-important">
Don't forget the leading asterisk (\*) in `*ngIf`. It is an essential part of the syntax.
Read more about `ngIf` and `*` in the [ngIf section](guide/template-syntax#ngIf) of the [Template Syntax](guide/template-syntax) page.
</div>
The template expression inside the double quotes,
`*ngIf="heroes.length > 3"`, looks and behaves much like TypeScript.
When the component's list of heroes has more than three items, Angular adds the paragraph
to the DOM and the message appears. If there are three or fewer items, Angular omits the
paragraph, so no message appears. For more information,
see the [template expressions](guide/template-syntax#template-expressions) section of the
[Template Syntax](guide/template-syntax) page.
to the DOM and the message appears.
If there are three or fewer items, Angular omits the paragraph, so no message appears.
For more information, see [template expressions](guide/template-syntax#template-expressions).
<div class="alert is-helpful">
Angular isn't showing and hiding the message. It is adding and removing the paragraph element from the DOM. That improves performance, especially in larger projects when conditionally including or excluding
big chunks of HTML with many data bindings.
</div>
Try it out. Because the array has four items, the message should appear.
Go back into <code>app.component.ts</code> and delete or comment out one of the elements from the heroes array.
The browser should refresh automatically and the message should disappear.
## Summary
Now you know how to use:
@ -341,7 +291,6 @@ Now you know how to use:
Here's the final code:
<code-tabs>
<code-pane header="src/app/app.component.ts" path="displaying-data/src/app/app.component.ts" region="final">

View File

@ -593,7 +593,7 @@ Compare to [NgModule](#ngmodule).
## ngcc
Angular compatability compiler.
Angular compatibility compiler.
If you build your app using [Ivy](#ivy), but it depends on libraries have not been compiled with Ivy, the CLI uses `ngcc` to automatically update the dependent libraries to use Ivy.

View File

@ -320,7 +320,7 @@ Use `@SkipSelf()` with `@Optional()` to prevent an error if the value is `null`.
``` ts
class Person {
constructor(@Optional() @SkipSelf() parent: Person) {}
constructor(@Optional() @SkipSelf() parent?: Person) {}
}
```

View File

@ -17,6 +17,23 @@ If you're still seeing the errors, they are not specific to Ivy. In this case, y
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.
{@a payload-size-debugging}
### Payload size debugging
If you notice that the size of your application's main bundle has increased with Ivy, you may want to check the following:
1. Verify that the components and `NgModules` that you want to be lazy loaded are only imported in lazy modules.
Anything that you import outside lazy modules can end up in the main bundle.
See more details in the original issue [here](https://github.com/angular/angular-cli/issues/16146#issuecomment-557559287).
1. Check that imported libraries have been marked side-effect-free.
If your app imports from shared libraries that are meant to be free from side effects, add "sideEffects": false to their `package.json`.
This will ensure that the libraries will be properly tree-shaken if they are imported but not directly referenced.
See more details in the original issue [here](https://github.com/angular/angular-cli/issues/16799#issuecomment-580912090).
1. Projects not using Angular CLI will see a significant size regression unless they update their minifier settings and set compile-time constants `ngDevMode`, `ngI18nClosureMode` and `ngJitMode` to `false` (for Terser, please set these to `false` via [`global_defs` config option](https://terser.org/docs/api-reference.html#conditional-compilation)).
Please note that these constants are not meant to be used by 3rd party library or application code as they are not part of our public api surface and might change in the future.
{@a common-changes}
### Changes you may see
@ -27,6 +44,8 @@ If the errors are gone, switch back to Ivy by removing the changes to the `tscon
* 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).
* Static attributes set directly in the HTML of a template will override any conflicting host attributes set by directives or components (previously, static host attributes set by directives / components would override static template attributes if conflicting).
{@a less-common-changes}
### Less common changes
@ -62,4 +81,10 @@ If the errors are gone, switch back to Ivy by removing the changes to the `tscon
* `DebugElement.classes` returns `undefined` for classes that were added and then subsequently removed (previously, classes added and later removed would have a value of `false`).
* If selecting the native `<option>` element in a `<select>` where the `<option>`s are created via `*ngFor`, use the `[selected]` property of an `<option>` instead of binding to the `[value]` property of the `<select>` element (previously, you could bind to either.) [details](guide/ivy-compatibility-examples#select-value-binding)
* If selecting the native `<option>` element in a `<select>` where the `<option>`s are created via `*ngFor`, use the `[selected]` property of an `<option>` instead of binding to the `[value]` property of the `<select>` element (previously, you could bind to either.) [details](guide/ivy-compatibility-examples#select-value-binding)
* Embedded views (such as ones created by `*ngFor`) are now inserted in front of anchor DOM comment node (e.g. `<!--ng-for-of-->`) rather than behind it as was the case previously.
In most cases this does not have any impact on rendered DOM.
In some cases (such as animations delaying the removal of an embedded view) any new embedded views will be inserted after the embedded view being animated away.
This difference only last while the animation is active, and might alter the visual appearance of the animation.
Once the animation is finished the resulting rendered DOM is identical to that rendered with View Engine.

View File

@ -54,17 +54,13 @@ See [Keeping Up-to-Date](guide/updating "Updating your projects") for more infor
{@a previews}
### Preview releases
We let you preview what's coming by providing Beta releases and Release Candidates (`rc`) for each major and minor release:
We let you preview what's coming by providing "Next" and Release Candidates (`rc`) pre-releases for each major and minor release:
<!--
* **Next:** The release that is under active development. The next release is indicated by a release tag appended with the `next` identifier, such as `8.1.0-next.0`. For the next version of the documentation, see [next.angular.io](https://next.angular.io).
-->
* **Next:** The release that is under active development and testing. The next release is indicated by a release tag appended with the `-next` identifier, such as `8.1.0-next.0`.
* **Beta:** A release that is under active development and testing. A Beta release is indicated by a release tag appended with the `beta` identifier, such as `8.0.0-beta.0`.
* **Release candidate:** A release that is feature complete and in final testing. A release candidate is indicated by a release tag appended with the `-rc` identifier, such as version `8.1.0-rc.0`.
* **Release candidate:** A release that is feature complete and in final testing. A release candidate is indicated by a release tag appended with the `rc` identifier, such as version `8.1.0-rc`.
The next version of the documentation is available at [next.angular.io](https://next.angular.io). This includes any documentation for Beta or Release Candidate features and APIs.
The latest `next` or `rc` pre-release version of the documentation is available at [next.angular.io](https://next.angular.io).
{@a frequency}
@ -72,36 +68,21 @@ The next version of the documentation is available at [next.angular.io](https://
We work toward a regular schedule of releases, so that you can plan and coordinate your updates with the continuing evolution of Angular.
<div class="alert is-helpful">
Disclaimer: Dates are offered as general guidance and will be adjusted by us when necessary to ensure delivery of a high-quality platform.
</div>
In general, you can expect the following release cycle:
* A major release every 6 months
* 1-3 minor releases for each major release
* A patch release almost every week
This cadence of releases gives you access to new features as soon as they are ready, while maintaining the stability and reliability of the platform for production users.
{@a schedule}
## Release schedule
<div class="alert is-helpful">
Disclaimer: The dates are offered as general guidance and may be adjusted by us when necessary to ensure delivery of a high-quality platform.
</div>
The following table contains our current target release dates for the next two major versions of Angular:
Date | Stable Release | Compatibility
---------------------- | -------------- | -------------
October/November 2019 | 9.0.0 | ^8.0.0
May 2020 | 10.0.0 | ^9.0.0
Compatibility note: The primary goal of the backward compatibility promise is to ensure that changes in the core framework and tooling don't break the existing ecosystem of components and applications and don't put undue upgrade/migration burden on Angular application and component authors.
* A patch release and pre-release (`next` or `rc`) build almost every week
This cadence of releases gives eager developers access to new features as soon as they are fully developed and pass through our code review and integration testing processes, while maintaining the stability and reliability of the platform for production users that prefer to receive features after they have been validated by Google and other developers that use the pre-release builds.
@ -142,7 +123,7 @@ To help ensure that you have sufficient time and a clear path to update, this is
* **Announcement:** We announce deprecated APIs and features in the [change log](https://github.com/angular/angular/blob/master/CHANGELOG.md "Angular change log"). Deprecated APIs appear in the [documentation](api?status=deprecated) with ~~strikethrough.~~ When we announce a deprecation, we also announce a recommended update path. For convenience, [Deprecations](guide/deprecations) contains a summary of deprecated APIs and features.
* **Deprecation period:** When an API or a feature is deprecated, it will still be present in the [next two major releases](#schedule). After that, deprecated APIs and features will be candidates for removal. A deprecation can be announced in any release, but the removal of a deprecated API or feature will happen only in major release. Until a deprecated API or feature is removed, it will be maintained according to the LTS support policy, meaning that only critical and security issues will be fixed.
* **Deprecation period:** When an API or a feature is deprecated, it will still be present in the next two major releases. After that, deprecated APIs and features will be candidates for removal. A deprecation can be announced in any release, but the removal of a deprecated API or feature will happen only in major release. Until a deprecated API or feature is removed, it will be maintained according to the LTS support policy, meaning that only critical and security issues will be fixed.
* **npm dependencies:** We only make npm dependency updates that require changes to your apps in a major release.

View File

@ -67,7 +67,7 @@ The `<router-outlet>` container has an attribute directive that contains data ab
<code-example path="animations/src/app/app.component.ts" header="src/app/app.component.ts" region="prepare-router-outlet" language="typescript"></code-example>
Here, the `prepareRoute()` method takes the value of the output directive (established through `#outlet="outlet"`) and returns a string value representing the state of the animation based on the custom data of the current active route. You can use this data to control which transition to execute for each route.
Here, the `prepareRoute()` method takes the value of the outlet directive (established through `#outlet="outlet"`) and returns a string value representing the state of the animation based on the custom data of the current active route. You can use this data to control which transition to execute for each route.
## Animation definition
@ -107,7 +107,7 @@ Use the `query()` method to find and animate elements within the current host co
Let's assume that we are routing from the *Home => About*.
<code-example path="animations/src/app/animations.ts" header="src/app/animations.ts" region="query" language="typescript"></code-example>
<code-example path="animations/src/app/animations.ts" header="src/app/animations.ts (Continuation from above)" region="query" language="typescript"></code-example>
The animation code does the following after styling the views:

View File

@ -3302,7 +3302,13 @@ Although it doesn't actually log in, it has what you need for this discussion.
It has an `isLoggedIn` flag to tell you whether the user is authenticated.
Its `login` method simulates an API call to an external service by returning an
observable that resolves successfully after a short pause.
The `redirectUrl` property will store the attempted URL so you can navigate to it after authenticating.
The `redirectUrl` property stores the URL that the user wanted to access so you can navigate to it after authentication.
<div class="alert is-helpful">
To keep things simple, this example redirects unauthenticated users to `/admin`.
</div>
Revise the `AuthGuard` to call it.

View File

@ -117,7 +117,7 @@ You will see:
<div class="alert is-helpful">
Getting Started assumes the [StackBlitz](https://stackblitz.com/) online development environment.
To learn how to export an app from StackBlitz to your local environment, skip ahead to the [Deployment](start/deployment "Getting Started: Deployment") section.
To learn how to export an app from StackBlitz to your local environment, skip ahead to the [Deployment](start/start-deployment "Getting Started: Deployment") section.
</div>

View File

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

View File

@ -237,16 +237,15 @@ You're free to change anything, anywhere, during this turn of the event loop.
Like template expressions, template *statements* use a language that looks like JavaScript.
The template statement parser differs from the template expression parser and
specifically supports both basic assignment (`=`) and chaining expressions
(with <code>;</code> or <code>,</code>).
specifically supports both basic assignment (`=`) and chaining expressions with <code>;</code>.
However, certain JavaScript syntax is not allowed:
However, certain JavaScript and template expression syntax is not allowed:
* <code>new</code>
* increment and decrement operators, `++` and `--`
* operator assignment, such as `+=` and `-=`
* the bitwise operators `|` and `&`
* the [template expression operators](guide/template-syntax#expression-operators)
* the bitwise operators, such as `|` and `&`
* the [pipe operator](guide/template-syntax#pipe)
### Statement context
@ -731,11 +730,11 @@ As you can see here, the `parentItem` in `AppComponent` is a string, which the `
The previous simple example showed passing in a string. To pass in an object,
the syntax and thinking are the same.
In this scenario, `ListItemComponent` is nested within `AppComponent` and the `item` property expects an object.
In this scenario, `ListItemComponent` is nested within `AppComponent` and the `items` property expects an array of objects.
<code-example path="property-binding/src/app/app.component.html" region="pass-object" header="src/app/app.component.html"></code-example>
The `item` property is declared in the `ListItemComponent` with a type of `Item` and decorated with `@Input()`:
The `items` property is declared in the `ListItemComponent` with a type of `Item` and decorated with `@Input()`:
<code-example path="property-binding/src/app/list-item/list-item.component.ts" region="item-input" header="src/app/list-item.component.ts"></code-example>
@ -748,7 +747,7 @@ specify a different item in `app.component.ts` so that the new item will render:
<code-example path="property-binding/src/app/app.component.ts" region="pass-object" header="src/app.component.ts"></code-example>
You just have to make sure, in this case, that you're supplying an object because that's the type of `item` and is what the nested component, `ListItemComponent`, expects.
You just have to make sure, in this case, that you're supplying an array of objects because that's the type of `items` and is what the nested component, `ListItemComponent`, expects.
In this example, `AppComponent` specifies a different `item` object
(`currentItem`) and passes it to the nested `ListItemComponent`. `ListItemComponent` was able to use `currentItem` because it matches what an `Item` object is according to `item.ts`. The `item.ts` file is where
@ -892,58 +891,97 @@ Instead, you'd use property binding and write it like this:
### Class binding
Add and remove CSS class names from an element's `class` attribute with
a **class binding**.
Here's how to set the attribute without binding in plain HTML:
Here's how to set the `class` attribute without a binding in plain HTML:
```html
<!-- standard class attribute setting -->
<div class="item clearance special">Item clearance special</div>
<div class="foo bar">Some text</div>
```
Class binding syntax resembles property binding, but instead of an element property between brackets, start with the prefix `class`,
optionally followed by a dot (`.`) and the name of a CSS class: `[class.class-name]`.
You can also add and remove CSS class names from an element's `class` attribute with a **class binding**.
You can replace that with a binding to a string of the desired class names; this is an all-or-nothing, replacement binding.
To create a single class binding, start with the prefix `class` followed by a dot (`.`) and the name of the CSS class (for example, `[class.foo]="hasFoo"`).
Angular adds the class when the bound expression is truthy, and it removes the class when the expression is falsy (with the exception of `undefined`, see [styling delegation](#styling-delegation)).
To create a binding to multiple classes, use a generic `[class]` binding without the dot (for example, `[class]="classExpr"`).
The expression can be a space-delimited string of class names, or you can format it as an object with class names as the keys and truthy/falsy expressions as the values.
With object format, Angular will add a class only if its associated value is truthy.
It's important to note that with any object-like expression (`object`, `Array`, `Map`, `Set`, etc), the identity of the object must change for the class list to be updated.
Updating the property without changing object identity will have no effect.
If there are multiple bindings to the same class name, conflicts are resolved using [styling precedence](#styling-precedence).
<style>
td, th {vertical-align: top}
</style>
<table width="100%">
<col width="15%">
</col>
<col width="20%">
</col>
<col width="35%">
</col>
<col width="30%">
</col>
<tr>
<th>
Binding Type
</th>
<th>
Syntax
</th>
<th>
Input Type
</th>
<th>
Example Input Values
</th>
</tr>
<tr>
<td>Single class binding</td>
<td><code>[class.foo]="hasFoo"</code></td>
<td><code>boolean | undefined | null</code></td>
<td><code>true</code>, <code>false</code></td>
</tr>
<tr>
<td rowspan=3>Multi-class binding</td>
<td rowspan=3><code>[class]="classExpr"</code></td>
<td><code>string</code></td>
<td><code>"my-class-1 my-class-2 my-class-3"</code></td>
</tr>
<tr>
<td><code>{[key: string]: boolean | undefined | null}</code></td>
<td><code>{foo: true, bar: false}</code></td>
</tr>
<tr>
<td><code>Array</code><<code>string</code>></td>
<td><code>['foo', 'bar']</code></td>
</tr>
</table>
<code-example path="attribute-binding/src/app/app.component.html" region="class-override" header="src/app/app.component.html"></code-example>
You can also add a class to an element without overwriting the classes already on the element:
<code-example path="attribute-binding/src/app/app.component.html" region="add-class" header="src/app/app.component.html"></code-example>
Finally, you can bind to a specific class name.
Angular adds the class when the template expression evaluates to truthy.
It removes the class when the expression is falsy.
<code-example path="attribute-binding/src/app/app.component.html" region="is-special" header="src/app/app.component.html"></code-example>
While this technique is suitable for toggling a single class name,
consider the [`NgClass`](guide/template-syntax#ngClass) directive when
managing multiple class names at the same time.
The [NgClass](#ngclass) directive can be used as an alternative to direct `[class]` bindings.
However, using the above class binding syntax without `NgClass` is preferred because due to improvements in class binding in Angular, `NgClass` no longer provides significant value, and might eventually be removed in the future.
<hr/>
### Style binding
You can set inline styles with a **style binding**.
Here's how to set the `style` attribute without a binding in plain HTML:
Style binding syntax resembles property binding.
Instead of an element property between brackets, start with the prefix `style`,
followed by a dot (`.`) and the name of a CSS style property: `[style.style-property]`.
```html
<!-- standard style attribute setting -->
<div style="color: blue">Some text</div>
```
<code-example path="attribute-binding/src/app/app.component.html" region="style-binding" header="src/app/app.component.html"></code-example>
You can also set styles dynamically with a **style binding**.
Some style binding styles have a unit extension.
The following example conditionally sets the font size in “em” and “%” units.
<code-example path="attribute-binding/src/app/app.component.html" region="style-binding-condition" header="src/app/app.component.html"></code-example>
This technique is suitable for setting a single style, but consider
the [`NgStyle`](guide/template-syntax#ngStyle) directive when setting several inline styles at the same time.
To create a single style binding, start with the prefix `style` followed by a dot (`.`) and the name of the CSS style property (for example, `[style.width]="width"`).
The property will be set to the value of the bound expression, which is normally a string.
Optionally, you can add a unit extension like `em` or `%`, which requires a number type.
<div class="alert is-helpful">
@ -953,8 +991,140 @@ Note that a _style property_ name can be written in either
</div>
If there are multiple styles you'd like to toggle, you can bind to the `[style]` property directly without the dot (for example, `[style]="styleExpr"`).
The expression attached to the `[style]` binding is most often a string list of styles like `"width: 100px; height: 100px;"`.
You can also format the expression as an object with style names as the keys and style values as the values, like `{width: '100px', height: '100px'}`.
It's important to note that with any object-like expression (`object`, `Array`, `Map`, `Set`, etc), the identity of the object must change for the class list to be updated.
Updating the property without changing object identity will have no effect.
If there are multiple bindings to the same style property, conflicts are resolved using [styling precedence rules](#styling-precedence).
<style>
td, th {vertical-align: top}
</style>
<table width="100%">
<col width="15%">
</col>
<col width="20%">
</col>
<col width="35%">
</col>
<col width="30%">
</col>
<tr>
<th>
Binding Type
</th>
<th>
Syntax
</th>
<th>
Input Type
</th>
<th>
Example Input Values
</th>
</tr>
<tr>
<td>Single style binding</td>
<td><code>[style.width]="width"</code></td>
<td><code>string | undefined | null</code></td>
<td><code>"100px"</code></td>
</tr>
<tr>
<tr>
<td>Single style binding with units</td>
<td><code>[style.width.px]="width"</code></td>
<td><code>number | undefined | null</code></td>
<td><code>100</code></td>
</tr>
<tr>
<td rowspan=3>Multi-style binding</td>
<td rowspan=3><code>[style]="styleExpr"</code></td>
<td><code>string</code></td>
<td><code>"width: 100px; height: 100px"</code></td>
</tr>
<tr>
<td><code>{[key: string]: string | undefined | null}</code></td>
<td><code>{width: '100px', height: '100px'}</code></td>
</tr>
<tr>
<td><code>Array</code><<code>string</code>></td>
<td><code>['width', '100px']</code></td>
</tr>
</table>
The [NgStyle](#ngstyle) directive can be used as an alternative to direct `[style]` bindings.
However, using the above style binding syntax without `NgStyle` is preferred because due to improvements in style binding in Angular, `NgStyle` no longer provides significant value, and might eventually be removed in the future.
<hr/>
{@a styling-precedence}
### Styling Precedence
A single HTML element can have its CSS class list and style values bound to a multiple sources (for example, host bindings from multiple directives).
When there are multiple bindings to the same class name or style property, Angular uses a set of precedence rules to resolve conflicts and determine which classes or styles are ultimately applied to the element.
<div class="alert is-helpful">
<h4>Styling precedence (highest to lowest)</h4>
1. Template bindings
1. Property binding (for example, `<div [class.foo]="hasFoo">` or `<div [style.color]="color">`)
1. Map binding (for example, `<div [class]="classExpr">` or `<div [style]="styleExpr">`)
1. Static value (for example, `<div class="foo">` or `<div style="color: blue">`)
1. Directive host bindings
1. Property binding (for example, `host: {'[class.foo]': 'hasFoo'}` or `host: {'[style.color]': 'color'}`)
1. Map binding (for example, `host: {'[class]': 'classExpr'}` or `host: {'[style]': 'styleExpr'}`)
1. Static value (for example, `host: {'class': 'foo'}` or `host: {'style': 'color: blue'}`)
1. Component host bindings
1. Property binding (for example, `host: {'[class.foo]': 'hasFoo'}` or `host: {'[style.color]': 'color'}`)
1. Map binding (for example, `host: {'[class]': 'classExpr'}` or `host: {'[style]': 'styleExpr'}`)
1. Static value (for example, `host: {'class': 'foo'}` or `host: {'style': 'color: blue'}`)
</div>
The more specific a class or style binding is, the higher its precedence.
A binding to a specific class (for example, `[class.foo]`) will take precedence over a generic `[class]` binding, and a binding to a specific style (for example, `[style.bar]`) will take precedence over a generic `[style]` binding.
<code-example path="attribute-binding/src/app/app.component.html" region="basic-specificity" header="src/app/app.component.html"></code-example>
Specificity rules also apply when it comes to bindings that originate from different sources.
It's possible for an element to have bindings in the template where it's declared, from host bindings on matched directives, and from host bindings on matched components.
Template bindings are the most specific because they apply to the element directly and exclusively, so they have the highest precedence.
Directive host bindings are considered less specific because directives can be used in multiple locations, so they have a lower precedence than template bindings.
Directives often augment component behavior, so host bindings from components have the lowest precedence.
<code-example path="attribute-binding/src/app/app.component.html" region="source-specificity" header="src/app/app.component.html"></code-example>
In addition, bindings take precedence over static attributes.
In the following case, `class` and `[class]` have similar specificity, but the `[class]` binding will take precedence because it is dynamic.
<code-example path="attribute-binding/src/app/app.component.html" region="dynamic-priority" header="src/app/app.component.html"></code-example>
{@a styling-delegation}
### Delegating to styles with lower precedence
It is possible for higher precedence styles to "delegate" to lower precedence styles using `undefined` values.
Whereas setting a style property to `null` ensures the style is removed, setting it to `undefined` will cause Angular to fall back to the next-highest precedence binding to that style.
For example, consider the following template:
<code-example path="attribute-binding/src/app/app.component.html" region="style-delegation" header="src/app/app.component.html"></code-example>
Imagine that the `dirWithHostBinding` directive and the `comp-with-host-binding` component both have a `[style.width]` host binding.
In that case, if `dirWithHostBinding` sets its binding to `undefined`, the `width` property will fall back to the value of the `comp-with-host-binding` host binding.
However, if `dirWithHostBinding` sets its binding to `null`, the `width` property will be removed entirely.
{@a event-binding}
## Event binding `(event)`

View File

@ -121,6 +121,7 @@ In case of a false positive like these, there are a few options:
|`strictOutputEventTypes`|Whether `$event` will have the correct type for event bindings to component/directive an `@Output()`, or to animation events. If disabled, it will be `any`.|
|`strictDomEventTypes`|Whether `$event` will have the correct type for event bindings to DOM events. If disabled, it will be `any`.|
|`strictContextGenerics`|Whether the type parameters of generic components will be inferred correctly (including any generic bounds). If disabled, any type parameters will be `any`.|
|`strictLiteralTypes`|Whether object and array literals declared in the template will have their type inferred. If disabled, the type of such literals will be `any`.|
If you still have issues after troubleshooting with these flags, you can fall back to full mode by disabling `strictTemplates`.

View File

@ -620,8 +620,8 @@ It also generates an initial test file for the component, `banner-external.compo
<div class="alert is-helpful">
Because `compileComponents` is asynchronous, it uses
the [`async`](api/core/testing/async) utility
Because `compileComponents` is asynchronous, it uses
the [`async`](api/core/testing/async) utility
function imported from `@angular/core/testing`.
Please refer to the [async](#async) section for more details.
@ -1261,21 +1261,38 @@ XHR calls within a test are rare, but if you need to call XHR, see [`async()`](#
#### The _tick()_ function
You do have to call `tick()` to advance the (virtual) clock.
You do have to call [tick()](api/core/testing/tick) to advance the (virtual) clock.
Calling `tick()` simulates the passage of time until all pending asynchronous activities finish.
Calling [tick()](api/core/testing/tick) simulates the passage of time until all pending asynchronous activities finish.
In this case, it waits for the error handler's `setTimeout()`.
The `tick()` function accepts milliseconds as a parameter (defaults to 0 if not provided). The parameter represents how much the virtual clock advances. For example, if you have a `setTimeout(fn, 100)` in a `fakeAsync()` test, you need to use tick(100) to trigger the fn callback.
The [tick()](api/core/testing/tick) function accepts milliseconds and tickOptions as parameters, the millisecond (defaults to 0 if not provided) parameter represents how much the virtual clock advances. For example, if you have a `setTimeout(fn, 100)` in a `fakeAsync()` test, you need to use tick(100) to trigger the fn callback. The tickOptions is an optional parameter with a property called processNewMacroTasksSynchronously (defaults is true) represents whether to invoke
new generated macro tasks when ticking.
<code-example
path="testing/src/app/demo/async-helper.spec.ts"
region="fake-async-test-tick">
</code-example>
The `tick()` function is one of the Angular testing utilities that you import with `TestBed`.
The [tick()](api/core/testing/tick) function is one of the Angular testing utilities that you import with `TestBed`.
It's a companion to `fakeAsync()` and you can only call it within a `fakeAsync()` body.
#### tickOptions
<code-example
path="testing/src/app/demo/async-helper.spec.ts"
region="fake-async-test-tick-new-macro-task-sync">
</code-example>
In this example, we have a new macro task (nested setTimeout), by default, when we `tick`, the setTimeout `outside` and `nested` will both be triggered.
<code-example
path="testing/src/app/demo/async-helper.spec.ts"
region="fake-async-test-tick-new-macro-task-async">
</code-example>
And in some case, we don't want to trigger the new maco task when ticking, we can use `tick(milliseconds, {processNewMacroTasksSynchronously: false})` to not invoke new maco task.
#### Comparing dates inside fakeAsync()
`fakeAsync()` simulates passage of time, which allows you to calculate the difference between dates inside `fakeAsync()`.
@ -1422,7 +1439,7 @@ in the real world.
Notice that the quote element displays the placeholder value (`'...'`) after `ngOnInit()`.
The first quote hasn't arrived yet.
To flush the first quote from the observable, you call `tick()`.
To flush the first quote from the observable, you call [tick()](api/core/testing/tick).
Then call `detectChanges()` to tell Angular to update the screen.
Then you can assert that the quote element displays the expected text.
@ -1468,7 +1485,7 @@ When using an `intervalTimer()` such as `setInterval()` in `async()`, remember t
#### _whenStable_
The test must wait for the `getQuote()` observable to emit the next quote.
Instead of calling `tick()`, it calls `fixture.whenStable()`.
Instead of calling [tick()](api/core/testing/tick), it calls `fixture.whenStable()`.
The `fixture.whenStable()` returns a promise that resolves when the JavaScript engine's
task queue becomes empty.
@ -1577,7 +1594,7 @@ you tell the `TestScheduler` to _flush_ its queue of prepared tasks like this.
path="testing/src/app/twain/twain.component.marbles.spec.ts"
region="test-scheduler-flush"></code-example>
This step serves a purpose analogous to `tick()` and `whenStable()` in the
This step serves a purpose analogous to [tick()](api/core/testing/tick) and `whenStable()` in the
earlier `fakeAsync()` and `async()` examples.
The balance of the test is the same as those examples.
@ -1589,7 +1606,7 @@ Here's the marble testing version of the `getQuote()` error test.
path="testing/src/app/twain/twain.component.marbles.spec.ts"
region="error-test"></code-example>
It's still an async test, calling `fakeAsync()` and `tick()`, because the component itself
It's still an async test, calling `fakeAsync()` and [tick()](api/core/testing/tick), because the component itself
calls `setTimeout()` when processing errors.
Look at the marble observable definition.
@ -3582,13 +3599,13 @@ The Angular `By` class has three static methods for common predicates:
<hr>
{@a faq}
{@a useful-tips}
## Frequently Asked Questions
## Useful tips
{@a q-spec-file-location}
#### Why put spec file next to the file it tests?
#### Place your spec file next to the file it tests
It's a good idea to put unit test spec files in the same folder
as the application source code files that they test:
@ -3599,11 +3616,9 @@ as the application source code files that they test:
- When you move the source (inevitable), you remember to move the test.
- When you rename the source file (inevitable), you remember to rename the test file.
<hr>
{@a q-specs-in-test-folder}
#### When would I put specs in a test folder?
#### Place your spec files in a test folder
Application integration specs can test the interactions of multiple parts
spread across folders and modules.
@ -3615,15 +3630,17 @@ It's often better to create an appropriate folder for them in the `tests` direct
Of course specs that test the test helpers belong in the `test` folder,
next to their corresponding helper files.
{@a q-e2e}
{@a q-kiss}
#### Why not rely on E2E tests of DOM integration?
#### Keep it simple
The component DOM tests described in this guide often require extensive setup and
advanced techniques whereas the [unit tests](#component-class-testing)
are comparatively simple.
[Component class testing](#component-class-testing) should be kept very clean and simple.
It should test only a single unit. On a first glance, you should be able to understand
what the test is testing. If it's doing more, then it doesn't belong here.
#### Why not defer DOM integration tests to end-to-end (E2E) testing?
{@a q-end-to-end}
#### Use E2E (end-to-end) to test more than a single unit
E2E tests are great for high-level validation of the entire system.
But they can't give you the comprehensive test coverage that you'd expect from unit tests.

View File

@ -2,7 +2,8 @@
You learned the basics of Angular animations in the [introduction](guide/animations) page.
In this guide, we go into greater depth on special transition states such as `*` (wildcard) and `void`, and show how these special states are used for elements entering and leaving a view. The chapter also explores multiple animation triggers, animation callbacks and sequence-based animation using keyframes.
This guide goes into greater depth on special transition states such as `*` (wildcard) and `void`, and show how these special states are used for elements entering and leaving a view.
This chapter also explores multiple animation triggers, animation callbacks, and sequence-based animation using keyframes.
## Predefined states and wildcard matching
@ -18,7 +19,8 @@ For example, a transition of `open => *` applies when the element's state change
<img src="generated/images/guide/animations/wildcard-state-500.png" alt="wildcard state expressions">
</div>
Here's another code sample using the wildcard state together with our previous example using the `open` and `closed` states. Instead of defining each state-to-state transition pair, we're now saying that any transition to `closed` takes 1 second, and any transition to `open` takes 0.5 seconds.
The following is another code sample using the wildcard state together with the previous example using the `open` and `closed` states.
Instead of defining each state-to-state transition pair, any transition to `closed` takes 1 second, and any transition to `open` takes 0.5 seconds.
This allows us to add new states without having to include separate transitions for each one.
@ -30,7 +32,9 @@ Use a double arrow syntax to specify state-to-state transitions in both directio
### Using wildcard state with multiple transition states
In our two-state button example, the wildcard isn't that useful because there are only two possible states, `open` and `closed`. Wildcard states are better when an element in one particular state has multiple potential states that it can change to. If our button can change from `open` to either `closed` or something like `inProgress`, using a wildcard state could reduce the amount of coding needed.
In the two-state button example, the wildcard isn't that useful because there are only two possible states, `open` and `closed`.
Wildcard states are better when an element in one particular state has multiple potential states that it can change to.
If the button can change from `open` to either `closed` or something like `inProgress`, using a wildcard state could reduce the amount of coding needed.
<div class="lightbox">
<img src="generated/images/guide/animations/wildcard-3-states.png" alt="wildcard state with 3 states">
@ -73,18 +77,18 @@ This section shows how to animate elements entering or leaving a page.
<div class="alert is-helpful">
**Note:** For our purposes, an element entering or leaving a view is equivalent to being inserted or removed from the DOM.
**Note:** For this example, an element entering or leaving a view is equivalent to being inserted or removed from the DOM.
</div>
Now we'll add a new behavior:
Now add a new behavior:
* When you add a hero to the list of heroes, it appears to fly onto the page from the left.
* When you remove a hero from the list, it appears to fly out to the right.
<code-example path="animations/src/app/hero-list-enter-leave.component.ts" header="src/app/hero-list-enter-leave.component.ts" region="animationdef" language="typescript"></code-example>
In the above code, we applied the `void` state when the HTML element isn't attached to a view.
In the above code, you applied the `void` state when the HTML element isn't attached to a view.
{@a enter-leave-view}
@ -105,7 +109,7 @@ So, use the aliases `:enter` and `:leave` to target HTML elements that are inser
The `:enter` transition runs when any `*ngIf` or `*ngFor` views are placed on the page, and `:leave` runs when those views are removed from the page.
In this example, we have a special trigger for the enter and leave animation called `myInsertRemoveTrigger`. The HTML template contains the following code.
This example has a special trigger for the enter and leave animation called `myInsertRemoveTrigger`. The HTML template contains the following code.
<code-example path="animations/src/app/insert-remove.component.html" header="src/app/insert-remove.component.html" region="insert-remove" language="typescript">
</code-example>
@ -169,11 +173,13 @@ The code sample below shows how to use this feature.
When the `@.disabled` binding is true, the `@childAnimation` trigger doesn't kick off.
When an element within an HTML template has animations disabled using the `@.disabled` host binding, animations are disabled on all inner elements as well. You can't selectively disable multiple animations on a single element.
When an element within an HTML template has animations disabled using the `@.disabled` host binding, animations are disabled on all inner elements as well.
You can't selectively disable multiple animations on a single element.
However, selective child animations can still be run on a disabled parent in one of the following ways:
* A parent animation can use the [`query()`](https://angular.io/api/animations/query) function to collect inner elements located in disabled areas of the HTML template. Those elements can still animate.
* A parent animation can use the [`query()`](https://angular.io/api/animations/query) function to collect inner elements located in disabled areas of the HTML template.
Those elements can still animate.
* A subanimation can be queried by a parent and then later animated with the `animateChild()` function.
@ -190,22 +196,27 @@ To disable all animations for an Angular app, place the `@.disabled` host bindin
## Animation callbacks
The animation `trigger()` function emits *callbacks* when it starts and when it finishes. In the example below we have a component that contains an `openClose` trigger.
The animation `trigger()` function emits *callbacks* when it starts and when it finishes. The example below features a component that contains an `openClose` trigger.
<code-example path="animations/src/app/open-close.component.ts" header="src/app/open-close.component.ts" region="events1" language="typescript"></code-example>
In the HTML template, the animation event is passed back via `$event`, as `@trigger.start` and `@trigger.done`, where `trigger` is the name of the trigger being used. In our example, the trigger `openClose` appears as follows.
In the HTML template, the animation event is passed back via `$event`, as `@trigger.start` and `@trigger.done`, where `trigger` is the name of the trigger being used.
In this example, the trigger `openClose` appears as follows.
<code-example path="animations/src/app/open-close.component.3.html" header="src/app/open-close.component.html" region="callbacks">
</code-example>
A potential use for animation callbacks could be to cover for a slow API call, such as a database lookup. For example, you could set up the **InProgress** button to have its own looping animation where it pulsates or does some other visual motion while the backend system operation finishes.
A potential use for animation callbacks could be to cover for a slow API call, such as a database lookup.
For example, you could set up the **InProgress** button to have its own looping animation where it pulsates or does some other visual motion while the backend system operation finishes.
Then, another animation can be called when the current animation finishes. For example, the button goes from the `inProgress` state to the `closed` state when the API call is completed.
Then, another animation can be called when the current animation finishes.
For example, the button goes from the `inProgress` state to the `closed` state when the API call is completed.
An animation can influence an end user to *perceive* the operation as faster, even when it isn't. Thus, a simple animation can be a cost-effective way to keep users happy, rather than seeking to improve the speed of a server call and having to compensate for circumstances beyond your control, such as an unreliable network connection.
An animation can influence an end user to *perceive* the operation as faster, even when it isn't.
Thus, a simple animation can be a cost-effective way to keep users happy, rather than seeking to improve the speed of a server call and having to compensate for circumstances beyond your control, such as an unreliable network connection.
Callbacks can serve as a debugging tool, for example in conjunction with `console.warn()` to view the application's progress in a browser's Developer JavaScript Console. The following code snippet creates console log output for our original example, a button with the two states of `open` and `closed`.
Callbacks can serve as a debugging tool, for example in conjunction with `console.warn()` to view the application's progress in a browser's Developer JavaScript Console.
The following code snippet creates console log output for the original example, a button with the two states of `open` and `closed`.
<code-example path="animations/src/app/open-close.component.ts" header="src/app/open-close.component.ts" region="events" language="typescript"></code-example>
@ -213,9 +224,10 @@ Callbacks can serve as a debugging tool, for example in conjunction with `consol
## Keyframes
In the previous section, we saw a simple two-state transition. Now we'll create an animation with multiple steps run in sequence using *keyframes*.
The previous section features a simple two-state transition. Now create an animation with multiple steps run in sequence using *keyframes*.
Angular's `keyframe()` function is similar to keyframes in CSS. Keyframes allow several style changes within a single timing segment. For example, our button, instead of fading, could change color several times over a single 2-second timespan.
Angular's `keyframe()` function is similar to keyframes in CSS. Keyframes allow several style changes within a single timing segment.
For example, the button, instead of fading, could change color several times over a single 2-second timespan.
<div class="lightbox">
<img src="generated/images/guide/animations/keyframes-500.png" alt="keyframes">
@ -227,9 +239,13 @@ The code for this color change might look like this.
### Offset
Keyframes include an *offset* that defines the point in the animation where each style change occurs. Offsets are relative measures from zero to one, marking the beginning and end of the animation, respectively and should be applied to each of the keyframe's steps if used at least once.
Keyframes include an *offset* that defines the point in the animation where each style change occurs.
Offsets are relative measures from zero to one, marking the beginning and end of the animation, respectively and should be applied to each of the keyframe's steps if used at least once.
Defining offsets for keyframes is optional. If you omit them, evenly spaced offsets are automatically assigned. For example, three keyframes without predefined offsets receive offsets of 0, 0.5, and 1. Specifying an offset of 0.8 for the middle transition in the above example might look like this.
Defining offsets for keyframes is optional.
If you omit them, evenly spaced offsets are automatically assigned.
For example, three keyframes without predefined offsets receive offsets of 0, 0.5, and 1.
Specifying an offset of 0.8 for the middle transition in the above example might look like this.
<div class="lightbox">
<img src="generated/images/guide/animations/keyframes-offset-500.png" alt="keyframes with offset">
@ -248,9 +264,9 @@ Use keyframes to create a pulse effect in your animations by defining styles at
Here's an example of using keyframes to create a pulse effect:
* The original `open` and `closed` states, with the original changes in height, color, and opacity, occurring over a timeframe of 1 second
* The original `open` and `closed` states, with the original changes in height, color, and opacity, occurring over a timeframe of 1 second.
* A keyframes sequence inserted in the middle that causes the button to appear to pulsate irregularly over the course of that same 1-second timeframe
* A keyframes sequence inserted in the middle that causes the button to appear to pulsate irregularly over the course of that same 1-second timeframe.
<div class="lightbox">
<img src="generated/images/guide/animations/keyframes-pulsation.png" alt="keyframes with irregular pulsation">
@ -262,7 +278,8 @@ The code snippet for this animation might look like this.
### Animatable properties and units
Angular's animation support builds on top of web animations, so you can animate any property that the browser considers animatable. This includes positions, sizes, transforms, colors, borders, and more. The W3C maintains a list of animatable properties on its [CSS Transitions](https://www.w3.org/TR/css-transitions-1/) page.
Angular's animation support builds on top of web animations, so you can animate any property that the browser considers animatable.
This includes positions, sizes, transforms, colors, borders, and more. The W3C maintains a list of animatable properties on its [CSS Transitions](https://www.w3.org/TR/css-transitions-1/) page.
For positional properties with a numeric value, define a unit by providing the value as a string, in quotes, with the appropriate suffix:
@ -270,15 +287,19 @@ For positional properties with a numeric value, define a unit by providing the v
* Relative font size: `'3em'`
* Percentage: `'100%'`
If you don't provide a unit when specifying dimension, Angular assumes a default unit of pixels, or px. Expressing 50 pixels as `50` is the same as saying `'50px'`.
If you don't provide a unit when specifying dimension, Angular assumes a default unit of pixels, or px.
Expressing 50 pixels as `50` is the same as saying `'50px'`.
### Automatic property calculation with wildcards
Sometimes you don't know the value of a dimensional style property until runtime. For example, elements often have widths and heights that depend on their content and the screen size. These properties are often challenging to animate using CSS.
Sometimes you don't know the value of a dimensional style property until runtime.
For example, elements often have widths and heights that depend on their content and the screen size.
These properties are often challenging to animate using CSS.
In these cases, you can use a special wildcard `*` property value under `style()`, so that the value of that particular style property is computed at runtime and then plugged into the animation.
In this example, we have a trigger called `shrinkOut`, used when an HTML element leaves the page. The animation takes whatever height the element has before it leaves, and animates from that height to zero.
The following example has a trigger called `shrinkOut`, used when an HTML element leaves the page.
The animation takes whatever height the element has before it leaves, and animates from that height to zero.
<code-example path="animations/src/app/hero-list-auto.component.ts" header="src/app/hero-list-auto.component.ts" region="auto-calc" language="typescript"></code-example>

View File

@ -26,7 +26,7 @@ The CLI schematic `@nguniversal/express-engine` performs the required steps, as
The [Tour of Heroes tutorial](tutorial) is the foundation for this walkthrough.
In this example, the Angular CLI compiles and bundles the Universal version of the app with the
[Ahead-of-Time (AoT) compiler](guide/aot-compiler).
[Ahead-of-Time (AOT) compiler](guide/aot-compiler).
A Node Express web server compiles HTML pages with Universal based on client requests.
To create the server-side app module, `app.server.module.ts`, run the following CLI command.
@ -127,8 +127,7 @@ people who otherwise couldn't use the app at all.
### Show the first page quickly
Displaying the first page quickly can be critical for user engagement.
[53 percent of mobile site visits are abandoned](https://www.thinkwithgoogle.com/marketing-resources/data-measurement/mobile-page-speed-new-industry-benchmarks/)
if pages take longer than 3 seconds to load.
Pages that load faster perform better, [even with changes as small as 100ms](https://web.dev/shopping-for-speed-on-ebay/).
Your app may have to launch faster to engage these users before they decide to do something else.
With Angular Universal, you can generate landing pages for the app that look like the complete app.
@ -214,7 +213,7 @@ import {REQUEST} from '@nguniversal/express-engine/tokens';
@Injectable()
export class UniversalInterceptor implements HttpInterceptor {
constructor(@Optional() @Inject(REQUEST) protected request: Request) {}
constructor(@Optional() @Inject(REQUEST) protected request?: Request) {}
intercept(req: HttpRequest<any>, next: HttpHandler) {
let serverReq: HttpRequest<any> = req;

View File

@ -1,6 +1,6 @@
# Updating to Angular version 9
This guide contains everything you need to know about updating to the next Angular version.
This guide contains information related to updating to version 9 of Angular.
## Updating CLI Apps
@ -25,7 +25,7 @@ If you're curious about the specific migrations being run by the CLI, see the [a
Users who only built with JIT before may see new type errors.
See our [template type-checking guide](guide/template-typecheck) for more information and debugging tips.
- Typescript 3.4 and 3.5 are no longer supported. Please update to Typescript 3.6.
- Typescript 3.4 and 3.5 are no longer supported. Please update to Typescript 3.7.
- `tslib` is now listed as a peer dependency rather than a direct dependency. If you are not using the CLI, you must manually install `tslib`, using `yarn add tslib` or `npm install tslib --save`.

View File

@ -68,5 +68,3 @@ For simple updates, the CLI command [`ng update`](cli/update) is all you need. W
* Update command reference: [Angular CLI `ng update` command reference](cli/update)
* Versioning, release, support, and deprecation practices: [Angular versioning and releases](guide/releases "Angular versioning and releases")
* Release schedule: [Angular versioning and releases](guide/releases#schedule "Angular versioning and releases")

View File

@ -539,12 +539,14 @@ of multiple words. In Angular, you would bind these attributes using camelCase:
<code-example format="">
[myHero]="hero"
(heroDeleted)="handleHeroDeleted($event)"
</code-example>
But when using them from AngularJS templates, you must use kebab-case:
<code-example format="">
[my-hero]="hero"
(hero-deleted)="handleHeroDeleted($event)"
</code-example>
</div>
@ -1162,11 +1164,19 @@ Begin by installing TypeScript to the project.
</code-example>
Install type definitions for the existing libraries that
you're using but that don't come with prepackaged types: AngularJS and the
you're using but that don't come with prepackaged types: AngularJS, AngularJS Material, and the
Jasmine unit test framework.
For the PhoneCat app, we can install the necessary type definitions by running the following command:
<code-example format="">
npm install @types/jasmine @types/angular @types/angular-animate @types/angular-cookies @types/angular-mocks @types/angular-resource @types/angular-route @types/angular-sanitize --save-dev
npm install @types/jasmine @types/angular @types/angular-animate @types/angular-aria @types/angular-cookies @types/angular-mocks @types/angular-resource @types/angular-route @types/angular-sanitize --save-dev
</code-example>
If you are using AngularJS Material, you can install the type definitions via:
<code-example format="">
npm install @types/angular-material --save-dev
</code-example>
You should also configure the TypeScript compiler with a `tsconfig.json` in the project directory

418
aio/content/guide/zone.md Normal file
View File

@ -0,0 +1,418 @@
# NgZone
A zone is an execution context that persists across async tasks. You can think of it as [thread-local storage](http://en.wikipedia.org/wiki/Thread-local_storage) for JavaScript VMs.
This guide describes how to use Angular's NgZone to automatically detect changes in the component to update HTML.
## Fundamentals of change detection
To understand the benefits of `NgZone`, it is important to have a clear grasp of what change detection is and how it works.
### Displaying and updating data in Angular
In Angular, you can [display data](guide/displaying-data) by binding controls in an HTML template to the properties of an Angular component.
<code-example path="displaying-data/src/app/app.component.1.ts" header="src/app/app.component.ts"></code-example>
In addition, you can bind DOM events to a method of an Angular component. In such methods, you can also update a property of the Angular component, which updates the corresponding data displayed in the template.
<code-example path="user-input/src/app/click-me.component.ts" region="click-me-component" header="src/app/click-me.component.ts"></code-example>
In both of the above examples, the component's code updates only the property of the component.
However, the HTML is also updated automatically.
This guide describes how and when Angular renders the HTML based on the data from the Angular component.
### Detecting changes with plain JavaScript
To clarify how changes are detected and values updated, consider the following code written in plain JavaScript.
```javascript
<html>
<div id="dataDiv"></div>
<button id="btn">updateData<btn>
<canvas id="canvas"><canvas>
<script>
let value = 'initialValue';
// initial rendering
detectChange();
function renderHTML() {
document.getElementById('dataDiv').innerText = value;
}
function detectChange() {
const currentValue = document.getElementById('dataDiv').innerText;
if (currentValue !== value) {
renderHTML();
}
}
// example 1: update data inside button click event handler
document.getElementById('btn').addEventListener('click', () => {
// update value
value = 'button update value';
// call detectChange manually
detectChange();
});
// example 2: Http Request
const xhr = new XMLHttpRequest();
xhr.addEventListener('load', function() {
// get response from server
value = this.responseText;
// call detectChange manually
detectChange();
});
xhr.open('GET', serverUrl);
xhr.send();
// example 3: setTimeout
setTimeout(() => {
// update value inside setTimeout callback
value = 'timeout update value';
// call detectChange manually
detectChange();
}, 100);
// example 4: Promise.then
Promise.resolve('promise resolved a value').then((v) => {
// update value inside Promise thenCallback
value = v;
// call detectChange manually
detectChange();
}, 100);
// example 5: some other asynchronous APIs
document.getElementById('canvas').toBlob(blob => {
// update value when blob data is created from the canvas
value = `value updated by canvas, size is ${blog.size}`;
// call detectChange manually
detectChange();
});
</script>
</html>
```
After you update the data, you need to call `detectChange()` manually to check whether the data changed.
If the data changed, you render the HTML to reflect the updated data.
In Angular, this step is unnecessary. Whenever you update the data, your HTML is updated automatically.
### When apps update HTML
To understand how change detection works, first consider when the application needs to update the HTML. Typically, updates occur for one of the following reasons:
1. Component initialization. For example, when bootstrapping an Angular application, Angular loads the bootstrap component and triggers the [ApplicationRef.tick()](api/core/ApplicationRef#tick) to call change detection and View Rendering. Just as in the [displaying data](guide/displaying-data) sample, the `AppComponent` is the bootstrap component. This component has the properties `title` and `myHero`, which the application renders in the HTML.
2. Event listener. The DOM event listener can update the data in an Angular component and also trigger change detection, as in the following example.
<code-example path="user-input/src/app/click-me.component.ts" region="click-me-component" header="src/app/click-me.component.ts"></code-example>
3. Http Data Request. You can also get data from a server through an Http request. For example:
```typescript
@Component({
selector: 'app-root',
template: '<div>{{data}}</div>';
})
export class AppComponent implements OnInit {
data = 'initial value';
constructor(private httpClient: HttpClient) {}
ngOnInit() {
this.httpClient.get(serverUrl).subscribe(response => {
// user does not need to trigger change detection manually
data = response.data;
});
}
}
```
4. MacroTasks, such as `setTimeout()`/`setInterval()`. You can also update the data in the callback function of `macroTask` such as `setTimeout()`. For example:
```typescript
@Component({
selector: 'app-root',
template: '<div>{{data}}</div>';
})
export class AppComponent implements OnInit {
data = 'initial value';
ngOnInit() {
setTimeout(() => {
// user does not need to trigger change detection manually
data = 'value updated';
});
}
}
```
5. MicroTask, such as `Promise.then()`. Other asynchronous APIs return a Promise object (such as `fetch`), so the `then()` callback function can also update the data. For example:
```typescript
@Component({
selector: 'app-root',
template: '<div>{{data}}</div>';
})
export class AppComponent implements OnInit {
data = 'initial value';
ngOnInit() {
Promise.resolve(1).then(v => {
// user does not need to trigger change detection manually
data = v;
});
}
}
```
6. Other async operations. In addition to `addEventListener()`/`setTimeout()`/`Promise.then()`, there are other operations that can update the data asynchronously. Some examples include `WebSocket.onmessage()` and `Canvas.toBlob()`.
The preceding list contains most common scenarios in which the application might change the data. Angular runs change detection whenever it detects that data could have changed.
The result of change detection is that DOM is updated with new data. Angular detects the changes in different ways. For component initialization, Angular calls change detection explicitly. For [asynchronous operations](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous), Angular uses a Zone to detect changes in places where the data could have possibly mutated and it runs change detection automatically.
## Zones and execution contexts
A zone provides an execution context that persists across async tasks. [Execution Context](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this) is an abstract concept that holds information about the environment within the current code being executed. Consider the following example.
```javascript
const callback = function() {
console.log('setTimeout callback context is', this);
}
const ctx1 = {
name: 'ctx1'
};
const ctx2 = {
name: 'ctx2'
};
const func = function() {
console.log('caller context is', this);
setTimeout(callback);
}
func.apply(ctx1);
func.apply(ctx2);
```
The value of `this` in the callback of `setTimeout` might differ depending on when `setTimeout` is called.
Thus you can lose the context in asynchronous operations.
A zone provides a new zone context other than `this`, the zone context persists across asynchronous operations.
In the following example, the new zone context is called `zoneThis`.
```javascript
zone.run(() => {
// now you are in a zone
expect(zoneThis).toBe(zone);
setTimeout(function() {
// the zoneThis context will be the same zone
// when the setTimeout is scheduled
expect(zoneThis).toBe(zone);
});
});
```
This new context, `zoneThis`, can be retrieved from the `setTimeout()` callback function, and this context is the same when the `setTimeout()` is scheduled.
To get the context, you can call [`Zone.current`](https://github.com/angular/angular/blob/master/packages/zone.js/lib/zone.ts).
### Zones and async lifecycle hooks
Zone.js can create contexts that persist across asynchronous operations as well as provide lifecycle hooks for asynchronous operations.
```javascript
const zone = Zone.current.fork({
name: 'zone',
onScheduleTask: function(delegate, curr, target, task) {
console.log('new task is scheduled: ', task.type, task.source);
return delegate.scheduleTask(target, task);
},
onInvokeTask: function(delegate, curr, target, task, applyThis, applyArgs) {
console.log('task will be invoked', task.type, task.source);
return delegate.invokeTask(target, task, applyThis, applyArgs);
},
onHasTask: function(delegate, curr, target, hasTaskState) {
console.log('task state changed in the zone', hasTaskState);
return delegate.hasTask(target, hasTaskState);
},
onInvoke: function(delegate, curr, target, callback, applyThis, applyArgs) {
console.log('the callback will be invoked', callback);
return delegate.invoke(target, callback, applyThis, applyArgs);
}
});
zone.run(() => {
setTimeout(() => {
console.log('timeout callback is invoked.');
});
});
```
The above example creates a zone with several hooks.
`onXXXTask` hooks trigger when the status of Task changes.
The Zone Task concept is very similar to the Javascript VM Task concept.
- `macroTask`: such as `setTimeout()`.
- `microTask`: such as `Promise.then()`.
- `eventTask`: such as `element.addEventListener()`.
The `onInvoke` hook triggers when a synchronize function is executed in a Zone.
These hooks trigger under the following circumstances:
- `onScheduleTask`: triggers when a new asynchronous task is scheduled, such as when you call `setTimeout()`.
- `onInvokeTask`: triggers when an asynchronous task is about to execute, such as when the callback of `setTimeout()` is about to execute.
- `onHasTask`: triggers when the status of one kind of task inside a zone changes from stable to unstable or from unstable to stable. A status of stable means there are no tasks inside the Zone, while unstable means a new task is scheduled in the zone.
- `onInvoke`: triggers when a synchronize function is going to execute in the zone.
With these hooks, `Zone` can monitor the status of all synchronize and asynchronous operations inside a zone.
The above example returns the following output.
```
the callback will be invoked () => {
setTimeout(() => {
console.log('timeout callback is invoked.');
});
}
new task is scheduled: macroTask setTimeout
task state changed in the zone { microTask: false,
macroTask: true,
eventTask: false,
change: 'macroTask' }
task will be invoked macroTask setTimeout
timeout callback is invoked.
task state changed in the zone { microTask: false,
macroTask: false,
eventTask: false,
change: 'macroTask' }
```
All of the functions of Zone are provided by a library called [zone.js](https://github.com/angular/angular/tree/master/packages/zone.js/README.md).
This library implements those features by intercepting asynchronous APIs through monkey patching.
Monkey patching is a technique to add or modify the default behavior of a function at runtime without changing the source code.
## NgZone
While Zone.js can monitor all the states of synchronous and asynchronous operations, Angular additionally provides a service called NgZone.
This service creates a zone named `angular` to automatically trigger change detection when the following conditions are satisfied:
1. When a sync or async function is executed.
1. When there is no `microTask` scheduled.
### NgZone `run()`/`runOutsideOfAngular()`
`Zone` handles most asynchronous APIs such as `setTimeout()`, `Promise.then(),and `addEventListener()`.
For the full list, see the [Zone Module document](https://github.com/angular/angular/blob/master/packages/zone.js/MODULE.md).
Therefore in those asynchronous APIs, you don't need to trigger change detection manually.
There are still some third party APIs that Zone does not handle.
In those cases, the NgZone service provides a [`run()`](api/core/NgZone#run) method that allows you to execute a function inside the angular zone.
This function, and all asynchronous operations in that function, trigger change detection automatically at the correct time.
```typescript
export class AppComponent implements OnInit {
constructor(private ngZone: NgZone) {}
ngOnInit() {
// new async API is not handled by Zone, so you need to
// use ngZone.run to make the asynchronous operation in angular zone
// and trigger change detection automatically
this.ngZone.run(() => {
someNewAsyncAPI(() => {
// update data of component
});
});
}
}
```
By default, all asynchronous operations are inside the angular zone, which triggers change detection automatically.
Another common case is when you don't want to trigger change detection.
In that situation, you can use another NgZone method: [runOutsideAngular()](api/core/NgZone#runoutsideangular).
```typescript
export class AppComponent implements OnInit {
constructor(private ngZone: NgZone) {}
ngOnInit() {
// you know no data will be updated
// you don't want to do change detection in this
// specified operation, you can call runOutsideAngular
this.ngZone.runOutsideAngular(() => {
setTimeout(() => {
// do something will not update component data
});
});
}
}
```
### Seting up Zone.js
To make Zone.js available in Angular, you need to import the zone.js package.
If you are using the Angular CLI, this step is done automatically, and you will see the following line in the `src/polyfills.ts`:
```typescript
/***************************************************************************************************
* Zone JS is required by default for Angular itself.
*/
import 'zone.js/dist/zone'; // Included with Angular CLI.
```
Before importing the `zone.js` package, you can set the following configurations:
- You can disable some asynchronous API monkey patching for better performance.
For example, you can disable the `requestAnimationFrame()` monkey patch, so the callback of `requestAnimationFrame()` will not trigger change detection.
This is useful if, in your application, the callback of the `requestAnimationFrame()` will not update any data.
- You can specify that certain DOM events not run inside the angular zone; for example, to prevent a `mousemove` or `scroll` event to trigger change detection.
There are several other settings you can change.
To make these changes, you need to create a `zone-flags.ts` file, such as the following.
```typescript
(window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame
(window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames
```
Next, import `zone-flags` before you import `zone` in the `polyfills.ts`.
```typescript
/***************************************************************************************************
* Zone JS is required by default for Angular.
*/
import `./zone-flags`;
import 'zone.js/dist/zone'; // Included with Angular CLI.
```
For more information of what you can configure, see the [zone.js](https://github.com/angular/angular/tree/master/packages/zone.js) documentation.
### NoopZone
`Zone` helps Angular know when to trigger change detection and let the developers focus on the application development.
By default, `Zone` is loaded and works without additional configuration. However, you don't have to use `Zone` to make Angular work, instead opting to trigger change detection on your own.
<div class="alert is-helpful">
<h4>Disabling <code>Zone</code></h4>
**If you disable `Zone`, you will need to trigger all change detection at the correct timing yourself, which requires comprehensive knowledge of change detection**.
</div>
To remove `zone.js`, make the following changes.
1. Remove the `zone.js` import from `polyfills.ts`.
```typescript
/***************************************************************************************************
* Zone JS is required by default for Angular itself.
*/
// import 'zone.js/dist/zone'; // Included with Angular CLI.
```
2. Bootstrap Angular with `noop zone` in `src/main.ts`.
```typescript
platformBrowserDynamic().bootstrapModule(AppModule, {ngZone: 'noop'})
.catch(err => console.error(err));
```

View File

@ -1,16 +1,16 @@
<h1 class="no-toc">Introduction to the Angular Docs</h1>
Angular is an app-design framework and development platform for creating efficient and sophisticated single-page apps.
These Angular docs help you learn and use the Angular platform and framework, from your first app to optimizing complex enterprise apps.
Tutorials and guides include downloadable example to accelerate your projects.
These Angular docs help you learn and use the Angular framework and development platform, from your first app to optimizing complex single-page apps for enterprises.
Tutorials and guides include downloadable examples to accelerate your projects.
<div class="card-container">
<a href="start" class="docs-card" title="Angular Getting Started">
<section>Learn</section>
<p>Create your first Angular app, without any setup</p>
<p class="card-footer">Getting Started</p>
<p>Play with and extend a small ready-made Angular app, without any setup</p>
<p class="card-footer">Getting Started</p>
</a>
<a href="guide/setup-local" class="docs-card"
title="Angular Local Environment Setup">
@ -18,10 +18,10 @@ Tutorials and guides include downloadable example to accelerate your projects.
<p>Set up your local environment with the Angular CLI</p>
<p class="card-footer">Local Setup</p>
</a>
<a href="guide/architecture" class="docs-card" title="Angular Architecture">
<a href="guide/architecture" class="docs-card" title="Angular App Architecture">
<section>Explore</section>
<p>Learn more about Angular apps and framework features</p>
<p class="card-footer">Architecture</p>
<p>Learn about the fundamental design concepts and architecture of Angular apps</p>
<p class="card-footer">Introduction to Angular concepts</p>
</a>
</div>
@ -29,13 +29,13 @@ Tutorials and guides include downloadable example to accelerate your projects.
## Assumptions
These docs assume that you are already familiar with [HTML](https://developer.mozilla.org/docs/Learn/HTML/Introduction_to_HTML "Learn HTML"), [CSS](https://developer.mozilla.org/docs/Learn/CSS/First_steps "Learn CSS"), [JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript "Learn JavaScript"),
and some of the tools from the [latest standards](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Language_Resources "Latest JavaScript standards"), such as [classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes "ES2015 Classes") and [modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import "ES2015 Modules").
The code samples are written using [TypeScript](https://www.typescriptlang.org/ "TypeScript").
These docs assume that you are already familiar with [HTML](https://developer.mozilla.org/docs/Learn/HTML/Introduction_to_HTML "Learn HTML"), [CSS](https://developer.mozilla.org/docs/Learn/CSS/First_steps "Learn CSS"), [JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript "Learn JavaScript"),
and some of the tools from the [latest standards](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Language_Resources "Latest JavaScript standards"), such as [classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes "ES2015 Classes") and [modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import "ES2015 Modules").
The code samples are written using [TypeScript](https://www.typescriptlang.org/ "TypeScript").
Most Angular code can be written with just the latest JavaScript, using [types](https://www.typescriptlang.org/docs/handbook/classes.html "TypeScript Types") for dependency injection, and using [decorators](https://www.typescriptlang.org/docs/handbook/decorators.html "Decorators") for metadata.
## Feedback
## Feedback
<h4>You can sit with us!</h4>
@ -45,8 +45,7 @@ Contribute to Angular docs by creating
[pull requests](https://github.com/angular/angular/pulls "Angular Github pull requests")
on the Angular Github repository.
See [Contributing to Angular](https://github.com/angular/angular/blob/master/CONTRIBUTING.md "Contributing guide")
for information about submission guidelines.
for information about submission guidelines.
Our community values respectful, supportive communication.
Please consult and adhere to the [Code of Conduct](https://github.com/angular/code-of-conduct/blob/master/CODE_OF_CONDUCT.md "Contributor code of conduct").

View File

@ -67,22 +67,22 @@
"tooltip": "Introduction to Angular's component model, template syntax, and component communication."
},
{
"url": "start/routing",
"url": "start/start-routing",
"title": "Routing",
"tooltip": "Introduction to routing between components using the browser's URL."
},
{
"url": "start/data",
"url": "start/start-data",
"title": "Managing Data",
"tooltip": "Introduction to services and accessing external data via HTTP."
},
{
"url": "start/forms",
"url": "start/start-forms",
"title": "Forms",
"tooltip": "Learn about fetching and managing data from users with forms."
},
{
"url": "start/deployment",
"url": "start/start-deployment",
"title": "Deployment",
"tooltip": "Move to local development, or deploy your application to Firebase or your own server."
}
@ -97,6 +97,37 @@
"title": "Fundamentals",
"tooltip": "The fundamentals of Angular",
"children": [
{
"title": "Angular Concepts",
"tooltip": "Introduction to basic concepts for Angular applications.",
"children": [
{
"url": "guide/architecture",
"title": "Intro to Basic Concepts",
"tooltip": "Basic building blocks of Angular applications."
},
{
"url": "guide/architecture-modules",
"title": "Intro to Modules",
"tooltip": "About NgModules."
},
{
"url": "guide/architecture-components",
"title": "Intro to Components",
"tooltip": "About Components, Templates, and Views."
},
{
"url": "guide/architecture-services",
"title": "Intro to Services and DI",
"tooltip": "About services and dependency injection."
},
{
"url": "guide/architecture-next-steps",
"title": "Next Steps",
"tooltip": "Beyond the basics."
}
]
},
{
"title": "Tour of Heroes App",
"tooltip": "The Tour of Heroes app is used as a reference point in many Angular examples.",
@ -104,17 +135,17 @@
{
"url": "tutorial",
"title": "Introduction",
"tooltip": "Introduction to the Tour of Heroes tutorial"
"tooltip": "Introduction to the Tour of Heroes app and tutorial"
},
{
"url": "tutorial/toh-pt0",
"title": "The Application Shell",
"title": "Create a Project",
"tooltip": "Creating the application shell"
},
{
"url": "tutorial/toh-pt1",
"title": "1. The Hero Editor",
"tooltip": "Part 1: Build a simple hero editor"
"tooltip": "Part 1: Build a simple editor"
},
{
"url": "tutorial/toh-pt2",
@ -143,37 +174,6 @@
}
]
},
{
"title": "Architecture",
"tooltip": "The basic building blocks of Angular applications.",
"children": [
{
"url": "guide/architecture",
"title": "Architecture Overview",
"tooltip": "Basic building blocks of Angular applications."
},
{
"url": "guide/architecture-modules",
"title": "Intro to Modules",
"tooltip": "About NgModules."
},
{
"url": "guide/architecture-components",
"title": "Intro to Components",
"tooltip": "About Components, Templates, and Views."
},
{
"url": "guide/architecture-services",
"title": "Intro to Services and DI",
"tooltip": "About services and dependency injection."
},
{
"url": "guide/architecture-next-steps",
"title": "Next Steps",
"tooltip": "Beyond the basics."
}
]
},
{
"title": "Components & Templates",
"tooltip": "Building dynamic views with data binding",
@ -297,11 +297,6 @@
}
]
},
{
"url": "guide/bootstrapping",
"title": "Bootstrapping",
"tooltip": "Tell Angular how to construct and bootstrap the app in the root \"AppModule\"."
},
{
"title": "NgModules",
"tooltip": "NgModules.",
@ -316,6 +311,11 @@
"title": "JS Modules vs NgModules",
"tooltip": "Differentiate between JavaScript modules and NgModules."
},
{
"url": "guide/bootstrapping",
"title": "App Root NgModule",
"tooltip": "Tell Angular how to construct and bootstrap the app in the root \"AppModule\"."
},
{
"url": "guide/frequent-ngmodules",
"title": "Frequently Used NgModules",
@ -439,6 +439,11 @@
"tooltip": "Animate route transitions."
}
]
},
{
"url": "guide/zone",
"title": "NgZone",
"tooltip": "How NgZone works"
}
]
},
@ -594,23 +599,23 @@
"hidden": true
},
{
"title": "AoT Compiler",
"title": "AOT Compiler",
"tooltip": "Understanding ahead-of-time compilation.",
"children": [
{
"url": "guide/aot-compiler",
"title": "Ahead-of-Time Compilation",
"tooltip": "Learn why and how to use the Ahead-of-Time (AoT) compiler."
"tooltip": "Learn why and how to use the Ahead-of-Time (AOT) compiler."
},
{
"url": "guide/angular-compiler-options",
"title": "Angular Compiler Options",
"tooltip": "Configuring AoT compilation."
"tooltip": "Configuring AOT compilation."
},
{
"url": "guide/aot-metadata-errors",
"title": "AoT Metadata Errors",
"tooltip": "Troubleshooting AoT compilation."
"title": "AOT Metadata Errors",
"tooltip": "Troubleshooting AOT compilation."
},
{
"url": "guide/template-typecheck",
@ -872,6 +877,10 @@
}
],
"docVersions": [
{
"title": "v8",
"url": "https://v8.angular.io/"
},
{
"title": "v7",
"url": "https://v7.angular.io/"

View File

@ -92,7 +92,7 @@ To help you get going, the following steps use predefined product data from the
<div class="alert is-helpful">
`*ngFor` is a "structural directive". Structural directives shape or reshape the DOM's structure, typically by adding, removing, and manipulating the elements to which they are attached. Any directive with an asterisk, `*`, is a structural directive.
`*ngFor` is a "structural directive". Structural directives shape or reshape the DOM's structure, typically by adding, removing, and manipulating the elements to which they are attached. Directives with an asterisk, `*`, are structural directives.
</div>
@ -358,5 +358,5 @@ You've learned about the foundation of Angular: components and template syntax.
You've also learned how the component class and template interact, and how components communicate with each other.
To continue exploring Angular, choose either of the following options:
* [Continue to the "Routing" section](start/routing "Getting Started: Routing") to create a product details page that can be accessed by clicking a product name and that has its own URL pattern.
* [Skip ahead to the "Deployment" section](start/deployment "Getting Started: Deployment") to move to local development, or deploy your app to Firebase or your own server.
* [Continue to the "Routing" section](start/start-routing "Getting Started: Routing") to create a product details page that can be accessed by clicking a product name and that has its own URL pattern.
* [Skip ahead to the "Deployment" section](start/start-deployment "Getting Started: Deployment") to move to local development, or deploy your app to Firebase or your own server.

View File

@ -1,6 +1,6 @@
# Managing Data
# Getting Started with Angular: Managing Data
At the end of [Routing](start/routing "Getting Started: Routing"), the online store application has a product catalog with two views: a product list and product details.
At the end of [Routing](start/start-routing "Getting Started: Routing"), the online store application has a product catalog with two views: a product list and product details.
Users can click on a product name from the list to see details in a new view, with a distinct URL, or route.
This page guides you through creating the shopping cart in three phases:
@ -29,12 +29,10 @@ about products in the cart.
<div class="alert is-helpful">
Later, the [Forms](start/forms "Getting Started: Forms") part of
Later, the [Forms](start/start-forms "Getting Started: Forms") part of
this tutorial guides you through accessing this cart service
from the page where the user checks out.
Later, the [Forms](start/forms "Getting Started: Forms") part of this tutorial guides you through accessing this cart service from the page where the user checks out.
</div>
{@a generate-cart-service}
@ -236,7 +234,7 @@ This section shows you how to use the HTTP client to retrieve shipping prices fr
### Predefined shipping data
The app StackBlitz generates for this guide comes with predefined shipping data in `assets/shipping.json`.
The application that StackBlitz generates for this guide comes with predefined shipping data in `assets/shipping.json`.
Use this data to add shipping prices for items in the cart.
<code-example header="src/assets/shipping.json" path="getting-started/src/assets/shipping.json">
@ -316,7 +314,7 @@ Now that your app can retrieve shipping data, create a shipping component and t
There's no link to the new shipping component yet, but you can see its template in the preview pane by entering the URL its route specifies. The URL has the pattern: `https://getting-started.stackblitz.io/shipping` where the `getting-started.stackblitz.io` part may be different for your StackBlitz project.
1. Modify the shipping component so it uses the cart service to retrieve shipping data via HTTP from the `shipping.json` file.
1. Modify the shipping component so that it uses the cart service to retrieve shipping data via HTTP from the `shipping.json` file.
1. Import the cart service.
@ -364,5 +362,5 @@ Now that your app can retrieve shipping data, create a shipping component and t
Congratulations! You have an online store application with a product catalog and shopping cart. You can also look up and display shipping prices.
To continue exploring Angular, choose either of the following options:
* [Continue to the "Forms" section](start/forms "Getting Started: Forms") to finish the app by adding the shopping cart page and a checkout form.
* [Skip ahead to the "Deployment" section](start/deployment "Getting Started: Deployment") to move to local development, or deploy your app to Firebase or your own server.
* [Continue to the "Forms" section](start/start-forms "Getting Started: Forms") to finish the app by adding the shopping cart page and a checkout form.
* [Skip ahead to the "Deployment" section](start/start-deployment "Getting Started: Deployment") to move to local development, or deploy your app to Firebase or your own server.

View File

@ -1,4 +1,4 @@
# Deployment
# Getting Started with Angular: Deployment
To deploy your application, you have to compile it, and then host the JavaScript, CSS, and HTML on a web server. Built Angular applications are very portable and can live in any environment or served by any technology, such as Node, Java, .NET, PHP, and many others.
@ -6,13 +6,11 @@ To deploy your application, you have to compile it, and then host the JavaScript
<div class="alert is-helpful">
Whether you came here directly from [Your First App](start "Getting Started: Your First App"), or completed the entire online store application through the [Routing](start/routing "Getting Started: Routing"), [Managing Data](start/data "Getting Started: Managing Data"), and [Forms](start/forms "Getting Started: Forms") sections, you have an application that you can deploy by following the instructions in this section.
Whether you came here directly from [Your First App](start "Getting Started: Your First App"), or completed the entire online store application through the [Routing](start/start-routing "Getting Started: Routing"), [Managing Data](start/start-data "Getting Started: Managing Data"), and [Forms](start/start-forms "Getting Started: Forms") sections, you have an application that you can deploy by following the instructions in this section.
</div>
## Share your application
StackBlitz projects are public by default, allowing you to share your Angular app via the project URL. Keep in mind that this is a great way to share ideas and prototypes, but it is not intended for production hosting.
@ -24,9 +22,9 @@ StackBlitz projects are public by default, allowing you to share your Angular ap
## Building locally
To build your application locally or for production, you will need to download the source code from your StackBlitz project. Click the `Download Project` icon in the left menu across from `Project` to download your files.
To build your application locally or for production, download the source code from your StackBlitz project by clicking the `Download Project` icon in the left menu across from `Project` to download your files.
Once you have the source code downloaded and unzipped, use the [Angular Console](https://angularconsole.com "Angular Console web site") to serve the application, or you install `Node.js` and have the Angular CLI installed.
Once you have the source code downloaded and unzipped, use the [Angular Console](https://angularconsole.com "Angular Console web site") to serve the application, or install `Node.js` and serve your app with the Angular CLI.
From the terminal, install the Angular CLI globally with:
@ -34,7 +32,7 @@ From the terminal, install the Angular CLI globally with:
npm install -g @angular/cli
```
This will install the command `ng` into your system, which is the command you use to create new workspaces, new projects, serve your application during development, or produce builds that can be shared or distributed.
This installs the command `ng` on your system, which is the command you use to create new workspaces, new projects, serve your application during development, or produce builds to share or distribute.
Create a new Angular CLI workspace using the [`ng new`](cli/new "CLI ng new command reference") command:
@ -42,7 +40,7 @@ Create a new Angular CLI workspace using the [`ng new`](cli/new "CLI ng new comm
ng new my-project-name
```
From there you replace the `/src` folder with the one from your `StackBlitz` download, and then perform a build.
In your new CLI generated app, replace the `/src` folder with the one from your `StackBlitz` download, and then perform a build.
```sh
ng build --prod
@ -58,7 +56,7 @@ If the above `ng build` command throws an error about missing packages, append t
#### Hosting the built project
The files in the `dist/my-project-name` folder are static and can be hosted on any web server capable of serving files (`Node.js`, Java, .NET) or any backend (Firebase, Google Cloud, App Engine, others).
The files in the `dist/my-project-name` folder are static. This means you can host them on any web server capable of serving files (such as `Node.js`, Java, .NET), or any backend (such as Firebase, Google Cloud, or App Engine).
### Hosting an Angular app on Firebase
@ -66,33 +64,33 @@ One of the easiest ways to get your site live is to host it using Firebase.
1. Sign up for a firebase account on [Firebase](https://firebase.google.com/ "Firebase web site").
1. Create a new project, giving it any name you like.
1. Install the `firebase-tools` CLI that will handle your deployment using `npm install -g firebase-tools`.
1. Add the `@angular/fire` schematics that will handle your deployment using `ng add @angular/fire`.
1. Connect your CLI to your Firebase account and initialize the connection to your project using `firebase login` and `firebase init`.
1. Follow the prompts to select the `Firebase` project you are creating for hosting.
- Select the `Hosting` option on the first prompt.
- Select the project you previously created on Firebase.
- Select `dist/my-project-name` as the public directory.
1. Deploy your application with `firebase deploy`, because the command `firebase init` has created a `firebase.json` file that tells Firebase how to serve your app.
- Select the `Hosting` option on the first prompt.
- Select the project you previously created on Firebase.
- Select `dist/my-project-name` as the public directory.
1. Deploy your application with `ng deploy`.
1. Once deployed, visit https://your-firebase-project-name.firebaseapp.com to see it live!
### Hosting an Angular app anywhere else
To host an Angular app on another web host, you'll need to upload or send the files to the host.
Because you are building a Single Page Application, you'll also need to make sure you redirect any invalid URLs to your `index.html` file.
Learn more about development and distribution of your application in the [Building & Serving](guide/build "Building and Serving Angular Apps") and [Deployment](guide/deployment "Deployment guide") guides.
To host an Angular app on another web host, upload or send the files to the host.
Because you are building a single page application, you'll also need to make sure you redirect any invalid URLs to your `index.html` file.
Read more about development and distribution of your application in the [Building & Serving](guide/build "Building and Serving Angular Apps") and [Deployment](guide/deployment "Deployment guide") guides.
## Join our community
## Join the Angular community
You are now an Angular developer! [Share this moment](https://twitter.com/intent/tweet?url=https://angular.io/start&text=I%20just%20finished%20the%20Angular%20Getting%20Started%20Tutorial "Angular on Twitter"), tell us what you thought of this Getting Started, or submit [suggestions for future editions](https://github.com/angular/angular/issues/new/choose "Angular GitHub repository new issue form").
You are now an Angular developer! [Share this moment](https://twitter.com/intent/tweet?url=https://angular.io/start&text=I%20just%20finished%20the%20Angular%20Getting%20Started%20Tutorial "Angular on Twitter"), tell us what you thought of this Getting Started, or submit [suggestions for future editions](https://github.com/angular/angular/issues/new/choose "Angular GitHub repository new issue form").
Angular offers many more capabilities, and you now have a foundation that empowers you to build an application and explore those other capabilities:
* Angular provides advanced capabilities for mobile apps, animation, internationalization, server-side rendering, and more.
* [Angular Material](https://material.angular.io/ "Angular Material web site") offers an extensive library of Material Design components.
* [Angular Protractor](https://protractor.angular.io/ "Angular Protractor web site") offers an end-to-end testing framework for Angular apps.
* Angular also has an extensive [network of 3rd-party tools and libraries](https://angular.io/resources "Angular resources list").
* Angular provides advanced capabilities for mobile apps, animation, internationalization, server-side rendering, and more.
* [Angular Material](https://material.angular.io/ "Angular Material web site") offers an extensive library of Material Design components.
* [Angular Protractor](https://protractor.angular.io/ "Angular Protractor web site") offers an end-to-end testing framework for Angular apps.
* Angular also has an extensive [network of 3rd-party tools and libraries](https://angular.io/resources "Angular resources list").
Keep current by following the [Angular blog](https://blog.angular.io/ "Angular blog").
Keep current by following the [Angular blog](https://blog.angular.io/ "Angular blog").

View File

@ -1,6 +1,6 @@
# Forms
# Getting Started with Angular: Forms
At the end of [Managing Data](start/data "Getting Started: Managing Data"), the online store application has a product catalog and a shopping cart.
At the end of [Managing Data](start/start-data "Getting Started: Managing Data"), the online store application has a product catalog and a shopping cart.
This section walks you through adding a form-based checkout feature to collect user information as part of checkout.
@ -40,7 +40,7 @@ of the constructor.
1. For the checkout process, users need to submit their name and address. When they submit their order, the form should reset and the cart should clear.
1. In `cart.component.ts`, define an `onSubmit()` method to process the form. Use the `CartService` `clearCart()` method to empty the cart items and reset the form after it is submission. In a real-world app, this method would also submit the data to an external server. The entire cart component class is as follows:
1. In `cart.component.ts`, define an `onSubmit()` method to process the form. Use the `CartService` `clearCart()` method to empty the cart items and reset the form after its submission. In a real-world app, this method would also submit the data to an external server. The entire cart component class is as follows:
<code-example header="src/app/cart/cart.component.ts" path="getting-started/src/app/cart/cart.component.ts">
</code-example>
@ -82,4 +82,4 @@ To confirm submission, open the console where you should see an object containin
Congratulations! You have a complete online store application with a product catalog, a shopping cart, and a checkout function.
[Continue to the "Deployment" section](start/deployment "Getting Started: Deployment") to move to local development, or deploy your app to Firebase or your own server.
[Continue to the "Deployment" section](start/start-deployment "Getting Started: Deployment") to move to local development, or deploy your app to Firebase or your own server.

View File

@ -1,4 +1,4 @@
# Routing
# Getting Started with Angular: Routing
At the end of [Your First App](start "Getting Started: Your First App"), the online store application has a basic product catalog.
The app doesn't have any variable states or navigation.
@ -73,7 +73,7 @@ The product details component handles the display of each product. The Angular R
The `ActivatedRoute` is specific to each routed component that the Angular Router loads. It contains information about the
route, its parameters, and additional data associated with the route.
By injecting the `ActivatedRoute`, you are configuring the component to use a service. While this part of the Getting Started tutorial uses this syntax briefly, the [Managing Data](start/data "Getting Started: Managing Data") page covers services in more detail.
By injecting the `ActivatedRoute`, you are configuring the component to use a service. While this part of the Getting Started tutorial uses this syntax briefly, the [Managing Data](start/start-data "Getting Started: Managing Data") page covers services in more detail.
1. In the `ngOnInit()` method, subscribe to route parameters and fetch the product based on the `productId`.
@ -111,5 +111,5 @@ Congratulations! You have integrated routing into your online store.
* Users can click on a product name from the list to see details in a new view, with a distinct URL/route.
To continue exploring Angular, choose either of the following options:
* [Continue to the "Managing Data" section](start/data "Getting Started: Managing Data") to add a shopping cart feature, use a service to manage the cart data and use HTTP to retrieve external data for shipping prices.
* [Skip ahead to the Deployment section](start/deployment "Getting Started: Deployment") to deploy your app to Firebase or move to local development.
* [Continue to the "Managing Data" section](start/start-data "Getting Started: Managing Data") to add a shopping cart feature, use a service to manage the cart data and use HTTP to retrieve external data for shipping prices.
* [Skip ahead to the Deployment section](start/start-deployment "Getting Started: Deployment") to deploy your app to Firebase or move to local development.

View File

@ -1,4 +1,4 @@
# Create services
# Add services
The Tour of Heroes `HeroesComponent` is currently getting and displaying fake data.
@ -122,7 +122,7 @@ Replace the definition of the `heroes` property with a simple declaration.
Add a private `heroService` parameter of type `HeroService` to the constructor.
<code-example path="toh-pt4/src/app/heroes/heroes.component.ts" header="src/app/heroes/heroes.component.ts" region="ctor">
<code-example path="toh-pt4/src/app/heroes/heroes.component.1.ts" header="src/app/heroes/heroes.component.ts" region="ctor">
</code-example>
The parameter simultaneously defines a private `heroService` property and identifies it as a `HeroService` injection site.

View File

@ -1,4 +1,4 @@
# Add in-app navigation (routing)
# Add in-app navigation with routing
There are new requirements for the Tour of Heroes app:

View File

@ -30,6 +30,12 @@
{"type": 301, "source": "/getting-started", "destination": "/start"},
{"type": 301, "source": "/getting-started/:rest*", "destination": "/start/:rest*"},
// Renaming of Getting Started topics
{"type": 301, "source": "/start/data", "destination": "/start/start-data"},
{"type": 301, "source": "/start/deployment", "destination": "/start/start-deployment"},
{"type": 301, "source": "/start/forms", "destination": "/start/start-forms"},
{"type": 301, "source": "/start/routing", "destination": "/start/start-routing"},
// some top level guide pages on old site were moved below the guide folder
{"type": 301, "source": "/styleguide", "destination": "/guide/styleguide"},
{"type": 301, "source": "/docs/styleguide", "destination": "/guide/styleguide"},

View File

@ -1,5 +1,6 @@
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
process.env.CHROME_BIN = require('puppeteer').executablePath();
module.exports = function (config) {
config.set({
@ -30,7 +31,14 @@ module.exports = function (config) {
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
customLaunchers: {
ChromeHeadlessNoSandbox: {
base: 'ChromeHeadless',
// See /integration/README.md#browser-tests for more info on these args
flags: ['--no-sandbox', '--headless', '--disable-gpu', '--disable-dev-shm-usage', '--hide-scrollbars', '--mute-audio'],
},
},
browsers: ['ChromeHeadlessNoSandbox'],
browserNoActivityTimeout: 60000,
singleRun: false,
restartOnFileChange: true,

View File

@ -131,6 +131,18 @@
"!/news",
"!/news.html",
"!/news/",
"!/start/data",
"!/start/data/",
"!/start/data.html",
"!/start/deployment",
"!/start/deployment/",
"!/start/deployment.html",
"!/start/forms",
"!/start/forms/",
"!/start/forms.html",
"!/start/routing",
"!/start/routing/",
"!/start/routing.html",
"!/styleguide",
"!/styleguide/**",
"!/testing",

View File

@ -72,7 +72,7 @@
"generate-stackblitz": "node ./tools/stackblitz-builder/generateStackblitz",
"generate-zips": "node ./tools/example-zipper/generateZips",
"build-404-page": "node scripts/build-404-page",
"update-webdriver": "webdriver-manager update --standalone false --gecko false $CI_CHROMEDRIVER_VERSION_ARG",
"update-webdriver": "node ../scripts/webdriver-manager-update.js",
"~~audit-web-app": "node scripts/audit-web-app",
"~~check-env": "node scripts/check-environment",
"~~clean-generated": "node --eval \"require('shelljs').rm('-rf', 'src/generated')\"",
@ -87,28 +87,28 @@
},
"private": true,
"dependencies": {
"@angular/animations": "9.0.0-rc.11",
"@angular/cdk": "9.0.0-rc.8",
"@angular/common": "9.0.0-rc.11",
"@angular/compiler": "9.0.0-rc.11",
"@angular/core": "9.0.0-rc.11",
"@angular/elements": "9.0.0-rc.11",
"@angular/forms": "9.0.0-rc.11",
"@angular/material": "9.0.0-rc.8",
"@angular/platform-browser": "9.0.0-rc.11",
"@angular/platform-browser-dynamic": "9.0.0-rc.11",
"@angular/router": "9.0.0-rc.11",
"@angular/service-worker": "9.0.0-rc.11",
"@webcomponents/custom-elements": "^1.2.0",
"@angular/animations": "9.0.0",
"@angular/cdk": "^9.0.0",
"@angular/common": "9.0.0",
"@angular/compiler": "9.0.0",
"@angular/core": "9.0.0",
"@angular/elements": "9.0.0",
"@angular/forms": "9.0.0",
"@angular/material": "^9.0.0",
"@angular/platform-browser": "9.0.0",
"@angular/platform-browser-dynamic": "9.0.0",
"@angular/router": "9.0.0",
"@angular/service-worker": "9.0.0",
"@webcomponents/custom-elements": "1.2.1",
"rxjs": "^6.5.3",
"tslib": "^1.10.0",
"zone.js": "~0.10.2"
},
"devDependencies": {
"@angular-devkit/build-angular": "0.900.0-rc.11",
"@angular/cli": "9.0.0-rc.11",
"@angular/compiler-cli": "9.0.0-rc.11",
"@angular/language-service": "9.0.0-rc.11",
"@angular-devkit/build-angular": "0.900.1",
"@angular/cli": "9.0.1",
"@angular/compiler-cli": "9.0.0",
"@angular/language-service": "9.0.0",
"@types/jasmine": "^3.4.2",
"@types/jasminewd2": "^2.0.8",
"@types/lunr": "^2.3.2",
@ -118,13 +118,12 @@
"archiver": "^1.3.0",
"canonical-path": "1.0.0",
"chalk": "^2.1.0",
"chrome-launcher": "^0.10.7",
"cjson": "^0.5.0",
"codelyzer": "^5.1.2",
"cross-spawn": "^5.1.0",
"css-selector-parser": "^1.3.0",
"dgeni": "^0.4.11",
"dgeni-packages": "^0.27.5",
"dgeni-packages": "^0.28.3",
"entities": "^1.1.1",
"eslint": "^3.19.0",
"eslint-plugin-jasmine": "^2.2.0",
@ -155,6 +154,7 @@
"lunr": "^2.1.0",
"npm-run-all": "^4.1.5",
"protractor": "^5.4.2",
"puppeteer": "2.1.1",
"rehype": "^6.0.0",
"rehype-slug": "^2.0.0",
"remark": "^9.0.0",

View File

@ -3,7 +3,7 @@
"master": {
"uncompressed": {
"runtime-es2015": 2987,
"main-es2015": 455897,
"main-es2015": 450612,
"polyfills-es2015": 52195
}
}
@ -12,7 +12,7 @@
"master": {
"uncompressed": {
"runtime-es2015": 2987,
"main-es2015": 448928,
"main-es2015": 451469,
"polyfills-es2015": 52195
}
}
@ -21,7 +21,7 @@
"master": {
"uncompressed": {
"runtime-es2015": 3097,
"main-es2015": 426513,
"main-es2015": 429230,
"polyfills-es2015": 52195
}
}

View File

@ -27,14 +27,13 @@
*/
// Imports
const chromeLauncher = require('chrome-launcher');
const lighthouse = require('lighthouse');
const printer = require('lighthouse/lighthouse-cli/printer');
const logger = require('lighthouse-logger');
const puppeteer = require('puppeteer');
// Constants
const AUDIT_CATEGORIES = ['accessibility', 'best-practices', 'performance', 'pwa', 'seo'];
const CHROME_LAUNCH_OPTS = {chromeFlags: ['--headless']};
const LIGHTHOUSE_FLAGS = {logLevel: process.env.CI ? 'error' : 'info'}; // Be less verbose on CI.
const SKIPPED_HTTPS_AUDITS = ['redirects-http', 'uses-http2'];
const VIEWER_URL = 'https://googlechrome.github.io/lighthouse/viewer';
@ -84,13 +83,13 @@ function formatScore(score) {
}
async function launchChromeAndRunLighthouse(url, flags, config) {
const chrome = await chromeLauncher.launch(CHROME_LAUNCH_OPTS);
flags.port = chrome.port;
const browser = await puppeteer.launch();
flags.port = (new URL(browser.wsEndpoint())).port;
try {
return await lighthouse(url, flags, config);
} finally {
await chrome.kill();
await browser.close();
}
}

View File

@ -22,7 +22,7 @@
<img *ngSwitchCase="true" src="assets/images/logos/angular/logo-nav@2x.png" width="150" height="40" title="Home" alt="Home">
<img *ngSwitchDefault src="assets/images/logos/angular/shield-large.svg" width="37" height="40" title="Home" alt="Home">
</a>
<aio-top-menu *ngIf="isSideBySide" [nodes]="topMenuNodes"></aio-top-menu>
<aio-top-menu *ngIf="isSideBySide" [nodes]="topMenuNodes" [currentNode]="currentNodes?.TopBar"></aio-top-menu>
<aio-search-box class="search-container" #searchBox (onSearch)="doSearch($event)" (onFocus)="doSearch($event)"></aio-search-box>
<div class="toolbar-external-icons-container">
<a href="https://twitter.com/angular" title="Twitter" aria-label="Angular on twitter">

View File

@ -1,35 +1,32 @@
import { NO_ERRORS_SCHEMA, DebugElement } from '@angular/core';
import { inject, ComponentFixture, TestBed, fakeAsync, flushMicrotasks, tick } from '@angular/core/testing';
import { Title } from '@angular/platform-browser';
import { APP_BASE_HREF } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { DebugElement, NO_ERRORS_SCHEMA } from '@angular/core';
import { ComponentFixture, fakeAsync, flushMicrotasks, inject, TestBed, tick } from '@angular/core/testing';
import { MatProgressBar } from '@angular/material/progress-bar';
import { MatSidenav } from '@angular/material/sidenav';
import { By } from '@angular/platform-browser';
import { Subject, of, timer } from 'rxjs';
import { first, mapTo } from 'rxjs/operators';
import { AppComponent } from './app.component';
import { AppModule } from './app.module';
import { CurrentNodes } from 'app/navigation/navigation.model';
import { By, Title } from '@angular/platform-browser';
import { ElementsLoader } from 'app/custom-elements/elements-loader';
import { DocumentService } from 'app/documents/document.service';
import { DocViewerComponent } from 'app/layout/doc-viewer/doc-viewer.component';
import { CurrentNodes } from 'app/navigation/navigation.model';
import { NavigationNode, NavigationService } from 'app/navigation/navigation.service';
import { SearchBoxComponent } from 'app/search/search-box/search-box.component';
import { SearchService } from 'app/search/search.service';
import { Deployment } from 'app/shared/deployment.service';
import { ElementsLoader } from 'app/custom-elements/elements-loader';
import { GaService } from 'app/shared/ga.service';
import { LocationService } from 'app/shared/location.service';
import { Logger } from 'app/shared/logger.service';
import { ScrollService } from 'app/shared/scroll.service';
import { SearchResultsComponent } from 'app/shared/search-results/search-results.component';
import { SelectComponent } from 'app/shared/select/select.component';
import { TocItem, TocService } from 'app/shared/toc.service';
import { of, Subject, timer } from 'rxjs';
import { first, mapTo } from 'rxjs/operators';
import { MockLocationService } from 'testing/location.service';
import { MockLogger } from 'testing/logger.service';
import { MockSearchService } from 'testing/search.service';
import { NavigationNode, NavigationService } from 'app/navigation/navigation.service';
import { ScrollService } from 'app/shared/scroll.service';
import { SearchBoxComponent } from 'app/search/search-box/search-box.component';
import { SearchResultsComponent } from 'app/shared/search-results/search-results.component';
import { SearchService } from 'app/search/search.service';
import { SelectComponent } from 'app/shared/select/select.component';
import { TocItem, TocService } from 'app/shared/toc.service';
import { AppComponent } from './app.component';
import { AppModule } from './app.module';
const sideBySideBreakPoint = 992;
const hideToCBreakPoint = 800;
@ -405,10 +402,12 @@ describe('AppComponent', () => {
// Older docs versions have an href
it('should navigate when change to a version with a url', async () => {
await setupSelectorForTesting();
locationService.urlSubject.next('new-page?id=1#section-1');
const versionWithUrlIndex = component.docVersions.findIndex(v => !!v.url);
const versionWithUrl = component.docVersions[versionWithUrlIndex];
const versionWithUrlAndPage = `${versionWithUrl.url}new-page?id=1#section-1`;
selectElement.triggerEventHandler('change', { option: versionWithUrl, index: versionWithUrlIndex});
expect(locationService.go).toHaveBeenCalledWith(versionWithUrl.url);
expect(locationService.go).toHaveBeenCalledWith(versionWithUrlAndPage);
});
it('should not navigate when change to a version without a url', async () => {
@ -793,7 +792,7 @@ describe('AppComponent', () => {
const searchService = TestBed.inject(SearchService) as Partial<SearchService> as MockSearchService;
const results = [
{ path: 'news', title: 'News', type: 'marketing', keywords: '', titleWords: '', deprecated: false }
{ path: 'news', title: 'News', type: 'marketing', keywords: '', titleWords: '', deprecated: false, topics: '' }
];
searchService.searchResults.next({ query: 'something', results });

View File

@ -1,18 +1,15 @@
import { Component, ElementRef, HostBinding, HostListener, OnInit,
QueryList, ViewChild, ViewChildren } from '@angular/core';
import { Component, ElementRef, HostBinding, HostListener, OnInit, QueryList, ViewChild, ViewChildren } from '@angular/core';
import { MatSidenav } from '@angular/material/sidenav';
import { CurrentNodes, NavigationService, NavigationNode, VersionInfo } from 'app/navigation/navigation.service';
import { DocumentService, DocumentContents } from 'app/documents/document.service';
import { DocumentContents, DocumentService } from 'app/documents/document.service';
import { NotificationComponent } from 'app/layout/notification/notification.component';
import { CurrentNodes, NavigationNode, NavigationService, VersionInfo } from 'app/navigation/navigation.service';
import { SearchResults } from 'app/search/interfaces';
import { SearchBoxComponent } from 'app/search/search-box/search-box.component';
import { SearchService } from 'app/search/search.service';
import { Deployment } from 'app/shared/deployment.service';
import { LocationService } from 'app/shared/location.service';
import { NotificationComponent } from 'app/layout/notification/notification.component';
import { ScrollService } from 'app/shared/scroll.service';
import { SearchBoxComponent } from 'app/search/search-box/search-box.component';
import { SearchResults } from 'app/search/interfaces';
import { SearchService } from 'app/search/search.service';
import { TocService } from 'app/shared/toc.service';
import { BehaviorSubject, combineLatest, Observable } from 'rxjs';
import { first, map } from 'rxjs/operators';
@ -77,6 +74,8 @@ export class AppComponent implements OnInit {
versionInfo: VersionInfo;
private currentUrl: string;
get isOpened() { return this.isSideBySide && this.isSideNavDoc; }
get mode() { return this.isSideBySide ? 'side' : 'over'; }
@ -148,27 +147,27 @@ export class AppComponent implements OnInit {
this.navigationService.versionInfo,
this.navigationService.navigationViews.pipe(map(views => views['docVersions'])),
]).subscribe(([versionInfo, versions]) => {
// TODO(pbd): consider whether we can lookup the stable and next versions from the internet
const computedVersions: NavigationNode[] = [
{ title: 'next', url: 'https://next.angular.io' },
{ title: 'stable', url: 'https://angular.io' },
];
if (this.deployment.mode === 'archive') {
computedVersions.push({ title: `v${versionInfo.major}` });
}
this.docVersions = [...computedVersions, ...versions];
// TODO(pbd): consider whether we can lookup the stable and next versions from the internet
const computedVersions: NavigationNode[] = [
{ title: 'next', url: 'https://next.angular.io' },
{ title: 'stable', url: 'https://angular.io' },
];
if (this.deployment.mode === 'archive') {
computedVersions.push({ title: `v${versionInfo.major}` });
}
this.docVersions = [...computedVersions, ...versions];
// Find the current version - eithers title matches the current deployment mode
// or its title matches the major version of the current version info
this.currentDocVersion = this.docVersions.find(version =>
version.title === this.deployment.mode || version.title === `v${versionInfo.major}`)!;
this.currentDocVersion.title += ` (v${versionInfo.raw})`;
});
// Find the current version - eithers title matches the current deployment mode
// or its title matches the major version of the current version info
this.currentDocVersion = this.docVersions.find(version =>
version.title === this.deployment.mode || version.title === `v${versionInfo.major}`)!;
this.currentDocVersion.title += ` (v${versionInfo.raw})`;
});
this.navigationService.navigationViews.subscribe(views => {
this.footerNodes = views['Footer'] || [];
this.footerNodes = views['Footer'] || [];
this.sideNavNodes = views['SideNav'] || [];
this.topMenuNodes = views['TopBar'] || [];
this.topMenuNodes = views['TopBar'] || [];
this.topMenuNarrowNodes = views['TopBarNarrow'] || this.topMenuNodes;
});
@ -188,6 +187,8 @@ export class AppComponent implements OnInit {
this.navigationService.currentNodes, // ...needed to determine `sidenav` state
]).pipe(first())
.subscribe(() => this.updateShell());
this.locationService.currentUrl.subscribe(url => this.currentUrl = url);
}
onDocReady() {
@ -231,7 +232,7 @@ export class AppComponent implements OnInit {
onDocVersionChange(versionIndex: number) {
const version = this.docVersions[versionIndex];
if (version.url) {
this.locationService.go(version.url);
this.locationService.go(`${version.url}${this.currentUrl}`);
}
}
@ -263,7 +264,7 @@ export class AppComponent implements OnInit {
}
// Deal with anchor clicks; climb DOM tree until anchor found (or null)
let target: HTMLElement|null = eventTarget;
let target: HTMLElement | null = eventTarget;
while (target && !(target instanceof HTMLAnchorElement)) {
target = target.parentElement;
}
@ -406,7 +407,7 @@ export class AppComponent implements OnInit {
if (key === '/' || keyCode === 191) {
this.focusSearchBox();
}
if (key === 'Escape' || keyCode === 27 ) {
if (key === 'Escape' || keyCode === 27) {
// escape key
if (this.showSearchResults) {
this.hideSearchResults();

View File

@ -57,6 +57,7 @@ export class ApiListComponent implements OnInit {
statuses: Option[] = [
{ value: 'all', title: 'All' },
{ value: 'stable', title: 'Stable'},
{ value: 'deprecated', title: 'Deprecated' },
{ value: 'security-risk', title: 'Security Risk' }
];

View File

@ -14,7 +14,7 @@
<div *ngFor="let resource of subCategory.resources">
<div class="c-resource" *ngIf="resource.rev">
<a class="l-flex--column resource-row-link" target="_blank" [href]="resource.url">
<a class="l-flex--column resource-row-link" rel="noopener" target="_blank" [href]="resource.url">
<div>
<h4>{{resource.title}}</h4>
<p class="resource-description">{{resource.desc || 'No Description'}}</p>

View File

@ -111,6 +111,22 @@ describe('NotificationComponent', () => {
expect(getItemSpy).toHaveBeenCalledWith('aio-notification/survey-january-2018');
expect(component.showNotification).toBe('hide');
});
it('should not break when cookies are disabled in the browser', () => {
configTestingModule();
// Simulate `window.localStorage` being inaccessible, when cookies are disabled.
const mockWindow: MockWindow = TestBed.inject(WindowToken);
Object.defineProperty(mockWindow, 'localStorage', {
get() { throw new Error('The operation is insecure'); },
});
expect(() => createComponent()).not.toThrow();
expect(component.showNotification).toBe('show');
component.dismiss();
expect(component.showNotification).toBe('hide');
});
});
@Component({

View File

@ -20,7 +20,7 @@ const LOCAL_STORAGE_NAMESPACE = 'aio-notification/';
]
})
export class NotificationComponent implements OnInit {
private get localStorage() { return this.window.localStorage; }
private storage: Storage;
@Input() dismissOnContentClick: boolean;
@Input() notificationId: string;
@ -31,12 +31,27 @@ export class NotificationComponent implements OnInit {
showNotification: 'show'|'hide';
constructor(
@Inject(WindowToken) private window: Window,
@Inject(WindowToken) window: Window,
@Inject(CurrentDateToken) private currentDate: Date
) {}
) {
try {
this.storage = window.localStorage;
} catch {
// When cookies are disabled in the browser, even trying to access
// `window.localStorage` throws an error. Use a no-op storage.
this.storage = {
length: 0,
clear: () => undefined,
getItem: () => null,
key: () => null,
removeItem: () => undefined,
setItem: () => undefined
};
}
}
ngOnInit() {
const previouslyHidden = this.localStorage.getItem(LOCAL_STORAGE_NAMESPACE + this.notificationId) === 'hide';
const previouslyHidden = this.storage.getItem(LOCAL_STORAGE_NAMESPACE + this.notificationId) === 'hide';
const expired = this.currentDate > new Date(this.expirationDate);
this.showNotification = previouslyHidden || expired ? 'hide' : 'show';
}
@ -48,7 +63,7 @@ export class NotificationComponent implements OnInit {
}
dismiss() {
this.localStorage.setItem(LOCAL_STORAGE_NAMESPACE + this.notificationId, 'hide');
this.storage.setItem(LOCAL_STORAGE_NAMESPACE + this.notificationId, 'hide');
this.showNotification = 'hide';
this.dismissed.next();
}

View File

@ -1,42 +1,86 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { BehaviorSubject } from 'rxjs';
import { TopMenuComponent } from './top-menu.component';
import { NavigationService, NavigationViews } from 'app/navigation/navigation.service';
describe('TopMenuComponent', () => {
let component: TopMenuComponent;
let fixture: ComponentFixture<TopMenuComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ TopMenuComponent ],
providers: [
{ provide: NavigationService, useClass: TestNavigationService }
]
});
});
// Helpers
const getListItems = () => {
const list: HTMLUListElement = fixture.debugElement.nativeElement.querySelector('ul');
return Array.from(list.querySelectorAll('li'));
};
const getSelected = (items: HTMLLIElement[]) =>
items.filter(item => item.classList.contains('selected'));
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
TopMenuComponent,
],
});
fixture = TestBed.createComponent(TopMenuComponent);
component = fixture.componentInstance;
component.nodes = [
{url: 'api', title: 'API', tooltip: 'API docs'},
{url: 'features', title: 'Features', tooltip: 'Angular features overview'},
];
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
it('should create an item for each navigation node', () => {
const items = getListItems();
const links = items.map(item => item.querySelector('a'))
.filter((link): link is NonNullable<typeof link> => link !== null);
expect(links.length).toBe(2);
expect(links.map(link => link.pathname)).toEqual(['/api', '/features']);
expect(links.map(link => link.textContent)).toEqual(['API', 'Features']);
expect(links.map(link => link.title)).toEqual(['API docs', 'Angular features overview']);
});
it('should mark the currently selected node with `.selected`', () => {
const items = getListItems();
expect(getSelected(items)).toEqual([]);
component.currentNode = {url: 'api', view: 'foo', nodes: []};
fixture.detectChanges();
expect(getSelected(items)).toEqual([items[0]]);
component.currentNode = {url: 'features', view: 'foo', nodes: []};
fixture.detectChanges();
expect(getSelected(items)).toEqual([items[1]]);
component.currentNode = {url: 'something/else', view: 'foo', nodes: []};
fixture.detectChanges();
expect(getSelected(items)).toEqual([]);
});
it('should not mark any node with `.selected` if the current URL is undefined', () => {
component.nodes = [
{url: '', title: 'API', tooltip: 'API docs'},
{url: undefined, title: 'Features', tooltip: 'Angular features overview'},
];
fixture.detectChanges();
const items = getListItems();
component.currentNode = undefined;
fixture.detectChanges();
expect(getSelected(items)).toEqual([]);
});
it('should correctly mark a node with `.selected` even if its URL is empty', () => {
component.nodes = [
{url: '', title: 'API', tooltip: 'API docs'},
{url: undefined, title: 'Features', tooltip: 'Angular features overview'},
];
fixture.detectChanges();
const items = getListItems();
component.currentNode = {url: '', view: 'Empty url', nodes: []};
fixture.detectChanges();
expect(getSelected(items)).toEqual([items[0]]);
});
});
//// Test Helpers ////
class TestNavigationService {
navJson = {
TopBar: [
{url: 'api', title: 'API' },
{url: 'features', title: 'Features' }
],
};
navigationViews = new BehaviorSubject<NavigationViews>(this.navJson);
}

View File

@ -1,12 +1,12 @@
import { Component, Input } from '@angular/core';
import { NavigationNode } from 'app/navigation/navigation.service';
import { CurrentNode, NavigationNode } from 'app/navigation/navigation.service';
@Component({
selector: 'aio-top-menu',
template: `
<ul role="navigation">
<li *ngFor="let node of nodes">
<a class="nav-link" [href]="node.url" [title]="node.title">
<li *ngFor="let node of nodes" [ngClass]="{selected: node.url === currentUrl}">
<a class="nav-link" [href]="node.url" [title]="node.tooltip">
<span class="nav-link-inner">{{ node.title }}</span>
</a>
</li>
@ -14,5 +14,7 @@ import { NavigationNode } from 'app/navigation/navigation.service';
})
export class TopMenuComponent {
@Input() nodes: NavigationNode[];
@Input() currentNode: CurrentNode | undefined;
get currentUrl(): string | null { return this.currentNode ? this.currentNode.url : null; }
}

View File

@ -9,6 +9,7 @@ export interface SearchResult {
type: string;
titleWords: string;
keywords: string;
topics: string;
deprecated: boolean;
}

View File

@ -15,6 +15,7 @@ interface PageInfo {
type: string;
titleWords: string;
keyWords: string;
topics: string;
}
addEventListener('message', handleMessage);
@ -27,6 +28,7 @@ function createIndex(loadIndexFn: IndexLoader): lunr.Index {
queryLexer.termSeparator = lunr.tokenizer.separator = /\s+/;
return lunr(/** @this */function() {
this.ref('path');
this.field('topics', { boost: 15 });
this.field('titleWords', { boost: 10 });
this.field('headingWords', { boost: 5 });
this.field('members', { boost: 4 });

View File

@ -1,30 +1,57 @@
<div class="search-results">
<div *ngIf="searchAreas.length; then searchResults; else notFound"></div>
<div class="search-results" [ngSwitch]="searchState">
<ng-container *ngSwitchCase="'in-progress'">
<p class="no-results">Searching ...</p>
</ng-container>
<ng-container *ngSwitchCase="'results-found'">
<h2 class="visually-hidden">Search Results</h2>
<div class="search-area" *ngFor="let area of searchAreas">
<h3 class="search-section-header">{{area.name}} ({{area.pages.length + area.priorityPages.length}})</h3>
<ul class="priority-pages" >
<li class="search-page" *ngFor="let page of area.priorityPages">
<a class="search-result-item" href="{{ page.path }}" (click)="onResultSelected(page, $event)">
<span class="symbol {{page.type}}" *ngIf="area.name === 'api'"></span>
<span [class.deprecated-api-item]="page.deprecated">{{ page.title }}</span>
</a>
</li>
</ul>
<ul>
<li class="search-page" *ngFor="let page of area.pages">
<a class="search-result-item" href="{{ page.path }}" (click)="onResultSelected(page, $event)">
<span class="symbol {{page.type}}" *ngIf="area.name === 'api'"></span>
<span [class.deprecated-api-item]="page.deprecated">{{ page.title }}</span>
</a>
</li>
</ul>
</div>
</ng-container>
<ng-container *ngSwitchCase="'no-results-found'">
<div class="search-area">
<p class="no-results">
No results found.<br>
Here are a few links that might be helpful in finding what you are looking for:
</p>
<ul class="priority-pages">
<li class="search-page">
<a class="search-result-item" href="api">API reference</a>
</li>
<li class="search-page">
<a class="search-result-item" href="resources">Resources</a>
</li>
<li class="search-page">
<a class="search-result-item" href="guide/glossary">Glossary</a>
</li>
<li class="search-page">
<a class="search-result-item" href="guide/cheatsheet">Cheat-sheet</a>
</li>
<li class="search-page">
<a class="search-result-item" href="https://blog.angular.io/">Angular blog</a>
</li>
</ul>
</div>
</ng-container>
</div>
<ng-template #searchResults>
<h2 class="visually-hidden">Search Results</h2>
<div class="search-area" *ngFor="let area of searchAreas">
<h3 class="search-section-header">{{area.name}} ({{area.pages.length + area.priorityPages.length}})</h3>
<ul class="priority-pages" >
<li class="search-page" *ngFor="let page of area.priorityPages">
<a class="search-result-item" href="{{ page.path }}" (click)="onResultSelected(page, $event)">
<span class="symbol {{page.type}}" *ngIf="area.name === 'api'"></span>
<span [class.deprecated-api-item]="page.deprecated">{{ page.title }}</span>
</a>
</li>
</ul>
<ul>
<li class="search-page" *ngFor="let page of area.pages">
<a class="search-result-item" href="{{ page.path }}" (click)="onResultSelected(page, $event)">
<span class="symbol {{page.type}}" *ngIf="area.name === 'api'"></span>
<span [class.deprecated-api-item]="page.deprecated">{{ page.title }}</span>
</a>
</li>
</ul>
</div>
</ng-template>
<ng-template #notFound>
<p class="not-found">{{notFoundMessage}}</p>
</ng-template>

View File

@ -37,21 +37,21 @@ describe('SearchResultsComponent', () => {
/** Get a full set of test results. "Take" what you need */
beforeEach(() => {
apiD = { path: 'api/d', title: 'API D', deprecated: false, keywords: '', titleWords: '', type: '' };
apiC = { path: 'api/c', title: 'API C', deprecated: false, keywords: '', titleWords: '', type: '' };
guideA = { path: 'guide/a', title: 'Guide A', deprecated: false, keywords: '', titleWords: '', type: '' };
guideB = { path: 'guide/b', title: 'Guide B', deprecated: false, keywords: '', titleWords: '', type: '' };
guideAC = { path: 'guide/a/c', title: 'Guide A - C', deprecated: false, keywords: '', titleWords: '', type: '' };
guideE = { path: 'guide/e', title: 'Guide e', deprecated: false, keywords: '', titleWords: '', type: '' };
guideF = { path: 'guide/f', title: 'Guide f', deprecated: false, keywords: '', titleWords: '', type: '' };
guideG = { path: 'guide/g', title: 'Guide g', deprecated: false, keywords: '', titleWords: '', type: '' };
guideH = { path: 'guide/h', title: 'Guide h', deprecated: false, keywords: '', titleWords: '', type: '' };
guideI = { path: 'guide/i', title: 'Guide i', deprecated: false, keywords: '', titleWords: '', type: '' };
guideJ = { path: 'guide/j', title: 'Guide j', deprecated: false, keywords: '', titleWords: '', type: '' };
guideK = { path: 'guide/k', title: 'Guide k', deprecated: false, keywords: '', titleWords: '', type: '' };
guideL = { path: 'guide/l', title: 'Guide l', deprecated: false, keywords: '', titleWords: '', type: '' };
guideM = { path: 'guide/m', title: 'Guide m', deprecated: false, keywords: '', titleWords: '', type: '' };
guideN = { path: 'guide/n', title: 'Guide n', deprecated: false, keywords: '', titleWords: '', type: '' };
apiD = { path: 'api/d', title: 'API D', deprecated: false, keywords: '', titleWords: '', type: '', topics: '' };
apiC = { path: 'api/c', title: 'API C', deprecated: false, keywords: '', titleWords: '', type: '', topics: '' };
guideA = { path: 'guide/a', title: 'Guide A', deprecated: false, keywords: '', titleWords: '', type: '', topics: '' };
guideB = { path: 'guide/b', title: 'Guide B', deprecated: false, keywords: '', titleWords: '', type: '', topics: '' };
guideAC = { path: 'guide/a/c', title: 'Guide A - C', deprecated: false, keywords: '', titleWords: '', type: '', topics: '' };
guideE = { path: 'guide/e', title: 'Guide e', deprecated: false, keywords: '', titleWords: '', type: '', topics: '' };
guideF = { path: 'guide/f', title: 'Guide f', deprecated: false, keywords: '', titleWords: '', type: '', topics: '' };
guideG = { path: 'guide/g', title: 'Guide g', deprecated: false, keywords: '', titleWords: '', type: '', topics: '' };
guideH = { path: 'guide/h', title: 'Guide h', deprecated: false, keywords: '', titleWords: '', type: '', topics: '' };
guideI = { path: 'guide/i', title: 'Guide i', deprecated: false, keywords: '', titleWords: '', type: '', topics: '' };
guideJ = { path: 'guide/j', title: 'Guide j', deprecated: false, keywords: '', titleWords: '', type: '', topics: '' };
guideK = { path: 'guide/k', title: 'Guide k', deprecated: false, keywords: '', titleWords: '', type: '', topics: '' };
guideL = { path: 'guide/l', title: 'Guide l', deprecated: false, keywords: '', titleWords: '', type: '', topics: '' };
guideM = { path: 'guide/m', title: 'Guide m', deprecated: false, keywords: '', titleWords: '', type: '', topics: '' };
guideN = { path: 'guide/n', title: 'Guide n', deprecated: false, keywords: '', titleWords: '', type: '', topics: '' };
standardResults = [
guideA, apiD, guideB, guideAC, apiC, guideN, guideM, guideL, guideK, guideJ, guideI, guideH, guideG, guideF, guideE,
@ -80,13 +80,13 @@ describe('SearchResultsComponent', () => {
it('should special case results that are top level folders', () => {
setSearchResults('', [
{ path: 'tutorial', title: 'Tutorial index', type: '', keywords: '', titleWords: '', deprecated: false },
{ path: 'tutorial/toh-pt1', title: 'Tutorial - part 1', type: '', keywords: '', titleWords: '', deprecated: false },
{ path: 'tutorial', title: 'Tutorial index', type: '', keywords: '', titleWords: '', deprecated: false, topics: '' },
{ path: 'tutorial/toh-pt1', title: 'Tutorial - part 1', type: '', keywords: '', titleWords: '', deprecated: false, topics: '' },
]);
expect(component.searchAreas).toEqual([
{ name: 'tutorial', priorityPages: [
{ path: 'tutorial', title: 'Tutorial index', type: '', keywords: '', titleWords: '', deprecated: false },
{ path: 'tutorial/toh-pt1', title: 'Tutorial - part 1', type: '', keywords: '', titleWords: '', deprecated: false },
{ path: 'tutorial', title: 'Tutorial index', type: '', keywords: '', titleWords: '', deprecated: false, topics: '' },
{ path: 'tutorial/toh-pt1', title: 'Tutorial - part 1', type: '', keywords: '', titleWords: '', deprecated: false, topics: '' },
], pages: [] }
]);
});
@ -116,20 +116,20 @@ describe('SearchResultsComponent', () => {
it('should put search results with no containing folder into the default area (other)', () => {
const results = [
{ path: 'news', title: 'News', type: 'marketing', keywords: '', titleWords: '', deprecated: false }
{ path: 'news', title: 'News', type: 'marketing', keywords: '', titleWords: '', deprecated: false, topics: '' }
];
setSearchResults('', results);
expect(component.searchAreas).toEqual([
{ name: 'other', priorityPages: [
{ path: 'news', title: 'News', type: 'marketing', keywords: '', titleWords: '', deprecated: false }
{ path: 'news', title: 'News', type: 'marketing', keywords: '', titleWords: '', deprecated: false, topics: '' }
], pages: [] }
]);
});
it('should omit search results with no title', () => {
const results = [
{ path: 'news', title: '', type: 'marketing', keywords: '', titleWords: '', deprecated: false }
{ path: 'news', title: '', type: 'marketing', keywords: '', titleWords: '', deprecated: false, topics: '' }
];
setSearchResults('something', results);
@ -170,6 +170,12 @@ describe('SearchResultsComponent', () => {
expect(getText()).toContain('Searching ...');
});
it('should not display default links while searching', () => {
fixture.detectChanges();
const resultLinks = fixture.debugElement.queryAll(By.css('.search-page a'));
expect(resultLinks.length).toEqual(0);
});
describe('when a search result anchor is clicked', () => {
let searchResult: SearchResult;
let selected: SearchResult|null;
@ -179,7 +185,7 @@ describe('SearchResultsComponent', () => {
component.resultSelected.subscribe((result: SearchResult) => selected = result);
selected = null;
searchResult = { path: 'news', title: 'News', type: 'marketing', keywords: '', titleWords: '', deprecated: false };
searchResult = { path: 'news', title: 'News', type: 'marketing', keywords: '', titleWords: '', deprecated: false, topics: '' };
setSearchResults('something', [searchResult]);
fixture.detectChanges();
@ -214,9 +220,25 @@ describe('SearchResultsComponent', () => {
});
describe('when no query results', () => {
it('should display "not found" message', () => {
beforeEach(() => {
setSearchResults('something', []);
});
it('should display "not found" message', () => {
expect(getText()).toContain('No results');
});
it('should contain reference links', () => {
const resultLinks = fixture.debugElement.queryAll(By.css('.search-page a'));
const resultHrefs = resultLinks.map(a => a.nativeNode.getAttribute('href'));
expect(resultHrefs.length).toEqual(5);
expect(resultHrefs).toEqual([
'api',
'resources',
'guide/glossary',
'guide/cheatsheet',
'https://blog.angular.io/',
]);
});
});
});

View File

@ -1,6 +1,12 @@
import { Component, EventEmitter, Input, OnChanges, Output } from '@angular/core';
import { SearchResult, SearchResults, SearchArea } from 'app/search/interfaces';
enum SearchState {
InProgress = 'in-progress',
ResultsFound = 'results-found',
NoResultsFound = 'no-results-found'
}
/**
* A component to display search results in groups
*/
@ -23,11 +29,18 @@ export class SearchResultsComponent implements OnChanges {
resultSelected = new EventEmitter<SearchResult>();
readonly defaultArea = 'other';
notFoundMessage = 'Searching ...';
searchState: SearchState = SearchState.InProgress;
readonly topLevelFolders = ['guide', 'tutorial'];
searchAreas: SearchArea[] = [];
ngOnChanges() {
if (this.searchResults === null) {
this.searchState = SearchState.InProgress;
} else if (this.searchResults.results.length) {
this.searchState = SearchState.ResultsFound;
} else {
this.searchState = SearchState.NoResultsFound;
}
this.searchAreas = this.processSearchResults(this.searchResults);
}
@ -43,7 +56,6 @@ export class SearchResultsComponent implements OnChanges {
if (!search) {
return [];
}
this.notFoundMessage = 'No results found.';
const searchAreaMap: { [key: string]: SearchResult[] } = {};
search.results.forEach(result => {
if (!result.title) { return; } // bad data; should fix

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