Commit Graph

41 Commits

Author SHA1 Message Date
JoostK 51156f3f07 fix(core): allow proper type inference when `ngFor` is used with a `trackBy` function (#42692)
In #41995 the type of `TrackByFunction` was changed such that the
declaration of a `trackBy` function did not cause the item type to be
widened to the `trackBy`'s item type, which may be a supertype of the
iterated type. This has introduced situations where the template type
checker is now reporting errors for cases where a `trackBy` function is
no longer assignable to `TrackByFunction`.

This commit fixes the error by also including the item type `T` in
addition to the constrained type parameter `U`, allowing TypeScript to
infer an appropriate `T`.

Fixes #42609

PR Close #42692
2021-07-13 14:08:05 -07:00
Paul Gschwendtner e99af184ab build: update API goldens after api-extractor update (#42737)
Given we have updated API extractor to the most recent
version, we need to update the API goldens because the
latest version uses alias exports to avoid collisions with
default library globals (like `Event`).

PR Close #42737
2021-07-02 10:08:03 -07:00
Paul Gschwendtner 59fe159b78 build: update API goldens to reflect new tool (#42688)
Updates the TS API guardian goldens with their equivalents
based on the new shared dev-infra tool.

PR Close #42688
2021-06-30 11:43:48 -07:00
Kristiyan Kostadinov 873229f24b feat(core): add opt-in test module teardown configuration (#42566)
We currently have two long-standing issues related to how `TestBed` tests are torn down:
1. The dynamically-created test module isn't going to be destroyed, preventing the `ngOnDestroy` hooks on providers from running and keeping the component `style` nodes in the DOM.
2. The test root elements aren't going to be removed from the DOM. Instead, they will be removed whenever another test component is created.

By themselves, these issues are easy to resolve, but given how long they've been around, there are a lot of unit tests out there that depend on the broken behavior.

These changes address the issues by introducing APIs that allow users to opt into the correct test teardown behavior either at the application level via `TestBed.initTestEnvironment` or the test suite level via `TestBed.configureTestingModule`.

At the moment, the new teardown behavior is opt-in, but the idea is that we'll eventually make it opt-out before removing the configuration altogether.

Fixes #18831.

PR Close #42566
2021-06-17 18:03:47 +00:00
JoostK 85c7f7691e fix(common): infer correct type when `trackBy` is used in `ngFor` (#41995)
When a `trackBy` function is used that accepts a supertype of the iterated
array's type, the loop variable would undesirably be inferred as the supertype
instead of the array's item type. This commit adds an inferred type parameter
to `TrackByFunction` to allow an extra degree of freedom, enabling the
loop value to be inferred as the most narrow type.

Fixes #40125

PR Close #41995
2021-06-03 11:33:26 -07:00
Kristiyan Kostadinov de4fafb818 refactor(core): add single type for injector token (#41580)
Currently we have a lot of places where we repeat the type `Type<T>|AbstractType<T>|InjectionToken<T>` which makes it cumbersome to add another type or to type something else with the same signature.

These changes add a new type that can be used instead.

Fixes #39792.

PR Close #41580
2021-04-22 10:47:12 -07:00
mgechev a07f303708 feat(core): introduce getDirectiveMetadata global debugging utility (#41525)
This commit introduces a global debugging method
`ng.getDirectiveMetadata` which returns the metadata for a directive or
component instance.

PR Close #41525
2021-04-13 16:06:32 -07:00
Pete Bacon Darwin c83fe1698b refactor(core): rename `ɵɵInjectableDef` interface to `ɵɵInjectableDeclaration` (#41316)
The other similar interfaces were renamed in https://github.com/angular/angular/pull/41119,
but this one was left since it had existed before Ivy. It looks like the interface was
never actually exposed on npm so it is safe to rename this one too.

PR Close #41316
2021-04-07 13:57:12 -07:00
Pete Bacon Darwin 857dfaa1e7 refactor(core): remove the need for `ɵɵinjectPipeChangeDetectorRef()` (#41231)
This instruction was created to work around a problem with injecting a
`ChangeDetectorRef` into a pipe. See #31438. This fix required special
metadata for when the thing being injected was a `ChangeDetectorRef`.

Now this is handled by adding a flag `InjectorFlags.ForPipe` to the
`ɵɵdirectiveInject()` call, which avoids the need to special test_cases
`ChangeDetectorRef` in the generated code.

PR Close #41231
2021-03-30 16:46:37 -07:00
Pete Bacon Darwin 2ebe2bcb2f refactor(compiler): move factory out of injector definition (#41022)
Previously, injector definitions contained a `factory` property that
was used to create a new instance of the associated NgModule class.

Now this factory has been moved to its own `ɵfac` static property on the
NgModule class itself. This is inline with how directives, components and
pipes are created.

There is a small size increase to bundle sizes for each NgModule class,
because the `ɵfac` takes up a bit more space:

Before:

```js
let a = (() => {
  class n {}
  return n.\u0275mod = c.Cb({type: n}),
  n.\u0275inj = c.Bb({factory: function(t) { return new (t || n) }, imports: [[e.a.forChild(s)], e.a]}),
  n
})(),
```

After:

```js
let a = (() => {
  class n {}
  return n.\u0275fac = function(t) { return new (t || n) },
  n.\u0275mod = c.Cb({type: n}),
  n.\u0275inj = c.Bb({imports: [[r.a.forChild(s)], r.a]}),
  n
})(),
```

In other words `n.\u0275fac = ` is longer than `factory: ` (by 5 characters)
and only because the tooling insists on encoding `ɵ` as `\u0275`.

This can be mitigated in a future PR by only generating the `ɵfac` property
if it is actually needed.

PR Close #41022
2021-03-08 15:31:30 -08:00
abarghoud ca721c2972 feat(core): more precise type for `APP_INITIALIZER` token (#40986)
This commit updates the type of the `APP_INITIALIZER` injection token to
better document the expected types of values that Angular handles. Only
Promises and Observables are awaited and other types of values are ignored,
so the type of `APP_INITIALIZER` has been updated to
`Promise<unknown> | Observable<unknown> | void` to reflect this behavior.

BREAKING CHANGE:

The type of the `APP_INITIALIZER` token has been changed to more accurately
reflect the types of return values that are handled by Angular. Previously,
each initializer callback was typed to return `any`, this is now
`Promise<unknown> | Observable<unknown> | void`. In the unlikely event that
your application uses the `Injector.get` or `TestBed.inject` API to inject
the `APP_INITIALIZER` token, you may need to update the code to account for
the stricter type.

Additionally, TypeScript may report the TS2742 error if the `APP_INITIALIZER`
token is used in an expression of which its inferred type has to be emitted
into a .d.ts file. To workaround this, an explicit type annotation is needed,
which would typically be `Provider` or `Provider[]`.

Closes #40729

PR Close #40986
2021-03-04 12:01:07 -08:00
Pete Bacon Darwin 0f818f36d7 refactor(core): use `unknown` rather than `never` for private properties (#41040)
Before `unknown` was available, the `never` type was used to discourage
application developers from using "private" properties. The `unknown` type
is much better suited for this.

PR Close #41040
2021-03-04 11:04:26 -08:00
Kristiyan Kostadinov a3e17190e7 fix(core): allow EmbeddedViewRef context to be updated (#40360)
Currently `EmbeddedViewRef.context` is read-only which means that the only way to update
it is to mutate the object which can lead to some undesirable outcomes if the template
and the context are provided by an external consumer (see #24515).

These changes make the property writeable since there doesn't appear to be a specific
reason why it was readonly to begin with.

PR Close #40360
2021-02-23 08:14:01 -08:00
Pete Bacon Darwin 1579df243d fix(core): ensure the type `T` of `EventEmitter<T>` can be inferred (#40644)
The `AsyncPipe.transform<T>(emitter)` method must infer the `T`
type from the `emitter` parameter. Since we changed the `AsyncPipe`
to expect a `Subscribable<T>` rather than `Observable<T>` the
`EventEmitter.subscribe()` method needs to have a tighter signature.
Otherwise TypeScript struggles to infer the type and ends up making
it `unknown`.

Fixes #40637

PR Close #40644
2021-02-03 09:07:29 -08:00
Misko Hevery e32b6256ce fix(core): `QueryList` should not fire changes if the underlying list did not change. (#40091)
Previous implementation would fire changes `QueryList.changes.subscribe`
whenever the `QueryList` was recomputed. This resulted in artificially
high number of change notifications, as it is possible that recomputing
`QueryList` results in the same list. When the `QueryList` gets recomputed
is an implementation detail and it should not be the thing which determines
how often change event should fire.

This change introduces a new `emitDistinctChangesOnly` option for
`ContentChildren` and `ViewChildren`.

```
export class QueryCompWithStrictChangeEmitParent {
  @ContentChildren('foo', {
    // This option will become the default in the future
    emitDistinctChangesOnly: true,
  })
  foos!: QueryList<any>;
}
```

PR Close #40091
2021-01-14 13:55:02 -08:00
Andrew Kushnir 6cff877f4f perf(core): make DI decorators tree-shakable when used for `useFactory` deps config (#40145)
This commit updates the logic that calculates `useFactory` function arguments to avoid relying on `instanceof`
checks (thus always retaining symbols) and relies on flags that DI decorators contain (as a monkey-patched property).

Another perf benefit is having less megamorphic reads while calculating args for the `useFactory` call: we used to
check whether a token has `ngMetadataName` property 4 times (in worst case), now we have just 1 megamorphic read in
all cases.

Closes #40143.

PR Close #40145
2021-01-13 14:08:45 -08:00
Mitchell Wills a1b6ad07a8 fix(core): Allow passing AbstractType to the inject function (#37958)
This is a type only change that replaces `Type<T>|InjectionToken<T>` with
`Type<T>|AbstractType<T>|InjectionToken<T>` in the injector.

PR Close #37958
2020-11-24 10:42:21 -08:00
Issei Horie a965589eb8 feat(core): adds get method to QueryList (#36907)
This commit adds get method to QueryList.
The method returns an item of the internal results by index number.

PR Close #29467

PR Close #36907
2020-11-19 12:18:30 -08:00
Misko Hevery 8574c3000e refactor(core): Cleanup non-standard `Injector` handling. (#39621)
Due to historical reasons `Injector.__NG_ELEMENT_ID__` was set to `-1`.
This changes it to be consistent with other `*Ref.__NG_ELEMENT_ID__`
constructs.

PR Close #39621
2020-11-16 09:12:46 -08:00
JiaLiPassion 5e92d649f2 feat(core): add shouldCoalesceRunChangeDetection option to coalesce change detections in the same event loop. (#39422)
Close #39348

Now `NgZone` has an option `shouldCoalesceEventChangeDetection` to coalesce
multiple event handler's change detections to one async change detection.

And there are some cases other than `event handler` have the same issues.
In #39348, the case like this.

```
// This code results in one change detection occurring per
// ngZone.run() call. This is entirely feasible, and can be a serious
// performance issue.
for (let i = 0; i < 100; i++) {
  this.ngZone.run(() => {
    // do something
  });
}
```

So such kind of case will trigger multiple change detections.
And now with Ivy, we have a new `markDirty()` API will schedule
a requestAnimationFrame to trigger change detection and also coalesce
the change detections in the same event loop, `markDirty()` API doesn't
only take care `event handler` but also all other cases `sync/macroTask/..`

So this PR add a new option to coalesce change detections for all cases.

test(core): add test case for shouldCoalesceEventChangeDetection option

Add new test cases for current `shouldCoalesceEventChangeDetection` in `ng_zone.spec`, since
currently we only have integration test for this one.

PR Close #39422
2020-11-16 08:58:50 -08:00
JoostK 306a1307c7 refactor(compiler-cli): rename `$ngDeclareDirective`/`$ngDeclareComponent` to use `ɵɵ` prefix (#39518)
For consistency with other generated code, the partial declaration
functions are renamed to use the `ɵɵ` prefix which indicates that it is
generated API.

This commit also removes the declaration from the public API golden
file, as it's not yet considered stable at this point. Once the linker
is finalized will these declaration function be included into the golden
file.

PR Close #39518
2020-11-04 10:44:37 -08:00
JoostK 8c0a92bb45 feat(compiler-cli): partial compilation of directives (#39518)
This commit implements partial code generation for directives, which
will be transformed by the linker plugin to fully AOT compiled code in
follow-up work.

PR Close #39518
2020-11-04 10:44:37 -08:00
Misko Hevery ca11ef2376 fix(core): Store ICU state in `LView` rather than in `TView` (#39233)
Before this refactoring/fix the ICU would store the current selected
index in `TView`. This is incorrect, since if ICU is in `ngFor` it will
cause issues in some circumstances. This refactoring properly moves the
state to `LView`.

closes #37021
closes #38144
closes #38073

PR Close #39233
2020-10-21 18:33:00 -07:00
Kristiyan Kostadinov 4a1c12c773 feat(core): remove ViewEncapsulation.Native (#38882)
Removes `ViewEncapsulation.Native` which has been deprecated for several major versions.

BREAKING CHANGES:
* `ViewEncapsulation.Native` has been removed. Use `ViewEncapsulation.ShadowDom` instead. Existing
usages will be updated automatically by `ng update`.

PR Close #38882
2020-10-08 11:56:03 -07:00
Joey Perrott fdea1804d6 fix(core): remove CollectionChangeRecord symbol (#38668)
Remove CollectionChangeRecord as it was deprecated for removal in v4, use
IterableChangeRecord instead.

BREAKING CHANGE: CollectionChangeRecord has been removed, use IterableChangeRecord
instead

PR Close #38668
2020-09-02 16:45:19 -07:00
JiaLiPassion 8fbf40bf40 feat(core): update reference and doc to change `async` to `waitAsync`. (#37583)
The last commit change `async` to `waitForAsync`.
This commit update all usages in the code and also update aio doc.

PR Close #37583
2020-08-03 12:54:13 -07:00
Misko Hevery 2a45b932e2 build: fix broken build (#38274)
```
export const __core_private_testing_placeholder__ = '';
```
This API should be removed. But doing so seems to break `google3` and
so it requires a bit of investigation. A work around is to mark it as
`@codeGenApi` for now and investigate later.

PR Close #38274
2020-07-28 12:30:59 -07:00
Ajit Singh af80bdb470 fix(core): `Attribute` decorator `attributeName` is mandatory (#38131)
`Attribute` decorator has defined `attributeName` as optional but actually its
 mandatory and compiler throws an error if `attributeName` is undefined. Made
`attributeName` mandatory in the `Attribute` decorator to reflect this functionality

Fixes #32658

PR Close #38131
2020-07-28 11:17:24 -07:00
Igor Minar 5d3ba8dec7 test: update ts-api-guardian's strip_export_pattern to exclude Ivy instructions (#38224)
Previously the instructions were included in the golden files to monitor the frequency and rate of
the instruction API changes for the purpose of understanding the stability of this API (as it was
considered for becoming a public API and deployed to npm via generated code).

This experiment has confirmed that the instruction API is not stable enough to be used as public
API. We've since also came up with an alternative plan to compile libraries with the Ivy compiler
for npm deployment and this plan does not rely on making Ivy instructions public.

For these reasons, I'm removing the instructions from the golden files as it's no longer important
to track them.

The are three instructions that are still being included: `ɵɵdefineInjectable`, `ɵɵinject`, and
`ɵɵInjectableDef`.

These instructions are already generated by the VE compiler to support tree-shakable providers, and
code depending on these instructions is already deployed to npm. For this reason we need to treat
them as public api.

This change also reduces the code review overhead, because changes to public api golden files now
require multiple approvals.

PR Close #38224
2020-07-27 14:37:41 -07:00
Andrew Kushnir d72b1e44c6 refactor(core): rename synthetic host property and listener instructions (#37145)
This commit updates synthetic host property and listener instruction names to better align with other instructions.
The `ɵɵupdateSyntheticHostBinding` instruction was renamed to `ɵɵsyntheticHostProperty` (to match the `ɵɵhostProperty`
instruction name) and `ɵɵcomponentHostSyntheticListener` was renamed to `ɵɵsyntheticHostListener` since this
instruction is generated for both Components and Directives (so 'component' is removed from the name).
This PR is a followup after PR #35568.

PR Close #37145
2020-07-21 09:09:24 -07:00
Misko Hevery 737506e79c fix(core): Allow modification of lifecycle hooks any time before bootstrap (#35464)
Currently we read lifecycle hooks eagerly during `ɵɵdefineComponent`.
The result is that it is not possible to do any sort of meta-programing
such as mixins or adding lifecycle hooks using custom decorators since
any such code executes after `ɵɵdefineComponent` has extracted the
lifecycle hooks from the prototype. Additionally the behavior is
inconsistent between AOT and JIT mode. In JIT mode overriding lifecycle
hooks is possible because the whole `ɵɵdefineComponent` is placed in
getter which is executed lazily. This is because JIT mode must compile a
template which can be specified as `templateURL` and those we are
waiting for its resolution.

- `+` `ɵɵdefineComponent` becomes smaller as it no longer needs to copy
  lifecycle hooks from prototype to `ComponentDef`
- `-` `ɵɵNgOnChangesFeature` feature is now always included with the
  codebase as it is no longer tree shakable.

Previously we have read lifecycle hooks from prototype in the
`ɵɵdefineComponent` so that lifecycle hook access would be monomorphic.
This decision was made before we had `T*` data structures. By not
reading the lifecycle hooks we are moving the megamorhic read form
`ɵɵdefineComponent` to instructions. However, the reads happen on
`firstTemplatePass` only and are subsequently cached in the `T*` data
structures. The result is that the overall performance should be same
(or slightly better as the intermediate `ComponentDef` has been
removed.)

- [ ] Remove `ɵɵNgOnChangesFeature` from compiler. (It will no longer
      be a feature.)
- [ ] Discuss the future of `Features` as they hinder meta-programing.

Fix #30497

PR Close #35464
2020-07-15 16:22:46 -07:00
Paul Gschwendtner 97dc85ba5e feat(core): support injection token as predicate in queries (#37506)
Currently Angular internally already handles `InjectionToken` as
predicates for queries. This commit exposes this as public API as
developers already relied on this functionality but currently use
workarounds to satisfy the type constraints (e.g. `as any`).

We intend to make this public as it's low-effort to support, and
it's a significant key part for the use of light-weight tokens as
described in the upcoming guide: https://github.com/angular/angular/pull/36144.

In concrete, applications might use injection tokens over classes
for both optional DI and queries, because otherwise such references
cause classes to be always retained. This was also an issue in View
Engine, but now with Ivy, this pattern became worse, as factories are
directly attached to retained classes (ultimately ending up in the
production bundle, while being unused).

More details in the light-weight token guide and in: https://github.com/angular/angular-cli/issues/16866.

Closes #21152. Related to #36144.

PR Close #37506
2020-06-11 13:21:11 -07:00
Alan Agius f97d8a9cbd refactor: `EventEmitter` to retain behaviour of pre TypeScript 3.9 (#36989)
TypeScript 3.9 introduced a breaking change where extends `any` no longer acts as `any`, instead it acts as `unknown`.

With this change we retain the behavior we had with TS 3.8 which is;

When using the `EventEmitter` as a type you must always provide a  type;
```ts
let emitter: EventEmitter<string>
```

and when initializing the `EventEmitter` class you can either provide a  type or or use the fallback type which is `any`

```ts
const emitter = new EventEmitter(); // EventEmitter<any>
const emitter = new EventEmitte<string>(); // EventEmitter<string>
``

PR Close #36989
2020-05-14 10:50:30 -07:00
Alan Agius 13ba84731f build: prepare for TypeScript 3.9 (#36989)
- Fix several compilation errors
- Update @microsoft/api-extractor to be compatible with TypeScript 3.9

PR Close #36989
2020-05-14 10:50:28 -07:00
Matias Niemelä 45f4a47286 refactor(core): remove style sanitization code for `[style]`/`[style.prop]` bindings (#36965)
In 420b9be1c1 all style-based sanitization code was
disabled because modern browsers no longer allow for javascript expressions within
CSS. This patch is a follow-up patch which removes all traces of style sanitization
code (both instructions and runtime logic) for the `[style]` and `[style.prop]` bindings.

PR Close #36965
2020-05-13 15:56:12 -07:00
Andrew Kushnir 0c8adbc4ec refactor(core): remove unused embedded view instructions (#34715)
This commit performs a cleanup and removes unused embedded view instructions and corresponding tests.

PR Close #34715
2020-05-11 10:52:28 -07:00
Kara Erickson 20cc3ab37e refactor(core): make generic mandatory for ModuleWithProviders (#36892)
In v9, we deprecated the use of ModuleWithProviders
without a generic. In v10, we will be requiring the
generic when using ModuleWithProviders. You can read
more about the reasoning behind this change in the
migration guide:
http://v9.angular.io/guide/migration-module-with-providers

PR Close #36892
2020-05-06 15:01:34 -07:00
Misko Hevery c9e0db55f7 refactor(core): deprecate `WrappedValue` (#36819)
The purpose of the `WrappedValue` is to allow same object instance to be treated as different for the purposes of change detection. It is currently used with `async` pipe and only with `Observables`. The use case which it covers is if the `Observable` produces the same instance of the value but it is desirable to still try to mark it as changed for the purposes of change detection.

We believe tha the above use case is too rare to warrant special handling in the framework. (Having special handling causes application slowdown for the users and mental load for the developers.) No replacement is planned for this deprecation.

PR Close #36819
2020-05-06 11:49:57 -07:00
Joey Perrott 698b0288be build: reformat repo to new clang@1.4.0 (#36613)
PR Close #36613
2020-04-14 12:08:36 -07:00
JoostK 32ce8b1326 feat(compiler): add dependency info and ng-content selectors to metadata (#35695)
This commit augments the `FactoryDef` declaration of Angular decorated
classes to contain information about the parameter decorators used in
the constructor. If no constructor is present, or none of the parameters
have any Angular decorators, then this will be represented using the
`null` type. Otherwise, a tuple type is used where the entry at index `i`
corresponds with parameter `i`. Each tuple entry can be one of two types:

1. If the associated parameter does not have any Angular decorators,
   the tuple entry will be the `null` type.
2. Otherwise, a type literal is used that may declare at least one of
   the following properties:
   - "attribute": if `@Attribute` is present. The injected attribute's
   name is used as string literal type, or the `unknown` type if the
   attribute name is not a string literal.
   - "self": if `@Self` is present, always of type `true`.
   - "skipSelf": if `@SkipSelf` is present, always of type `true`.
   - "host": if `@Host` is present, always of type `true`.
   - "optional": if `@Optional` is present, always of type `true`.

   A property is only present if the corresponding decorator is used.

   Note that the `@Inject` decorator is currently not included, as it's
   non-trivial to properly convert the token's value expression to a
   type that is valid in a declaration file.

Additionally, the `ComponentDefWithMeta` declaration that is created for
Angular components has been extended to include all selectors on
`ng-content` elements within the component's template.

This additional metadata is useful for tooling such as the Angular
Language Service, as it provides the ability to offer suggestions for
directives/components defined in libraries. At the moment, such
tooling extracts the necessary information from the _metadata.json_
manifest file as generated by ngc, however this metadata representation
is being replaced by the information emitted into the declaration files.

Resolves FW-1870

PR Close #35695
2020-03-24 14:21:42 -07:00
Joey Perrott 15f8afa4bf ci: move public-api goldens to goldens directory (#35768)
Moves the public api .d.ts files from tools/public_api_guard to
goldens/public-api.

Additionally, provides a README in the goldens directory and a script
assist in testing the current state of the repo against the goldens as
well as a command for accepting all changes to the goldens in a single
command.

PR Close #35768
2020-03-10 20:58:39 -04:00