This fixes a collision between #30639 and #30543 where the latter added
usages of @ViewChild without the static flag present, but the former
made the flag required.
PR Close#30666
This commit makes the static flag on @ViewChild and @ContentChild required.
BREAKING CHANGE:
In Angular version 8, it's required that all @ViewChild and @ContentChild
queries have a 'static' flag specifying whether the query is 'static' or
'dynamic'. The compiler previously sorted queries automatically, but in
8.0 developers are required to explicitly specify which behavior is wanted.
This is a temporary requirement as part of a migration; see
https://angular.io/guide/static-query-migration for more details.
@ViewChildren and @ContentChildren queries are always dynamic, and so are
unaffected.
PR Close#30639
This patch in the second runtime change which refactors how styling
bindings work in Angular. This patch refactors how map-based
`[style]` and `[class]` bindings work using a new algorithm which
is faster and less complex than the former one.
This patch is a follow-up to an earlier refactor which enabled
support for prop-based `[style.name]` and `[class.name]`
bindings (see f03475cac8).
PR Close#30543
This is a new feature of the Ivy TestBed.
A common user pattern is to test one component with another. This is
commonly done by creating a `TestFixture` component which exercises the
main component under test.
This pattern is more difficult if the component under test is declared in an
NgModule but not exported. In this case, overriding the module is necessary.
In g3 (and View Engine), it's possible to use an NgSummary to override the
recompilation of a component, and depend on its AOT compiled factory. The
way this is implemented, however, specifying a summary for a module
effectively overrides much of the TestBed's other behavior. For example, the
following is legal:
```typescript
TestBed.configureTestingModule({
declarations: [FooCmp, TestFixture],
imports: [FooModule],
aotSummaries: [FooModuleNgSummary],
});
```
Here, `FooCmp` is declared in both the testing module and in the imported
`FooModule`. However, because the summary is provided, `FooCmp` is not
compiled within the context of the testing module, but _is_ made available
for `TestFixture` to use, even if it wasn't originally exported from
`FooModule`.
This pattern breaks in Ivy - because summaries are a no-op, this amounts
to a true double declaration of `FooCmp` which raises an error.
Fixing this in user code is possible, but is difficult to do in an
automated or backwards compatible way. An alternative solution is
implemented in this PR.
This PR attempts to capture the user intent of the following previously
unsupported configuration:
```typescript
TestBed.configureTestingModule({
declarations: [FooCmp, TestFixture],
imports: [FooModule],
});
```
Note that this is the same as the configuration above in Ivy, as the
`aotSummaries` value provided has no effect.
The user intent here is interpreted as follows:
1) `FooCmp` is a pre-existing component that's being used in the test
(via import of `FooModule`). It may or may not be exported by this
module.
2) `FooCmp` should be part of the testing module's scope. That is, it
should be visible to `TestFixture`. This is because it's listed in
`declarations`.
This feature effectively makes the `TestBed` testing module special. It's
able to declare components without compiling them, if they're already
compiled (or configured to be compiled) in the imports. And crucially, the
behavior matches the first example with the summary, making Ivy backwards
compatible with View Engine for tests that use summaries.
PR Close#30578
Depending on which placeholders the translation uses, there are some legitimate cases where we might not use all placeholder replacements in `i18nPostprocess`. For example if some of the placeholders of the original messages have been removed in the translation.
FW-1312 #resolve
PR Close#30632
Prior to this change a component was considered unresolved (i.e. having dynamic resources that should be loaded, like external template or stylesheets) even if template override was provided as an empty string (for example, via TestBed.overrideTemplateUsingTestingModule call). This commit fixes the condition that previously treated empty string as an absent template value.
PR Close#30602
With Ivy, injecting a `ViewContainerRef` for a `<ng-container>` element
results in two comments generated in the DOM. One comment as host
element for the `ElementContainer` and one for the generated `LContainer`
which is needed for the created `ViewContainerRef`.
This is problematic as developers expect the same anchor element for
the `LContainer` and the `ElementContainer` in order to be able to move
the host element of `<ng-container>` without leaving the actual
`LContainer` anchor element at the original location.
This worked differently in View Engine and various applications might
depend on the behavior where the `ViewContainerRef` shares the anchor
comment node with the host comment node of the `<ng-container>`. For
example `CdkTable` from `@angular/cdk` moves around the host element of
a `<ng-container>` and also expects embedded views to be inserted next
to the moved `<ng-container>` host element.
See: f8be5329f8/src/cdk/table/table.ts (L999-L1016)
Resolves FW-1341
PR Close#30611
Prior to this change we processed binding expression (including bindings with pipes) in i18n attributes before we generate update instruction. As a result, slot offsets for pipeBind instructions were calculated incorrectly. Now we perform binding expression processing when we generate "update block" instructions, so offsets are calculated correctly.
PR Close#30573
There is an encoding issue with using delta `Δ`, where the browser will attempt to detect the file encoding if the character set is not explicitly declared on a `<script/>` tag, and Chrome will find the `Δ` character and decide it is window-1252 encoding, which misinterprets the `Δ` character to be some other character that is not a valid JS identifier character
So back to the frog eyes we go.
```
__
/ɵɵ\
( -- ) - I am ineffable. I am forever.
_/ \_
/ \ / \
== == ==
```
PR Close#30546
Moves all manual render3 view_container_ref tests that use property
bindings to acceptance tests with TestBed.
Two issues surfaced and refer to a difference between Ivy and View
engine:
* Multi-slot projection is not working with Ivy: FW-1331
* ViewContainerRef throws if index is invalid while View Engine clamped index: FW-1330
PR Close#30488
This is the first refactor PR designed to change how styling bindings
(i.e. `[style]` and `[class]`) behave in Ivy. Instead of having a heavy
element-by-element context be generated for each element, this new
refactor aims to use a single context for each `tNode` element that is
examined and iterated over when styling values are to be applied to the
element.
This patch brings this new functionality to prop-based bindings such as
`[style.prop]` and `[class.name]`.
PR Close#30469
Moves most of the tests from `render3/integration_spec` into `acceptance`. Note that there are still a handful of tests left in render3, because we don't have a way of moving all of them to go through `TestBed` since they either have r3-specific assertions or we don't have access to the same APIs as the raw instructions.
PR Close#30461
Ports render3 onDestroy tests over to be acceptance tests. Removes old render3 tests if possible.
Note the onlyInIvy test for one area where Ivy has a different behavior than ViewEngine
PR Close#30445
- Adds inheritance tests for many combinations of directive, component and bare class inheritance
- Adds tests that are failing in ivy, but should work, marks them with `xit` and a TODO.
- Removes render3 unit tests that cover the same things.
PR Close#30442
In View Engine, we would simply ignore host style bindings on template nodes. In Ivy,
we are throwing a "Cannot read length of undefined" error instead. For backwards
compatibility, we should also ignore these bindings rather than blowing up.
PR Close#30498
In View engine it is possible to instantiate a service that that has no
`@Injectable` decorator as long as it satisfies one of:
1) It has no dependencies and so a constructor with no parameters.
This is already supported in Ivy.
2) It has no constructor of its own and sub-classes a service which has
dependencies but has its own `@Injectable` decorator. This second
scenario was broken in Ivy.
In Ivy, previous to this commit, if a class to be instantiated did not have
its own `@Injectable` decorator and did not provide a constructor of
its own, then it would be created using `new` with no arguments -
i.e. falling back to the first scenario.
After this commit Ivy correctly uses the `ngInjectableDef` inherited
from the super-class to provide the `factory` for instantiating the
sub-class.
FW-1314
PR Close#30388
- Moves template ref tests from render3 unit tests to acceptance tests.
- Marks tests testing ivy specific changes as `onlyInIvy`.
- Deletes old render3 unit tests that are no longer necessary
PR Close#30443
Preserve compatibility with rollup_bundle rule.
Add missing npm dependencies, which are now enforced by the strict_deps plugin in tsc_wrapped
PR Close#30370
Moves most of the r3 change detection tests into `acceptance`. Notes:
* A handful of tests weren't migrated, because they were testing an API that isn't exposed publicly yet.
* The `should throw if bindings in children of current view have changed` and `should NOT throw if bindings in ancestors of current view have changed` tests were removed, because there's not nice way of hitting the same code path with `TestBed` and doing the same assertion as with the raw instructions. I'm open to ideas on how we could do them.
* There were a few tests that assert that the `innerHTML` looks in a particular way. I've switched them to use `textContent`, because Ivy and ViewEngine produce slightly different DOM. The tests were only checking whether the text has changed anyway.
PR Close#30425
Moves all manual render3 property binding tests to
TestBed acceptance tests. Unfortunately three property
binding tests could not be migrated as these rely on
manual Ivy template code that is not supported within
TestBed. These can be revisited as discussed in the
framework team meeting.
PR Close#30426
Moves all manual render3 tests which are located within the
`renderer_factory_spec.ts` file to acceptance tests. A few tests
that use Ivy-specific logic which is not replicable with `TestBed`
remain in the render3 folder (e.g. using `renderTemplate`)
Additionally migrated tests that assert the lifecycles of the
renderer_factory are set to *ivy only* as the lifecycle seems
to be different in Ivy. Tracked with: FW-1320
PR Close#30435
Currently in Ivy `NgModule` registration happens when the class is declared, however this is inconsistent with ViewEngine and requires extra generated code. These changes remove the generated code for `registerModuleFactory`, pass the id through to the `ngModuleDef` and do the module registration inside `NgModuleFactory.create`.
This PR resolves FW-1285.
PR Close#30244
- Moves tests related to the pureFunction instructions from render3 to acceptance tests
- Leaves behind one test for in-template javascript that is not supported syntax yet
PR Close#30406
Moves over the tests from `pipe_spec` into `acceptance`. Note that the two `WrappedValue` tests haven't been moved over, because impure pipes always throw "changed after checked" errors in `TestBed`. This seems to be consistent with ViewEngine.
PR Close#30389
Moves most of the tests in `output_spec` into `acceptance`. Note that one test is left in `render3`, because it's testing mixing in custom logic with instructions which we can't replicate using `TestBed`.
PR Close#30372
Moves all manual `render3` content projection tests that use
the `ɵɵelementProperty` to acceptance tests. Additionally a
few other content projection tests were moved over to
acceptance. Eventually we'll be able to move all remaining
content projection tests to acceptance.
PR Close#30357
This commit moves the delegated constructor detection to a helper
function and also adds more test coverage.
The original code for this came from https://github.com/angular/angular/pull/24156
thanks to @ts2do.
Closes#24156Closes#27267
// FW-1310
PR Close#30368
Even though we don't run the size-tracking test on CI
right now, we update the golden size map as part of
the size-tracking tool update. The size-map difference
should generally be kept up-to-date to be able to
determine which PRs contribute size to a given file.
PR Close#30257
Based on discussion that happened on the PR that introduced
the size-tracking tool, we want to have another threshold for
the raw byte difference. This allows us to better control for
which changes the size-tracking tool should report a difference.
See: https://github.com/angular/angular/pull/30070#discussion_r278332315
PR Close#30257
- splits existing property acceptance tests into property_binding and property_interpolation
- ports tests from render3 instructions tests to acceptance tests
- removes redundant or unnecessary tests that are covered by existing acceptance tests
:)
PR Close#30321
We have an issue where we would like to be able to test perf counter metrics in acceptance tests, but we are unable to do so, because it will break when those same tests are run with ViewEngine. This PR adds a testing utility to `onlyInIvy` that allows for testing of performance counters, and even gives readable errors for what value on `ngDevMode` is incorrect. Has typings for decent autocompletion as well.
PR Close#30339
This is the final patch to migrate the Angular styling code to have a
smaller instruction set in preparation for the runtime refactor. All
styling-related instructions now work both in template and hostBindings
functions and do not use `element` as a prefix for their names:
BEFORE:
elementStyling()
elementStyleProp()
elementClassProp()
elementStyleMap()
elementClassMap()
elementStylingApply()
AFTER:
styling()
styleProp()
classProp()
styleMap()
classMap()
stylingApply()
PR Close#30318
This patch removes all host-specific styling instructions in favor of
using element-level instructions instead. Because of the previous
patches that made sure `select(n)` worked between styling calls, all
host level instructions are not needed anymore. This patch changes each
of those instruction calls to use any of the `elementStyling*`,
`elementStyle*` and `elementClass*` styling instructions instead.
PR Close#30336
Fixes not being able to bind a `SafeStyle` as a camel cased style property (e.g. `[style.backgroundImage]="someSafeStyle"`). The issue was due to the fact that we only check the dash case property names to determine whether to sanitize a value.
This PR resolves FW-1279.
PR Close#30328
This patch is one commit of many patches that will unify all styling instructions
across both template-level bindings and host-level bindings. This patch in particular
removes the `elementIndex` param because it is already set prior to each styling
instruction via the `select(n)` instruction.
PR Close#30313
This patch breaks up the existing `elementStylingMap` into
`elementClassMap` and `elementStyleMap` instructions. It also breaks
apart `hostStlyingMap` into `hostClassMap` and `hostStyleMap`
instructions. This change allows for better tree-shaking and reduces
the complexity of the styling algorithm code for `[style]` and `[class]`
bindings.
PR Close#30293
This commit fixes a regression introduced in PR 29692 where
the interpolate symbol in View Engine was improperly prefixed
with the ɵɵ that signifies private instructions for Ivy. It
resulted in interpolations of 10+ values not working correctly
in AOT mode. This commit removes the prefix.
PR Close#30243
Ivy uses R3Injector, but we are currently pulling in both the StaticInjector
(View Engine injector) and the R3Injector when running with Ivy. This commit
adds an ivy switch so calling Injector.create() pulls in the correct
implementation of the injector depending on whether you are using VE or Ivy.
This saves us about 3KB in the bundle.
PR Close#30219
Previously, we were supporting injection flags for provider deps, but only
if they fit the format `new Optional()`. This commit fixes resolution of
provider deps to also support `Optional` (without the new). This keeps us
backwards compatible with what View Engine supported.
PR Close#30216
Stores the views that are part of a container directly on the `LContainer`, rather than maintaining a dedicated sub-array.
This PR resolves FW-1288.
PR Close#30179
Currently, we are not properly resolving forward refs when they appear
in deps for providers created with the useFactory strategy. This commit
wraps provider deps in the resolveForwardRef call so the tokens are
passed into the inject function as expected.
PR Close#30201
Fixes `HostBinding` and `HostListener` declarations not being inherited from base classes that don't have an Angular decorator.
This PR resolves FW-1275.
PR Close#30158
Introduces a new Bazel test that allows us to inspect
what source-files contribute to a given bundled file
and how much bytes they contribute to the bundle size.
Additionally the size-tracking rule groups the size
data by directories. This allows us to compare size
changes in the scope of directories. e.g. a lot of
files in a directory could increase slightly in size, but
in the directory scope the size change could be significant
and needs to be reported by the test target.
Resolves FW-1278
PR Close#30070
Fixes Ivy reflecting properties with `undefined` values, rather than omitting them. Also fixes that Ivy doesn't clear the reflected values when property value changes from something that is defined to undefined.
This PR resolves FW-1277.
PR Close#30103
Move tests for special tokens like `Injector`, `ElementRef`, `TemplateRef`, `ViewContainerRef`, `ChangeDectetorRef` and custom string tokens.
PR Close#29299
- Extracts and documents code that will be common to interpolation instructions
- Ensures that binding indices are updated at the proper time during compilation
- Adds additional tests
Related #30011
PR Close#30129
The `renderStringify` function is used in a lot of performance-sensitive places, however it contains a megamorphic read which is used primarily for error messages. These changes introduce a new function that can be used to stringify output for errors and removes the megamorphic read from `renderStringify`.
This PR resolves FW-1286.
PR Close#30082
Fixes view and content queries not being inherited in Ivy, if the base class hasn't been annotated with an Angular decorator (e.g. `Component` or `Directive`).
Also reworks the way the `ngBaseDef` is created so that it is added at the same point as the queries, rather than inside of the `Input` and `Output` decorators.
This PR partially resolves FW-1275. Support for host bindings will be added in a follow-up, because this PR is somewhat large as it is.
PR Close#30015
Fixes Ivy throwing an error because it tries to generate styling instructions for empty `style` and `class` bindings.
This PR resolves FW-1274.
PR Close#30024
Previously, we had a bug where directive matching could fail if the directive
attribute was bound and followed a certain number of classes. This is because
in the matching logic, we were treating classes like normal attributes. We
should instead be skipping classes in the attribute matching logic. Otherwise
classes will match for directives with attribute selectors, and as we are
iterating through them in twos (when they are stored as name-only, not in
name-value pairs), it may throw off directive matching for any bound attributes
that come after. This commit changes the directive matching logic to skip
classes altogether.
PR Close#30002
We only set ng-reflect properties on directive input bindings.
This PR ensures that we also add ng-reflect properties on unbound inputs for backwards compatibility.
FW-1266 #resolve
PR Close#29973
Previous to this change, we assumed embedded views could only be created after
their parent template node had completed processing. As a result, we only set
up query logic for containers after directives on the node were created.
However, this assumption didn't take into account the case where a directive
on a template node could create views in its constructor.
This commit fixes query logic to work with views created in constructors.
In that case, we need to create a query container before the new view is
rendered so query results in the view aren't lost. But since the query container
is created before directives have completed processing, we also have to ensure
that query results gathered later on the template node are inserted before that
query container. Otherwise, query results in embedded views will clobber query
results on template nodes.
This splice mode may be slightly slower than the normal matching for queries on
containers, but we should only fall back to this strategy in the edge case where
views are created in constructors. (We should encourage developers to create
views in ngOnInit instead).
PR Close#29983
Prior to this change, components created via TestBed.createComponent in the same test were placed into the same root context, which caused problems in conjunction with fixture.autoDetectChanges usage in the same test. Specifically, change detection was triggered immediately for created component (starting from the 2nd one) even if it was not required/desired. This commit makes Ivy and VE behavior consistent: now every component created via TestBed.createComponent is isolated from each other. Current solution uses host element id naming convention, which is not ideal, but helps avoid public API surface changes at this point (we might revisit this approach later).
Note: this commit also adds extra tests to verify bootstrap and change detection behavior in case of multiple components in `bootstrap` array in @NgModule, to make sure this behavior is aligned between Ivy and VE.
PR Close#29981
The `TNode.cleanup` data structure can contain sequences of 4-element
sequence of entries (event handlers, directive outputs) mixed with
2-element sequence of entries (QueryList cleanup). Before this fix
we would always skip 4 elements in the `TNode.cleanup` while looking
up event handler cleanups. 4-element skips are not correct in case
of query cleanup presence and this commit corrects the algorithm to
jump 4 or 2 elements depending on a type of cleanup encountered.
PR Close#29957
If a component has its definition set by defineComponent (as opposed to
JIT getter), then it will generate a factory that uses directiveInject()
to retrieve its dependencies. This can be problematic in test code because
tests could use the injection utility before bootstrapping the component,
and directiveInject() relies on the view having been created.
This commit tweaks directiveInject() to fall back to inject() if the view
has not been created. This will allow injection to work in tests even if
it is called before the component is bootstrapped.
PR Close#29948
Previous to this commit, providing a component or directive in a test
module without @Injectable() would throw because the injectable factory
would not be found. Providing components in tests in addition to declaring
or importing them is not necessary, but it should not throw an error.
This commit ensures factory data is saved when component defs and directive
defs are created, which allows them to be processed by the module injector.
Note that bootstrapping is still required for this setup to work because
directiveInject() does not support cases where the view has not been
created. This case will be handled in a future commit.
PR Close#29945
We had a bug where event.preventDefault() was not always called if listeners
were coalesced. This is because we were overwriting the previous listener's
result every time we called the next listener, so listeners early in the chain
that returned false would be ignored and preventDefault would not be called.
This commit fixes that issue, so now preventDefault() is called if any listener
in a coalesced chain returns false. This brings us in line with View Engine
behavior.
PR Close#29934
Overriding multi provider values (providers with `multi: true` flag) via TestBed require additional handling: all existing multi-provider values for the same token should be removed from the override list, so that they are not included into the final value of a given provider. This commit adds this logic to make sure we handle multi providers correctly.
PR Close#29919
Because the styling context may be stored in a different location
and be apart of a sub array, reading the styling context each time
a host binding is evaluated is costly. This patch ensures that the
active styling context is cached so that multiple interactions with
styling bindings can easily retrieve the styling context efficiently.
PR Close#29818
Plural ICU expressions depend on the locale (different languages have different plural forms). Until now the locale was hard coded as `en-US`.
For compatibility reasons, if you use ivy with AOT and bootstrap your app with `bootstrapModule` then the `LOCALE_ID` token will be set automatically for ivy, which is then used to get the correct plural form.
If you use JIT, you need to define the `LOCALE_ID` provider on the module that you bootstrap.
For `TestBed` you can use either `configureTestingModule` or `overrideProvider` to define that provider.
If you don't use the compat mode and start your app with `renderComponent` you need to call `ɵsetLocaleId` manually to define the `LOCALE_ID` before bootstrap. We expect this to change once we start adding the new i18n APIs, so don't rely on this function (there's a reason why it's a private export).
PR Close#29249
Prior to this change, element attributes annotated with i18n- prefix were removed from element attribute list and processed separately by i18n-specific logic. This behavior is causing issues with directive matching, since attributes are not present in the list of attrs for matching purposes. This commit updates i18n logic to retain attributes in the main attribute list, thus allowing directive matching logic to work correctly.
PR Close#29856
In order to be backwards compatible with View Engine, Ivy should log
errors by default in the TestBed error handler rather than re-throwing
them. Re-throwing the errors is a breaking change that causes issues with
libraries like ngrx that have async behavior and custom error handling.
This logging approach has issues (for both VE and Ivy) because it can allow
tests to pass inappropriately if errors are thrown inside listeners. However,
since re-throwing would be breaking and requires a larger redesign, we should
wait until post-Ivy.
PR Close#29853
The `Δ` caused issue with other infrastructure, and we are temporarily
changing it to `ɵɵ`.
This commit also patches ts_api_guardian_test and AIO to understand `ɵɵ`.
PR Close#29850
So far using runtime i18n with ivy meant that you needed to use Closure and `goog.getMsg` (or a polyfill). This PR changes the compiler to output both closure & non-closure code, while the unused option will be tree-shaken by minifiers.
This means that if you use the Angular CLI with ivy and load a translations file, you can use i18n and the application will not throw at runtime.
For now it will not translate your application, but at least you can try ivy without having to remove all of your i18n code and configuration.
PR Close#28689
Currently in Ivy we pass both the raw and parsed selectors to the projectionDef instruction, because the parsed selectors are used to match most nodes, whereas the raw ones are used to match against nodes with the ngProjectAs attribute. The raw selectors add a fair bit of code that won't be used in most cases, because ngProjectAs is somewhat rare.
These changes rework the compiler not to output the raw selectors in the projectionDef, but to parse the selector in ngProjectAs and to store it on the TAttributes. The logic for matching has also been changed so that it matches the pre-parsed ngProjectAs selector against the list of projection selectors.
PR Close#29578
- Adds the instructions
- Adds tests for all instructions
- Adds TODO to remove all tests when we are able to test this with TestBed after the compiler is updated
PR Close#29576
Fixes the creation mode block not being run on components which have been detached from change detection.
This PR resolves FW-1217.
Fixes#29645.
PR Close#29741
Fixes Ivy not throwing an error if it runs into an invalid property binding on a container node (e.g. `<div *ngFor="let row of rows">` instead of `<div *ngFor="let row if rows">`).
This PR resolves FW-1219.
PR Close#29691
The new styling algorithm in angular is designed to evaluate host
bindings stylinh priority in order of directive evaluation order. This,
however, does not work with respect to parent/sub-class directives
because sub-class host bindings are run after the parent host bindings
but still have priority. This patch ensures that the host styling bindings
for parent and sub-class components/directives are executed with respect
to the styling algorithm prioritization.
Jira Issue: FW-1132
PR Close#29602
Prior to this change, any provider that was independently resolved using
its InjectableDef would not be considered when destroying the module it
was requested from. This commit provides a fix for this issue by storing
the resolved provider in the module's list of provider definitions.
Fixes#28927
PR Close#28943
Simply adds a `debug` property to the array of create opcodes while inside
`readCreateOpCodes` in i18n. This `debug` property has a property called `operations`
that is a human-readable list of operations that will be performed, as derived
from the op codes themselves, and the view it's acting upon.
PR Close#29348
- moves all publicly exported instructions to their own files
- refactors namespace instructions to set state in `state.ts`
- no longer exports * from `instructions.ts`.
- `instructions.ts` renamed to `shared.ts` (old `shared.ts` contents folded in to `instructions.ts`)
- updates `all.ts` to re-export from public instruction files.
PR Close#29646
- Adds `property` instruction
- Does _NOT_ add compiler changes to accommodate `property` instruction, that will be a follow up PR.
- Updates `select` instruction to set the selected index in state.
- Adds dev mode assertions around the selected index state.
Related #29527
PR Close#29513
When an @NgModule is imported more than once in the testing module (for
example it appears in the imports of more than one module, or if it's
literally listed multiple times), then TestBed had a bug where the
providers for the module would be overridden many times.
This alone was problematic but would not break tests. However, the original
value of the providers field of the ngInjectorDef was saved each time, and
restored in the same order. Thus, if the provider array was [X], and
overrides were applied twice, then the override array would become
[X, X'] and then [X, X', X, X']. However, on the second override the state
[X, X'] would be stored as original. The array would then be restored to
[X] and then [X, X'].
Each test, therefore, would continue to double the size of the providers
array for the module, eventually exhausting the browser's memory.
This commit adds a Set to track when overrides have been applied to a module
and refrain from applying them more than once.
PR Close#29571
Prior to this change, recompilation of AOT-compiled components in TestBed may fail when template override is requested. That was happening due to the `styleUrls` field defined for a Component, thus switching its state to "requires resolution" (i.e. having external resources) at compile time. This change avoids this issue by storing styles and resetting `styleUrls` field before recompilation. Once compilation is done, saved styles are patched back onto Component def.
PR Close#29555
- Adds `property` instruction
- Does _NOT_ add compiler changes to accommodate `property` instruction, that will be a follow up PR.
- Updates `select` instruction to set the selected index in state.
- Adds dev mode assertions around the selected index state.
Related #29527
PR Close#29513
This commit removes code duplication where we had 2 versions of a
`flatten` utility. Moreover this change results in queries using
a non-recursive version of `flatten` which should result in a better
performance of query refresh operations.
PR Close#29547
Prior to this change, Ivy version of TestBed was not designed to support the logic to avoid recompilations - most of the Components/Directives/Pipes were recompiled for each test, even if there were no overrides defined for a given Type. Additional checks to avoid recompilation were introduced in one of the previous commits (0244a2433e), but there were still some corner cases that required attention. In order to support the necessary logic better, Ivy TestBed was rewritten/refactored. Main results of this rewrite are:
* no recompilation for Components/Directives/Pipes without overrides
* the logic to restore state between tests (isolate tests) was improved
* transitive scopes calculation no longer performs recompilation (it works with compiled defs)
As a result of these changes we see reduction in memory consumption (3.5-4x improvement) and pefromance increase (4-4.5x improvement).
PR Close#29483
The API changes are due to enabling strict checks in TypeScript (via `strict: true`).
The payload size changes in `polyfills.js` are due to more browser APIs being patched in recent versions (e.g. `fetch`, `customElement v1`).
PR Close#28219
In View Engine, we used to generate empty QueryLists for content queries on root
components (though we did not actually support populating these lists). We need
to keep this behavior in Ivy for backwards compatibility. Otherwise, components
that are sometimes used as root will fail if they are relying on content query
results to always be defined.
PR Close#29514
In some cases ivy expects projectable nodes to be passed in a different order
to ViewEngine. Specifically, ivy expects the catch-all ("*") to be at index
0, whereas ViewEngine expects it to be at its position at which it was parsed
in the template.
This commit adds one test that breaks under ivy and others that just describe
more accurately what happens in corner cases.
PR Close#27791
This patch is the first of a few patches which separates the
styling logic between template bindings (e.g. <div [style])
from host bindings (e.g. @HostBinding('style')). This patch
in particular introduces a series of host-specific styling
instructions and changes the existing set of template styling
instructions not to accept directives. The underyling code (which
communicates with the styling algorithm) still works as it did
before.
This PR also separates the styling instruction code into a separate
file and moves over all other instructions into an dedicated
instructions directory.
PR Close#29292
Prior to this change, we always recompile all Components/Directives/Pipes even if they were AOT-compiled and had no overrides. This is causing problems in case we try to recompile a Component with "templateUrl" or "styleUrls" (which were already resolved in case of AOT) and generally this unnecessary work that TestBed was doing is not required. This commit adds extra logic to check whether a Component/Directive/Pipe already have compiled NG def (like ngComponentDef) and whether there are no overrides present - in this case recompilation is skipped. Recompilation is also skipped in case a Component/Directive has only Provider overrides - in this situation providers resolver function is patched to reflect overrides. Provider overrides are very common in g3, thus this code path ensures no full recompilation.
PR Close#29294
Just updating comments in query-related things to make it easier for the next person that has to grok this for the first time.
Also adds a demo from @mhevery to one of the query specs
Related #29031
PR Close#29342
Just updating comments in query-related things to make it easier for the next person that has to grok this for the first time.
Also adds a demo from @mhevery to one of the query specs
Related #29031
PR Close#29342
Fixes host listeners being inherited twice, if the sub class has its own `propMetadata`. This is related to #29170 which fixed something similar, however all of the test cases there had a super class with some metadata and a sub class that didn't have any. The issue manifested itself in the `MatTreeToggle` which inherits a listener from the `CdkTreeToggle` and adds an extra `Input` of its own, causing the listener to be added twice.
PR Close#29353
Angular Ivy interprets inline static style/class attribute values as instructions that
are processed whilst an element gets created. Because these inline style values are
referenced by style/class bindings, their inline style values are applied at a later
stage. Despite them being eventually applied, their values should be applied earlier
before any directives are instantiated so that directive code can rely on any inline
style/class changes.
This patch ensures that all static style/class attribute values are applied (rendered)
on the element before directives are instantiated.
Jira Issue: FW-1133
PR Close#29269
Following my previous change for placeholders removal, some special code that was used to find the last created node was no longer needed and had wrong interactions with the *ngFor directive.
Removing it fixed the issue.
PR Close#29308
When injecting with `@Attribute`, namespaced attributes should not match (in order to have feature parity with View Engine).
This PR resolves FW-1137
PR Close#29257
BREAKING CHANGE:
Certain elements (like `<tr>` or `<col>`) require parent elements to be of a certain type by the HTML specification
(ex. <tr> can only be inside <tbody> / <thead>). Before this change Angular template parser was auto-correcting
"invalid" HTML using the following rules:
- `<tr>` would be wrapped in `<tbody>` if not inside `<tbody>`, `<tfoot>` or `<thead>`;
- `<col>` would be wrapped in `<colgroup>` if not inside `<colgroup>`.
This meachanism of automatic wrapping / auto-correcting was problematic for several reasons:
- it is non-obvious and arbitrary (ex. there are more HTML elements that has rules for parent type);
- it is incorrect for cases where `<tr>` / `<col>` are at the root of a component's content, ex.:
```html
<projecting-tr-inside-tbody>
<tr>...</tr>
</projecting-tr-inside-tbody>
```
In the above example the `<projecting-tr-inside-tbody>` component culd be "surprised" to see additional
`<tbody>` elements inserted by Angular HTML parser.
PR Close#29219
Previously, ngtsc would resolve forward references while evaluating the
bootstrap, declaration, imports, and exports fields of NgModule types.
However, when generating the resulting ngModuleDef, the forward nature of
these references was not taken into consideration, and so the generated JS
code would incorrectly reference types not yet declared.
This commit fixes this issue by introducing function closures in the
NgModuleDef type, similarly to how NgComponentDef uses them for forward
declarations of its directives and pipes arrays. ngtsc will then generate
closures when required, and the runtime will unwrap them if present.
PR Close#29198
Prior to this change default selector for Components was not applied in case selector is missing or defined as an empty string. This update aligns this behavior between Ivy and VE: now default selector is used for Components when it's needed. Directives with empty selector are not allowed and trigger a compile-time error in both Ivy and VE.
PR Close#29239
Currently with ViewEngine, if someone runs the platform's
`bootstrapModule` method in order to boostrap a module in
JIT mode, external component resources are properly resolved
*automatically*.
Currently with Ivy, the developer would need to manually call
`resolveComponentResources` in order to asynchronously fetch
the determined external component resources. In order to make
this backwards compatible with ViewEngine, and also since
platforms can already specify a `ResourceLoader` compiler
provider, we need to automatically resolve all external
component resources on module bootstrap.
--
Since the `ResourceLoader` is part of the `@angular/compiler`,
because ViewEngine performed the factory creation in the compiler,
we can't access the `ResourceLoader` token from within core.
In order to workaround this without introducing a breaking change,
we just proxy the `ResourceLoader` token to `core` through the
compiler facade. In the future, we should be able to move the
`ResourceLoader` to core when ViewEngine code no longer exists in
the `@angular/compiler`.
PR Close#29083
Dynamic nodes are created at the end of the view stack, but we were removing all the placeholders between `i18nStart` and the last created node index, instead of removing everything between `i18nStart` and `i18nEnd`. This caused errors when dynamic nodes where created in multiple i18n blocks because we would remove all of the dynamic nodes created in the previous i18n blocks.
PR Close#29252
Prior to this commit, i18n instructions (i18n, i18nStart) were generated before listener instructions. As a result, event listeners were attached to the wrong element (text node, not the parent element). This change updates the order of instructions and puts i18n ones after listeners, to make sure listeners are attached to the right elements.
PR Close#29173
The content projection mechanism is static, in that it only looks at the static
template nodes before directives are matched and change detection is run.
When you have a selector-based content projection the selection is based
on nodes that are available in the template.
For example:
```
<ng-content selector="[some-attr]"></ng-content>
```
would match
```
<div some-attr="..."></div>
```
If you have an inline-template in your projected nodes. For example:
```
<div *ngIf="..." some-attr="..."></div>
```
This gets pre-parsed and converted to a canonical form.
For example:
```
<ng-template [ngIf]="...">
<div some-attr=".."></div>
</ng-template>
```
Note that only structural attributes (e.g. `*ngIf`) stay with the `<ng-template>`
node. The other attributes move to the contained element inside the template.
When this happens in ivy, the ng-template content is removed
from the component template function and is compiled into its own
template function. But this means that the information about the
attributes that were on the content are lost and the projection
selection mechanism is unable to match the original
`<div *ngIf="..." some-attr>`.
This commit adds support for this in ivy. Attributes are separated into three
groups (Bindings, Templates and "other"). For inline-templates the Bindings
and "other" types are hoisted back from the contained node to the `template()`
instruction, so that they can be used in content projection matching.
PR Close#29041
This commit adds a new `AttributeMarker` type that will be used, in a
future commit, to mark attributes as coming from an inline-template
expansion, rather than the element that is being contained in the template.
PR Close#29041
Some tests in exports spec rely on the exact output of innerHTML. In IE11 the order of attributes might change, thus causing tests to fail (in case an element contains more than one attribute). This commit avoids innerHTML usage and performs the necessary checks via element properties.
PR Close#29127
Some of the export tests had assertions that relied on capitalization
of attributes in the DOM. IE treats capitalization somewhat differently,
so our SauceLabs tests were failing.
This commit tweaks the tests so that the assertions do not rely on
attributes to be capitalized or not.
PR Close#29125
Angular supports having a component extend off of a parent component.
When this happens, all annotation-level data is inherited including styles
and classes. Up until now, Ivy only paid attention to static styling
values on the parent component and not the child component. This patch
ensures that both the parent's component and child component's styling
data is merged and rendered accordingly.
Jira Issue: FW-1081
PR Close#29015
Currently we only reset the `Attached` flag of a view if it is detached through its parent, however this means that if a root view is destroyed, its flag will never be reset. This manifested itself in one of the Material tests where we were destroying the root view.
This PR resolves FW-1130.
PR Close#29064
Currently if a user accidentally calls ViewContainerRef.insert() with
a view that has already been attached, we do not clean up the references
properly, so we create a view tree with a cycle. This causes an infinite
loop when the view is destroyed.
This PR ensures that we fall back to ViewContainerRef.move() behavior
if we try to insert a view that is already attached. This fixes the
cycle and honors the user intention.
PR Close#29047
When web-animations and/or CSS keyframes are used for animations certain
CSS style values (such as `display` and `position`) may be ignored by a
keyframe-based animation. Angular should special-case these styles to
ensure that they get applied as inline styles throughout the duration of
the animation.
Closes#24923Closes#25635
Jira Issue: FW-1091
Jira Issue: FW-1092
PR Close#28911
Prior to this change i18n block bindings were converted to Expressions right away (once we first access them), when in non-i18n cases we processed them differently: the actual conversion happens at instructions generation. Because of this discrepancy, the output for bindings in i18n blocks was generated incorrectly (with invalid indicies in pipeBindN fns and invalid references to non-existent local variables). Now the bindings processing is unified and i18nExp instructions should contain right bind expressions.
PR Close#28969
Karma is not configured to retrieve the imported scripts using those
absolute deep paths. Using relative paths instead.
See [here][1] for an example failing job.
[1]: https://circleci.com/gh/angular/angular/220751
PR Close#29009
In the past, the sanitizer would remove unsafe elements, but still
traverse and sanitize (and potentially preserve) their content. This was
problematic in the case of `<style></style>` tags, whose content would
be converted to HTML text nodes.
In order to fix this, the sanitizer's behavior was changed in #25879 to
ignore the content of _all_ unsafe elements. While this fixed the
problem with `<style></style>` tags, it unnecessarily removed the
contents for _any_ unsafe element. This was an unneeded breaking change.
This commit partially restores the old sanitizer behavior (namely
traversing content of unsafe elements), but introduces a list of
elements whose content should not be traversed if the elements
themselves are considered unsafe. Currently, this list contains `style`,
`script` and `template`.
Related to #25879 and #26007.
Fixes#28427
PR Close#28804
Currently if an embedded view contains projected nodes, its `rootNodes` array will include `null` instead of the root nodes inside the projection slot. This manifested itself in one of the Material unit tests where we stamp out a template and then move its `rootNodes` into the overlay container.
This PR is related to FW-1087.
PR Close#28951
For efficiency reasons we often put several different data types (`RNode`, `LView`, `LContainer`,
`StylingContext`) in same location in `LView`. This is because we don't want to pre-allocate
space
for it because the storage is sparse. This file contains utilities for dealing with such data
types.
How do we know what is stored at a given location in `LView`.
- `Array.isArray(value) === false` => `RNode` (The normal storage value)
- `Array.isArray(value) === true` => than the `value[0]` represents the wrapped value.
- `typeof value[TYPE] === 'object'` => `LView`
- This happens when we have a component at a given location
- `typeof value[TYPE] === 'number'` => `StylingContext`
- This happens when we have style/class binding at a given location.
- `typeof value[TYPE] === true` => `LContainer`
- This happens when we have `LContainer` binding at a given location.
NOTE: it is assumed that `Array.isArray` and `typeof` operations are very efficient.
PR Close#28947
`LView`, `LContainer`, `StylingContext` are all arrays which wrap either
an `HTMLElement`, `LView`, `LContainer`, `StylingContext`. It is often
necessary to retrieve the correct type of element from the location
which means that we often have to wrap the arrays. Logically it makes
more sense if the thing which we are wrapping is at `0` location. Also
it may be more performant since data is more local which may result in
more L2 cache hits in CPU.
PR Close#28947
This change contains conditionally attached classes which provide human readable (debug) level
information for `LView`, `LContainer` and other internal data structures. These data structures
are stored internally as array which makes it very difficult during debugging to reason about the
current state of the system.
Patching the array with extra property does change the array's hidden class' but it does not
change the cost of access, therefore this patching should not have significant if any impact in
`ngDevMode` mode. (see: https://jsperf.com/array-vs-monkey-patch-array)
So instead of seeing:
```
Array(30) [Object, 659, null, …]
```
```
LViewDebug {
views: [...],
flags: {attached: true, ...}
nodes: [
{html: '<div id="123">', ..., nodes: [
{html: '<span>', ..., nodes: null}
]}
]
}
```
PR Close#28945
Google3 detected circular references here, so splitting up this rather hodge-podge list of functions into slightly better organizational units.
PR Close#28382
- TView no longer stores childIndex
- LView now as CHILD_HEAD and CHILD_TAIL
TView used to store the head of the list, therefor all LViews had to have the same head, which is incorrect.
PR Close#28382
- Removes CONTAINER_INDEX
- LView[PARENT] now contains LContainer when necessary
- Removes now unused arguments to methods after refactor
PR Close#28382
During build time we remap particular property bindings, because their names don't match their attribute equivalents (e.g. the property for the `for` attribute is called `htmlFor`). This breaks down if the particular element has an input that has the same name, because the property gets mapped to something invalid.
The following changes address the issue by mapping the name during runtime, because that's when directives are resolved and we know all of the inputs that are associated with a particular element.
PR Close#28765
Fixes the `ngOnDestroy` hook on a component or directive being called twice, if the type is also registered as a provider.
This PR resolves FW-1010.
PR Close#28470
Prior to this fix, both the `NgStyle` and `NgClass` directives made use
of `Renderer2` and this dependency raised issues for future versions of
Angular that cannot inject it. This patch ensures that there are two
versions of both directives: one for the VE and another for Ivy.
Jira Issue: FW-882
PR Close#28711
I18n can change the order of the nodes, or insert new dynamic nodes. When that happens it can break the existing links (`TNode.next`) or even create loops:
```
div1 → div2 → div3 → div4 → div5
```
Can become:
```
div1 → div4 → div2 → div3 div5
🡑 │
└─────────────┘
```
This PR fixes this issue by recreating the broken links between those nodes.
PR Close#28827
This commit adds support for the `static: true` flag in `ContentChild`
queries. Prior to this commit, all `ContentChild` queries were resolved
after change detection ran. This is a problem for backwards
compatibility because View Engine also supported "static" queries which
would resolve before change detection.
Now if users add a `static: true` option, the query will be resolved in
creation mode (before change detection runs). For example:
```ts
@ContentChild(TemplateRef, {static: true}) template !: TemplateRef;
```
This feature will come in handy for components that need
to create components dynamically.
PR Close#28811
This commit adds support for the `static: true` flag in
`ViewChild` queries. Prior to this commit, all `ViewChild`
queries were resolved after change detection ran. This is
a problem for backwards compatibility because View Engine
also supported "static" queries which would resolve before
change detection.
Now if users add a `static: true` option, the query will be
resolved in creation mode (before change detection runs).
For example:
```ts
@ViewChild(TemplateRef, {static: true}) template !: TemplateRef;
```
This feature will come in handy for components that need
to create components dynamically.
PR Close#28811
Prior to this commit, the timing of `ViewChild`/`ContentChild` query
resolution depended on the results of each query. If any results
for a particular query were nested inside embedded views (e.g.
*ngIfs), that query would be resolved after change detection ran.
Otherwise, the query would be resolved as soon as nodes were created.
This inconsistency in resolution timing had the potential to cause
confusion because query results would sometimes be available in
ngOnInit, but sometimes wouldn't be available until ngAfterContentInit
or ngAfterViewInit. Code depending on a query result could suddenly
stop working as soon as an *ngIf or an *ngFor was added to the template.
With this commit, users can dictate when they want a particular
`ViewChild` or `ContentChild` query to be resolved with the `static`
flag. For example, one can mark a particular query as `static: false`
to ensure change detection always runs before its results are set:
```ts
@ContentChild('foo', {static: false}) foo !: ElementRef;
```
This means that even if there isn't a query result wrapped in an
*ngIf or an *ngFor now, adding one to the template later won't change
the timing of the query resolution and potentially break your component.
Similarly, if you know that your query needs to be resolved earlier
(e.g. you need results in an ngOnInit hook), you can mark it as
`static: true`.
```ts
@ViewChild(TemplateRef, {static: true}) foo !: TemplateRef;
```
Note: this means that your component will not support *ngIf results.
If you do not supply a `static` option when creating your `ViewChild` or
`ContentChild` query, the default query resolution timing will kick in.
Note: This new option only applies to `ViewChild` and `ContentChild`
queries, not `ViewChildren` or `ContentChildren` queries, as those types
already resolve after CD runs.
PR Close#28810
This commit turns off an unknown binding test that is specific
to the View Engine implementation. In Ivy, we do property validation
at runtime for jit, so this test does not apply.
PR Close#28740
Accounts for schemas in when validating properties in Ivy.
This PR resolves FW-819.
A couple of notes:
* I had to rework the test slightly, in order to have it fail when we expect it to. The one in master is passing since Ivy's validation runs during the update phase, rather than creation.
* I had to deviate from the design in FW-819 and not add an `enableSchema` instruction, because the schema is part of the `NgModule` scope, however the scope is only assigned to a component once all of the module's declarations have been resolved and some of them can be async. Instead, I opted to have the `schemas` on the component definition.
PR Close#28637
Previously `DebugNode.classes` and `DebugNode.styles` mistakenly used an
object that is only *sometimes* a `StylingContext`. Also fixes a mistake
in `debug_node_spec.ts` where a test component was not declared in the
testing module.
There is still a bug here where `DebugNode` is not exposing *static*
values. This will need to be fixed in a follow up.
PR Close#28709
Prior to this fix if a root component was instantiated it create host
bindings, but never render them once update mode ran unless one or more
slot-allocated bindings were issued. Since styling in Ivy does not make
use of LView slots, the host bindings function never ran on the root
component.
This fix ensures that the `hostBindings` function does run for a root
component and also renders the schedlued styling instructions when
executed.
Jira Issue: FW-1062
PR Close#28664
While marking a given views tree as dirty we should go all the way to the
root of the views tree and cross boundaries of dynamically inserted views.
In other words the markForCheck functionality should consider parents of
dynamically inserted views.
PR Close#28687
Prior to this change we used current injector implementation for module injector, which was causing problems and produces circular dependencies in case the same token is referenced (with @SkipSelf flag) in the `deps` array. The origin of the problem was that once `directiveInject` implementation becomes active, it was used for module injector as well, thus searching deps in Component/Directive DI scope. This fix sets `injectInjectorOnly` implementation for module injector to resolve the problem.
PR Close#28667
Prior to this update we had separate contentQueries and contentQueriesRefresh functions to handle creation and update phases. This approach was inconsistent with View Queries, Host Bindings and Template functions that we generate for Component/Directive defs. Now the mentioned 2 functions are combines into one (contentQueries), creation and update logic is separated with RenderFlags (similar to what we have in other generated functions).
PR Close#28503
For TypeScript compilation units that have the "strictFunctionTypes"
option enabled, an error would be produced for Ivy's definition fields
in declaration files in the case of inheritance across directives or
pipes.
This change loosens the definition types to allow for subtypes of the
defined type where necessary.
A test package that has the "strict" option enabled verifies that we
won't regress in environments where strict type checking is enabled.
Fixes#28079
PR Close#28634
Previously, using a pipe in an input binding on an ng-template would
evaluate the pipe in the context of node that was processed before the
template. This caused the retrieval of e.g. ChangeDetectorRef to be
incorrect, resulting in one of the following bugs depending on the
template's structure:
1. If the template was at the root of a view, the previously processed
node would be the component's host node outside of the current view.
Accessing that node in the context of the current view results in a crash.
2. For templates not at the root, the ChangeDetectorRef injected into the
pipe would correspond with the previously processed node. If that node
hosts a component, the ChangeDetectorRef would not correspond with the
view that the ng-template is part of.
The solution to the above problem is two-fold:
1. Template compilation is adjusted such that the template instruction
is emitted before any instructions produced by input bindings, such as
pipes. This ensures that pipes are evaluated in the context of the
template's container node.
2. A ChangeDetectorRef can be requested for container nodes.
Fixes#28587
PR Close#27565
There are some differences in how ivy maps template source
compared to View Engine. In this commit we recreate the View Engine
tests for ivy.
PR Close#28055
When we resolve a component `templateUrl` we copy the contents of the
resolved template file into the `template` property.
Previously we would then remove the `templateUrl` to indicate that
the component has been resolved. But this meant that we no longer had
access to the URL of the original template file. This is essential for
diagnostics messages about the template compilation.
Now the existence of the `template` property overrides the existence of
`templateUrl`, which allows us to keep the `templateUrl` property.
PR Close#28055
Due to the fact that host nodes no longer match in ContentChild queries in Ivy, we disable test that was enabled previously in other commit.
PR Close#28660
Up until now, `[style]` and `[class]` bindings (the map-based ones) have only
worked as template bindings and have not been supported at all inside of host
bindings. This patch ensures that multiple host binding sources (components and
directives) all properly assign style values and merge them correctly in terms
of priority.
Jira: FW-882
PR Close#28246
Before this fix our ViewRef implementation assumed that checkNoChanges can be
only called on component views. In reality checkNoChanges can be also called on
embedded views (ex.: when an embedded view is attached to ApplicationRef).
PR Close#28644
Previously, it wasn't possible to compile template that contains pipe in context of ternary operator `{{ 1 ? 2 : 0 | myPipe }}` due to the error `Error: Illegal state: Pipes should have been converted into functions. Pipe: async`.
This PR fixes a typo in expression parser so that pipes are correctly converted into functions.
PR Close#28635
Prior to this change in Ivy we had strict check that disabled non-unique #localRefs usage within a given template. While this limitation was technically present in View Engine, in many cases View Engine neglected this restriction and as a result, some apps relied on a fact that multiple non-unique #localRefs can be defined and utilized to query elements via @ViewChild(ren) and @ContentChild(ren). In order to provide better compatibility with View Engine, this commit removes existing restriction.
As a part of this commit, are few tests were added to verify VE and Ivy compatibility in most common use-cases where multiple non-unique #localRefs were used.
PR Close#28627
There is nothing browser specific in those tests and fakeAsync is supported on node.
Testing / debugging on node is often faster than on Karma.
PR Close#28593
This commit adds a devMode-only check which will throw if a user
attempts to bind a property that does not match a directive
input or a known HTML property.
Example:
```
<div [unknownProp]="someValue"></div>
```
The above will throw because "unknownProp" is not a known
property of HTMLDivElement.
This check is similar to the check executed in View Engine during
template parsing, but occurs at runtime instead of compile-time.
Note: This change uncovered an existing bug with host binding
inheritance, so some Material tests had to be turned off. They
will be fixed in an upcoming PR.
PR Close#28537
Prior to this change we only checked whether current lView has a next pointer while traversing tNode tree. However in some cases this pointer can be undefined and we need to look up parents chain to find suitable next pointer. This commit adds the logic of searching for the next pointer taking parents chain into account.
PR Close#28533
`LView` `HOST` was set in most cases right after creating `LView`.
This makes the API cleaner by explicitly passing it ont `createLView`.
PR Close#28461
When we first started writing tests for Ivy, we did not yet have a
compatible compiler. For this reason, we set up the Ivy runtime tests
to run with generated code that we wrote by hand (instead of real code
generated by the compiler).
Now that we have a working Ivy compiler and TestBed infrastructure
that is compatible with Ivy, we should start writing integration
tests that leverage them (no more handwritten generated code!). This
will prevent bugs where the compiler code and runtime code become
out of sync (which is easy if they are tested separately). And
eventually, we should migrate all the existing runtime tests in
"core/test/render3" to TestBed and ngtsc.
To kick off this effort, this commit migrates some existing tests
from "core/test/render3/exports_spec.ts" and saves them in a new file
with the same name in the "core/test/acceptance" folder.
PR Close#28534
i18n instructions create text nodes dynamically and save them between bindings and the expando block in `LView`. e.g., they try to create the following order in `LView`.
```
| -- elements -- | -- bindings -- | -- dynamic i18n text -- | -- expando (dirs, injectors) -- |
```
Each time a new text node is created, it is pushed to the end of the array and the `expandoStartIndex` marker is incremented, so the section begins slightly later. This happens in `allocExpando`.
This is fine if no directives have been created yet. The end of the array will be in the "dynamic text node" section.
| -- elements -- | -- bindings -- | -- dynamic i18n text -- |
However, this approach doesn't work if dynamic text nodes are created after directives are matched (for example when the directive uses host bindings). In that case, there are already directives and injectors saved in the "expando" section. So pushing to the end of `LView` actually pushes after the expando section. What we get is this:
```
| -- elements -- | -- bindings -- | -- dynamic i18n text -- | -- expando -- | -- dynamic i18n text-- |
```
In this case, the `expandoStartIndex` shouldn't be incremented because we are not inserting anything before the expando section (it's now after the expando section). But because it is incremented in the code right now, it's now pointing to an index in the middle of the expando section.
This PR fixes that so that we only increment the `expandoStartIndex` if nothing was pushed into the expando section.
FW-978 #resolve
PR Close#28424
Currently, DOM node removal called `removeChild` on the saved parent
node when destroying a component. However, this will fail if the
component has been manually moved in the DOM. This change makes the
removal always use the node's real `parentNode` and ignore the provided
`parent`.
PR Close#28455
Ivy allows Components to extend Directives (but not the other way around) and as a result we may have Component and Directive annotations present at the same time. The logic that resolves annotations to pick the necessary one didn't take this into account and as a result Components were recognized as Directives (and vice versa) in case of inheritance. This change updates the resolution logic by picking known annotation that is the nearest one (in inheritance tree) and compares it with expected type. That should help avoid mis-classification of Components/Directives during resolution.
PR Close#28439
Improve the stacktrace for `R3Injector` errors by adding the source component (or module) that tried to inject the missing provider, as well as the name of the injector which triggered the error (`R3Injector`).
e.g.:
```
R3InjectorError(SomeModule)[car -> SportsCar]:
NullInjectorError: No provider for SportsCar!
```
FW-807 #resolve
FW-875 #resolve
PR Close#28207
createInjector() is an Ivy-only API that should not have
been exported as part of the public API. This commit removes
the export. It will be re-exported when Ivy is released.
PR Close#28509
Fixes Ivy not passing thrown errors along to the `ErrorHandler`.
**Note:** the failing test had to be reworked a little bit, because it has some assertions that depend on an error context being logged, however Ivy doesn't keep track of the error context.
This PR resolves FW-840.
PR Close#28447
In Ivy, we support a new manual mode that allows for stricter control
over change detection in OnPush components. Specifically, in this mode,
events do not automatically mark OnPush views as dirty. Only changed
inputs and manual calls to `markDirty()` actually mark a view dirty.
However, this mode cannot be the default for OnPush components if we
want to be backwards compatible with View Engine. This commit re-adds
the legacy logic for OnPush components where events always mark views
dirty and makes it the default behavior.
Note: It is still TODO to add a public API for manual change detection.
PR Close#28474
Due to the fact that the test in 'ng_module_integration_spec.ts' relied on internal VE data structures (the '_def' field) to verify the state and the structure has changed in Ivy, this commit adds an Ivy version of the same test.
PR Close#28477
Previously, attempting to destroy a view with listeners more than once
throws an error during event listener cleanup. This happens because
`cleanup` field on the `TView` has already been cleared out by the time
the second destruction runs.
The `destroyed` flag on LView was previously being set in the `destroyLView` function,
but this flag was never _checked_ anywhere in the codebase. This commit
moves _setting_ this flag to the `cleanupView` function, just before
destroy hooks are called. This is necessary because the destroy hooks
can contain arbitrary user code, such as (surprise!) attempting to
destroy the view (again). We also add a check to `destroyLView` to skip
already-destroyed views. This prevents the cleanup code path from running twice.
PR Close#28413
In View Engine, we supported @Input and @ContentChild annotations
on the same property. This feature was somewhat brittle because
it would only work for static queries, so it would break if a
content child was passed in wrapped in an *ngIf. Due to the
inconsistent behavior and low usage both internally and externally,
we will likely be deprecating it in the next version, and it does
not make sense to perpetuate it in Ivy.
This commit ensures that we now throw in Ivy if we encounter the
two annotations on the same property.
PR Close#28415
This commit updates the token used in fakeAsync test to the one available in both VE and R3 TestBeds. The goal of the test is to verify that fakeAsync works with inject function, so the actual token that is used for a test is irrelevant in that case. The logic to retrieve tokens from compiler injector (that the comment in "fixmeIvy" refers to) was implemented in PR #28196.
PR Close#28383
Prior to this change we may encounter some errors (like pipes being used where they should not be used) while compiling Host Bindings and Listeners. With this update we move validation logic to the analyze phase and throw an error if something is wrong. This also aligns error messages between Ivy and VE.
PR Close#28356
Previously, these components were not added to the view tree for the
(fake) root view in which they were bootstrapped. Without this,
root view destruction does not work as expected since the root view's
children are not present to be also destroyed.
PR Close#28409
This commit updates test that was added after Content Queries inheritance fix (that renames some instructions) was merged into master. The test used previous version of instructions, thus causing failures after merging Content Queries inheritance fix.
PR Close#28414
Prior to this change contentQueriesRefresh functions that represent refresh logic for @ContentQuery list were not composable, which caused problems in case one Directive inherits another one and both of them contain Content Queries. Due to the fact that we used indices to reference queries in refresh function, results were placed into wrong Queries. In order to avoid that we no longer use indices to reference queries and instead maintain current content query index while iterating through them. This allows us to compose contentQueriesRefresh functions and make inheritance feature work with Content Queries.
PR Close#28324
By its nature, Ivy alters the import graph of a TS program, adding imports
where template dependencies exist. For example, if ComponentA uses PipeB
in its template, Ivy will insert an import of PipeB into the file in which
ComponentA is declared.
Any insertion of an import into a program has the potential to introduce a
cycle into the import graph. If for some reason the file in which PipeB is
declared imports the file in which ComponentA is declared (maybe it makes
use of a service or utility function that happens to be in the same file as
ComponentA) then this could create an import cycle. This turns out to
happen quite regularly in larger Angular codebases.
TypeScript and the Ivy runtime have no issues with such cycles. However,
other tools are not so accepting. In particular the Closure Compiler is
very anti-cycle.
To mitigate this problem, it's necessary to detect when the insertion of
an import would create a cycle. ngtsc can then use a different strategy,
known as "remote scoping", instead of directly writing a reference from
one component to another. Under remote scoping, a function
'setComponentScope' is called after the declaration of the component's
module, which does not require the addition of new imports.
FW-647 #resolve
PR Close#28169
TestBed.compileComponents has always been an async API. However,
ViewEngine tolerated using this API in a synchronous manner if the
components declared in the testing module did not have any async
resources (templateUrl, styleUrls). This change makes the ivy TestBed
mirror this tolerance by configuring such components synchronously.
Ref: FW-992
PR Close#28350
This commit unifies handling of the "check no changes" mode between
ngIvy and the view engine. More specifically:
- check no changes can be invoked before change detection in ivy;
- `undefined` values are considered equal `NO_CHANGES` for the "check no changes"
mode purposes.
Chanes in this commit enables several tests that were previously running only in ivy
or only in the view engine.
PR Close#28366
Prior to this change the postprocess step relied on the order of placeholders combined in one group (e.g. [�#1�|�*1:1�]). The order is not guaranteed in case we have nested templates (since we use BFS to process templates) and some tags are represented using same placeholders. This change performs postprocessing more accurate by keeping track of currently active template and searching for matching placeholder.
PR Close#28209
Due to the fast moving nature of the Ivy codebase, the timing isn't
right to make changes to how errors and reported and handled during the
runtime.
Once ivy is stable this test should be revisted because that stage there
will be a better and more robust understanding of how ivy should recover
from runtime errors.
Jira Issue: FW-952
PR Close#28212
DebugElement.properties should contain a map of element
property names to element property values, with entries
for both normal property bindings and host bindings.
This commit adds support for property bindings in
DebugElement.properties (including interpolations).
PR Close#28355
DebugElement.properties should contain a map of element
property names to element property values, with entries
for both normal property bindings and host bindings.
Many Angular core tests depend on this map being present.
This commit adds support for host property bindings in
DebugElement.properties, which fixes the Angular core tests.
There is still work to be done for normal property bindings.
PR Close#28355
Previous to this change, we were storing view queries at the
wrong index. This is because we were passing a raw index to the
store() instruction instead of an adjusted index (i.e. an
index that does not include the HEADER_OFFSET). We had an
additional issue where TView.blueprint was not backfilled
when TView.data was backfilled, so new component instances
created from the blueprint would end up having a shorter LView.
Both of these problems together led to the Material demo app
failing with Ivy. This commit fixes those discrepancies.
PR Close#28327
Previously, bootstrapping a component with render3 would create a chained injector with the test bed ngModule instead of the ngModule that the component belongs to.
Now when a component belongs to an ngModule, we use that for the chained injector, ensuring the correct injection of any providers that this ngModule contains.
FW-776 #resolve
PR Close#28183
Fixes components with native content projection (using `<content>` or `<slot>`) not working under Ivy.
The issue comes from the fact that when creating elements inside a component, we sometimes don't append the element immediately, but we leave it to projection to move it into its final destination. This ends up breaking the native projection, because the slots have to be in place from the beginning. The following changes switch to appending the element immediately when inside a component with Shadow DOM encapsulation.
This PR resolves FW-841.
PR Close#28261
Prior to this change `viewQuery` functions that represent @ViewQuery list were not composable, which caused problems in case one Component/Directive inherits another one and both of them contain View Queries. Due to the fact that we used indices to reference queries, resulting query set was corrupted (child component queries were overridden by super class ones). In order to avoid that we no longer use indices assigned at compile time and instead maintain current view query index while iterating through them. This allows us to compose `viewQuery` functions and make inheritance feature work with View Queries.
PR Close#28309
- Wraps the NgOnChangesFeature in a factory such that no side effects occur in the module root
- Adds comments to ngInherit property on feature definition interface to help guide others not to make the same mistake
- Updates compiler to generate the feature properly after the change to it being a factory
- Updates appropriate tests
PR Close#28187
Before this commit we were creating a "fake" TNode for each and every
projectable node passed during dynamic component creation. This approach
had several problems:
- the existing TView structure had to be mutated to accomodate new TNodes and
it was very easy to "corrupt" TView / TNode data structures;
- TNodes are not really needed to fully support projectable nodes so we were
creating objects and updating existing data structures for nothing.
This commit changes the approach so we don't create "fake" TNodes for projectable
nodes but instead we process projectable nodes directly in the projection instruction.
As a result we've got less code, less object allocation and - as a bonus - we fix few
bugs where TView / TNode data structures were corrupted when using projectable nodes.
PR Close#28275
Fixes Ivy not applying properties that are set in camelCase, because it goes through the `CSSStyleDeclaration` API via `setProperty` and `removeProperty` which requires for [the values to be in dash-case](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/setProperty).
**Note:** I opted to let the browser normalize the value, rather than convert it to dash-case during compile time, because there are some special cases like browser-prefixed properties where we might not normalize it in-line with the browser.
This PR fixes FW-579.
PR Close#28276
Previous to this change, the isStylingContext() function was improperly
returning true for LContainers because it used the presence of an array
at index 2 to determine whether it was a styling context. Unfortunately,
LContainers also contain arrays at index 2, so this would return a false
positive. This led to other errors down the line because we would treat
nodes with containers as if they already had styling contexts (even if
they did not), so the proper initialization logic for styling contexts
was not run.
This commit fixes the isStylingContext() function to use LCONTAINER_LENGTH
as a marker rather than the presence of an array, which in turn fixes
host bindings to styles on nodes with containers.
PR Close#28221
Destroys the module's injector when an `NgModule` is destroyed which in turn calls the `ngOnDestroy` methods on the instantiated providers.
This PR resolves FW-739.
PR Close#27793
Due to the fact that animations in Angular are defined in the component metadata,
all animation trigger definitions are localized to the component and are
inaccessible outside of it. Animation host listeners in Ivy are
rendered in the context of the parent component, but the VE renders them
differently. This patch ensures that animation host listeners are
always registered in the sub component's renderer
Jira issue: FW-943
Jira issue: FW-958
PR Close#28210
Prior to this fix Ivy would not execute any animation triggers
that exist as host bindings on an element if it is removed by
the parent template.
PR Close#28162
In Ivy when elements are created a series of static attribute names are provided
over to the construction instruction of that element. Static attribute names
include non-binding attribues (like `<div selected>`) as well as animation bindings
that do not have a RHS value (like `<div @foo>`). Because of this distinction,
value-less animation triggers are rendered first before value-full animation
bindings are and this improper ordering has caused various existing tests to fail.
This patch ensures that animation bindings are evaluated in the order that they
exist within the HTML template code (or host binding code).
PR Close#28165
With the refactoring or how styles/classes are implmented in Ivy,
interpolation has caused the binding code to mess up since interpolation
itself takes up its own slot in Ivy's memory management code. This patch
makes sure that interpolation works as expected with class and style
bindings.
Jira issue: FW-944
PR Close#28190
In VE the renderer.begin() and renderer.end() methods are only called
when CD is called on an element. This patch ensures that Ivy does the
same thing.
Jira issue: FW-945
PR Close#28192
When we look for matching annotations in TestBed, we should always take the last
matching annotation. Otherwise, we will return superclass data for subclasses,
which would have unintended consequences like directives matching the wrong selectors.
PR Close#28195
Initial thinking was that the bug is in the content projection logic but
it turned out to be a wrong assumption - hence adding a test to illustrate
that basic content projection of view containers works correctly.
What fails in the marked test is the logic quering debug nodes - content
peojection is fine but we never create the 'B' text node since we call
show() method on the "wrong" directive instance.
PR Close#28152