Currently, if there are 2 nested @defer blocks with the same dependency, Angular throws an error at runtime to indicate that there was a duplicate component def in the registry. This commit updates the logic to only append dependencies when they didn't previously exist in the registry.
PR Close#51964
This partially reverts commit a3e17190e7
and deprecates behavior added.
The context of an embedded view ref at some point was switched from a
getter to an actual assignable property. This is something we revert
as it introduces additional complexity for our generated code
(in terms of closures capturing the `ctx`), creates technical
limitations for Angular's internals and the usage pattern is rarely
used (and can be addressed via simple assignments, `Object.assign` or
the use of a proxy if replacing the full context object is still
desirable)
DEPRECATED: Swapping out the context object for `EmbeddedViewRef`
is no longer supported. Support for this was introduced with v12.0.0, but
this pattern is rarely used. There is no replacement, but you can use
simple assignments in most cases, or `Object.assign , or alternatively
still replace the full object by using a `Proxy` (see `NgTemplateOutlet`
as an example).
Also adds a warning if the deprecated
PR Close#51887
When adding a new view flag, you currently need to adjust the last number of the last
3 flags. All of these share the same number so the shifting ones can just use
the base-10 IndexWithinInitPhaseShift.
PR Close#51839
The new list reconcilation algorithm, an alternative to
the DefaultIterableListDiffer. It works by performing updates
in place instead of creating intermediate data describing changes
to apply. For lists expressed as an Array it performs additional
optimizations for the moves and swap scenarios.
The new list diffing approach is meant to be used in the new control
flow and should me much faster as compared to the ngFor with the
DefaultIterableListDiffer.
PR Close#51980
The template pipeline now supports basic forms of `defer` blocks. This includes the `loading`, `placeholder`, and `error` blocks, as well as the loading and placeholder configuration options.
Lazy dependencies and prefetch are not yet implemented.
PR Close#51942
This is a deceptively simple fix for a deep issue. Consider the following template:
```
<button [title]="myTitle" [id]="(auth().identity() | async)" [tabindex]="1">
```
`TemplateDefinitionBuilder` allocates the following variable (binding) slots:
v[0] = [title] binding
v[1] = [id] binding
v[2] = [tabindex] binding
v[3] = pipe binding
v[4] = pipe binding
As you can see, all three top-level property bindings were assigned variable indices. Then, variables for nested expressions were assigned.
Before this change, Template Pipeline would choose the following order:
v[0] = [title] binding
v[1] = [id] binding
v[2] = pipe binding
v[3] = pipe binding
v[4] = [tabindex] binding
With this order, nested expressions have their variables counted and assigned before subsequent top-level property bindings. This results in different variable indices for `pipeBinding` expressions that are not inside the final property binding.
However, this is not just different -- it's actually incorrect! Consider a case like the following:
```
<button [p1]="c ? (a | pipe) : 3" [p2]="b | pipe">
```
These pipe bindings are executed *conditionally*. This means that, because we don't count and assign all the "fixed" variable slots first, i.e. those belonging to the property bindings, their indices might end up incorrect, depending on whether or not a pipeBinding happened as part of the update block.
With this change, we count all variables on top-level ops first, and then descend into all expressions.
PR Close#51961
Fixes an issue where if animations are enabled, deferred blocks don't remove their placeholder blocks immediately from the DOM. The problem is that we register the event handlers in `afterRender` which runs outside the zone, but the logic that removes the DOM nodes during animations is tied to change detection.
These changes resolve the issue by binding the listeners inside the zone. This was the intention from the beginning, I just forgot that `afterRender` runs outside the zone.
Fixes#51970.
PR Close#51971
Currently, there is no change detection scheduled after triggering `on idle` condition, since `requestIdleCallback` is not patched by Zone.js. This commit invokes the callback in NgZone, so that the code that is invoked within the callback can use zones and a new change detection round is scheduled as needed.
Fixes#51973.
PR Close#51975
This API allows for inspection of a given injector to determine it's type (Element, Environment, Null) as well as it's "source".
- For Environment injectors the source is the source of the injector; `injector.source`.
- For Element injectors the name is the DOM Element that created the injector.
- For the Null Injector this is the string `"Null Injector"`.
PR Close#51900
This commit adds hydration support for repeaters (for loops) and empty blocks. The logic looks up a dehydrated view and use this information for hydration. Otherwise, DOM elements for a view are created from scratch.
PR Close#51920
Prior to this change `this.isStable.pipe(first((isStable) => isStable)).toPromise()` had to be done in multiple places across the framework and the Angular CLI see https://github.com/angular/angular-cli/pull/25856#discussion_r1328158846. In the majority of cases an Observable based `isStable` API is not needed. This also removes the need for RXJS operator imports.
PR Close#51807
This commit updates the `if` and `switch` logic to support hydration. The logic attempts to find dehydrated views in containers while processing `if` and `switch` instructions. If a dehydrated is found, its used to further match elements. Otherwise, DOM elements for a view are created from scratch.
PR Close#51915
Previously, dehydrated views lookup was triggered only when ViewContainerRef was injected. The new control flow logic uses lower level APIs, thus having the code only in the ViewContainerRef is not sufficient.
This commit adds the logic to invoke the process of dehydrated views lookup from the `template` instruction, thus enabling it for new control flow instructions as well.
PR Close#51915
This commit updates hydration runtime code to avoid creating an empty array when we can avoid it. Instead, we just check whether the field is `null` directly (without using nullish coalescing).
PR Close#51917
This commit updates runtime logic of defer blocks to schedule a single `requestIdleCallback` for a group of defer blocks created within a single change detection cycle (for example, as a result of a defer block being defined in a for loop).
PR Close#51750
Switches the syntax for blocks from `{#block}{/block}` to `@block {}` based on the feedback from the community.
Read more about the decision-making process in our blog: https://blog.angular.io/meet-angulars-new-control-flow-a02c6eee7843
The existing block types changed in the following ways:
**Conditional blocks:**
```html
<!-- Before -->
{#if cond}
Main content
{:else if otherCond}
Else if content
{:else}
Else content
{/if}
<!-- After -->
@if (cond) {
Main content
} @else if (otherCond) {
Else if content
} @else {
Else content
}
```
**Deferred blocks**
```html
<!-- Before -->
{#defer when isLoaded}
Main content
{:loading} Loading...
{:placeholder} <icon>pending</icon>
{:error} Failed to load
{/defer}
<!-- After -->
@defer (when isLoaded) {
Main content
} @loading {
Loading...
} @placeholder {
<icon>pending</icon>
} @error {
Failed to load
}
```
**Switch blocks:**
```html
<!-- Before -->
{#switch value}
{:case 1}
One
{:case 2}
Two
{:default}
Default
{/switch}
<!-- After -->
@switch (value) {
@case (1) {
One
}
@case (2) {
Two
}
@default {
Default
}
}
```
**For loops**
```html
<!-- Before -->
{#for item of items; track item}
{{item.name}}
{:empty} No items
{/for}
<!-- After -->
@for (item of items; track item) {
{{item.name}}
} @empty {
No items
}
```
PR Close#51891
This commit adds a logic to handle `on immediate` conditions both as a main condition, as well as a prefetching condition (i.e. `prefetch on immediate`).
PR Close#51630
Adds support for `on viewport` and `prefetch on viewport` triggers which will load the deferred content when the element comes into the view.
PR Close#51874
Adds support for `on hover` and `prefetch on hover` triggers. Some code had to be moved around so it could be reused from the `on interaction` triggers.
PR Close#51874
Updates the logic that generates the instructions for the `on interaction` and `prefetch on interaction` triggers to their final shape. Now the instructions take two arguments:
1. `triggerIndex` - index at which to find the trigger in the view where it will be rendered.
2. `walkUpTimes` - tells the runtime how many views up it needs to go to find the trigger element. If the argument is omitted, it means that the trigger is in the same view as the deferred block. A positive number means that the runtime needs to go up X amount of times to find the trigger. A negative number means that the trigger is inside the root view of the placeholder block. Negative numbers are capped at -1 since the placeholder is always in the same position at runtime.
PR Close#51830
The `Writable` type is usefull when we want overwrite readonly properties and we still want to maintain code navigation/reference. It should be use instead of `any` type assertions for example.
PR Close#49754
The `Writable` type is usefull when we want overwrite readonly properties and we still want to maintain code navigation/reference. It should be use instead of `any` type assertion for example.
PR Close#49754
This change simply flip the flag which enables using the deps tracker in JIT compilation (the logic is already implemented in a previous PR). Some tests which depend on the old JIT implementation (e.g., patching the scope info into the type) are modified accordingly.
PR Close#51415
Using verification helpers such as `isComponent` may trigger JIT compilation. Now in some tests such compilation is made purposely to fail, and so in such cases any reference to the `depsTracker.clearScopeCacheFor` method will cause the exception to be thrown earlier than expected which results in teh test failure. Such scenario is the case in the next commit when we enable using the deps tracker in the jit compilation. Note that such failure is only for the framework tests and is a very edge case. The tests in downstream apps will not lead to such scenario of failure at all.
PR Close#51415
This commit adds the necessary mechanisms to perform cleanup of prefetch triggers when resource loading starts. Previously, this logic was missing, which resulted in retaining those triggers.
PR Close#51856
Certain tools in g3 which dynamically bootstrap a component (e.g., custom routers) simply swallow the exception coming from bootstrapping the component and show an empty outlet. Such cases are very difficult to debug as the dev has no clue why the component was not rendered. As bad as this pattern is, fixing all such tools for a better error handling is beyond the scope of our effort. Instead, in this change we print the error messages coming from calculating component dependencies (part of component rendering) to the console for a better visibility into the error. This change only affects local compilation where the component dependencies are calculated in runtime. This change can potentially shed light into many failures of local compilation in g3.
PR Close#51824
Standalone component need to include the imported NgModules as part of their dependencies in order to be able to use the injection tokens coming from these NgModules. To do so, in this change the imported NgModules are included in the standalone component compilation scope.
PR Close#51819
Currently deps tracker includes the exported scope of the exported NgModule only in the exported scope of that NgModule. This is in agreement with what AoT does today. But JIT diverges from this behavior by including these exported scopes into the compilation scope as well. Since deps tracker is going to be used for both AoT (local compilation mode) and JIT, the question might be which behavior the deps tracker should follow? Today it follows the AoT one, but it breaks some tests in Google which seem to depend on this behavior of JIT. So it is better to migrate deps tracker to what JIT does. This leads to a wider compilation scope in local compilation compared to full compilations, but it won't break any existing thing.
PR Close#51791
This change contains runtime logic needed to flatten the NgModule bootstrap field in local compilation mode. While it is quite odd to pass a "nested" array as NgModule bootstrap, it is still required to support this case in local compilation mode since it is supported in full compilation mode.
PR Close#51767
This change flattens the imports info on standalone component decorators in runtime dev mode by adding flattening logic to the deps tracker. Such flattening has no effect in AoT full compilation mode since these arrays are already resolved and flattened by AoT static analysis, but in local compilation mode it is needed since the raw array as appears on the component decorator will be passed to the deps tracker, and so it needs to be flattened.
This change does not affect prod runtime since deps tracker is only used in dev mode.
PR Close#51767
This change flattens the imports/exports/declarations info on ngModule decorators in runtime dev mode by adding flattening logic to the runtime `ɵɵsetNgModuleScope`. Such flattening has no effect in AoT full compilation mode since these arrays are already resolved and flattened by AoT static analysis, but in local compilation mode it is needed since the raw array as appears on the NgModule decorator will be passed to the runtime `ɵɵsetNgModuleScope`, and so it needs to be flattened.
This change has to effect on prod runtime as `ɵɵsetNgModuleScope` is not used in prod.
PR Close#51767
Currently when ESBuild bundles an application importing from
`@angular/core`, the signals library will be discovered during
export analysis. ESBuild will come across the constants for the reactive
signal graph- and end up considering some of these as side-effects given
the pattern of using a spread assignment for extending from e.g.
`REACTIVE_NODE` (a similar issue may occur if we e.g. extend from the
computed reactive node).
See more details on the issue: https://github.com/evanw/esbuild/issues/3392
Even though, ESBuild preserves these constants now, and all of its
dependencies— Terser will consider these as side-effect free and
eliminate these constants. This may require multiple passes though, and
might not be sufficient, depending on the chain of reactive node
extensions. E.g. in the signals branch we noticed some constants
unnecessarily being preserved.
PR Close#51809
Terser does not treat `Symbol` as side-effect free- so if we end up with
a symbol export being loaded, it will result in the symbol being
retained.
We noticed this in the signals prototyping where symbols exported
from `computed` ended up appearing in symbol bundling tests.
PR Close#51776
This commit moves the destroy logic from 'effect' in the lower-level
'watch' so this implementation is shared among varius watch implementations.
PR Close#51757
Certain code patterns and tools in Google (and possibly 3P world) lead to the situation that a component is bootstrapped/rendered without its ng-module being loaded in the browser. Technically speaking this should be an anti-pattern since the ng-module could contain some runtime logic (e.g., providing something, calling some services, etc) and its not being loaded leads to unexpected behaviour. However, in many cases ng-module is an empty class and its only usage is for providing scope, and since in AoT full compilation mode we already hard-code dependencies into components so we can get away with not loading the ng-module. But in AoT local compilation mode it is not possible to get away since the component's dependencies are computed in runtime and the presence of the corresponding ng-module in the browser is needed. For this reason in this change it is forbidden to attempt to render a component without first loading its ng-module in local compilation mode and an explicit error message is created to make this situation clear. This error message can help with catching such cases when running TGP in Google.
It would be an interesting question as to whether to ban this situation in full compilation mode as well, as it is error prone and these errors are sometimes very hard to debug.
PR Close#51726
This commit adds explicit type annotations to the reactive node prototype objects,
such that the prototypes are type-checked against the interface they are supposed
to (partially) implement. This also allows IDEs to better track usages of reactive
node properties, improving code navigation.
PR Close#51722
When a producer is no longer used, the consumer has to update its internal data structure
that keeps track of all producers. There used to be an issue where only half of the stale
producers would actually be removed from this data structure, as the intended upper bound
of the number of producers to remove would decrease with each removed producer, therefore
not reaching all producers that should be removed from the data structure.
This commit fixes the issue by truncating the arrays directly, without going through
individual `pop` operations. An assertion that would catch the inconsistent state in
the internal data structures of the signal graph has been introduced.
PR Close#51722
Adds support for passing in `@Component.styles` as a string. Also introduces a new `styleUrl` property on `@Component` for providing a single stylesheet. This is more convenient for the most common case where a component only has one stylesheet associated with it.
PR Close#51715
Currently internally Angular has some customized tsconfig files, because we don't align with the tsconfig of the rest of g3. These changes enable `noImplicitReturns` and `noPropertyAccessFromIndexSignature` to align better with the internal config.
PR Close#51728
Previously effects were queued as they became dirty, and this queue was
flushed at various checkpoints during the change detection cycle. The result
was that change detection _was_ the effect runner, and without executing CD,
effects would not execute. This leads a particular tradeoff:
* effects are subject to unidirectional data flow (bad for dx)
* effects don't cause a new round of CD (good/bad depending on use case)
* effects can be used to implement control flow efficiently (desirable)
This commit changes the scheduling mechanism. Effects are now scheduled via
the microtask queue. This changes the tradeoffs:
* effects are no longer limited by unidirectional data flow (easy dx)
* effects registered in the Angular zone will trigger CD after they run
(same as `Promise.resolve` really)
* the public `effect()` type of effect probably isn't a good building block
for our built-in control flow, and we'll need a new internal abstraction.
As `effect()` is in developer preview, changing the execution timing is not
considered breaking even though it may impact current users.
PR Close#51049
Improves the error handling story for after*Render by delegating errors to an ErrorHandler, so that one failure does not break every callback.
PR Close#51662
This commit updates the logic to add `prefetch on idle` support for defer blocks. Previously, the `on idle` logic was already implemented for the main loading and rendering. This commit reuses the same logic to bring it to the prefetching mechanism.
PR Close#51629
This flag allows message event listeners to prevent callbacks from executing within the NgZone if they contain a special `__ignore_ng_zone__` flag.
This functionality is built with Angular DevTools in mind, where it prevents an infinite change detection loop in inspecting applications that have message event listeners:
CD -> Inspected app emits componentTreeDirty event to DevTools -> DevTools emits event to get new component Tree from Inspected app -> Inspected app message event listener fires -> CD
PR Close#51339