This commit adds a re-export of the `NgForOf` class as `NgFor` to improve the DX for cases when the directive is used as standalone. Developers can import `NgFor` class, which better matches the `ngFor` attribute used in a template.
PR Close#47309
Using raw objects as a lookup structure will inadvertently find methods defined on
`Object`, where strings are expected. This causes errors downstream when string
operations are applied on functions.
This commit switches over to use `Map`s in the DOM element schema registry to fix
this category of issues.
Fixes#46936
PR Close#47220
When the Angular compiler emits a diagnostic in a template file, it
forces TypeScript to parse that template. Templates are not TypeScript,
so this parse finds a bunch of parsing errors, which Angular then
ignores and we show the diagnostic anyways because we have more context.
This can lead to strange behavior in TypeScript because templates are so
weird that it can break the parser and crash the whole compiler.
For example, certain Angular templates can encounter failures fixed by
microsoft/TypeScript#45987, which are not easily debuggable and require
a TS upgrade to fix.
This commit introduces logic to handle the error gracefully, by falling
back to report the template error on the component class itself. The
diagnostic is extended to still reference the template location and
includes the failure's stack trace, to allow the parsing failure to be
reported to TypeScript (as parsing should in theory not cause a crash).
Closes#43970
PR Close#44001
This option has no longer any effect as Ivy is the only rendering engine.
BREAKING CHANGE: Angular compiler option `enableIvy` has been removed as Ivy is the only rendering engine.
PR Close#47346
This is the compile-time implementation of the `hostDirectives` feature plus a little bit of runtime code to illustrate how the newly-generated code will plug into the runtime. It works by creating a call to the new `ɵɵHostDirectivesFeature` feature whenever a directive has a `hostDirectives` field. Afterwards `ɵɵHostDirectivesFeature` will patch a new function onto the directive definition that will be invoked during directive matching.
For example, if we take the following definition:
```ts
@Directive({
hostDirectives: [HostA, {directive: HostB, inputs: ['input: alias']}]
})
class MyDir {}
```
Will compile to:
```js
MyDir.ɵdir = ɵɵdefineComponent({
features: [ɵɵHostDirectivesFeature([HostA, {
directive: HostB,
inputs: {
input: "alias"
}
}])]
});
```
The template type checking is implemented during directive matching by adding the host directives applied on the host to the array of matched directives whenever the host is matched in a template.
Relates to #8785.
PR Close#46868
This helper accepts a class for an Angular trait, and returns the NgModule which owns that trait. This will be useful for the language service import project, which needs to edit import arrays on the module.
PR Close#47166
Replaces (almost) all of the usages of the deprecated `getMutableClone` function from TypeScript which has started to log deprecation warnings in version 4.8 and will likely be removed in version 5.0. The one place we have left is in the default import handling of ngtsc which will be more difficult to remove.
PR Close#47167
This helper accepts a class, and returns the primary Angular Decorator associated with that trait (e.g. the Component, Pipe, Directive, or NgModule decorator). This will be useful for the language service import project, which needs to edit import arrays inside the decorator.
PR Close#47180
Adds support for TypeScript 4.8 and resolves some issues that came up as a result of the update.
Most of the issues came from some changes in TypeScript where the `decorators` and `modifiers` properties were removed from most node types, and were combined into a single `modifiers` array. Since we need to continue supporting TS 4.6 and 4.7 until v15, I ended up creating a new `ngtsc/ts_compatibility` directory to make it easier to reuse the new backwards-compatible code.
PR Close#47038
Updates the tsickle version in the repository and accounts for its changes in
the `compiler-cli` package. Tsickle made a breaking change in the minor version
segment bump that would break the use with `@angular/compiler-cli`
Additionally the tsickle version for `@angular/bazel` is updated since
we updated `@bazel/typescript` to also account for the breaking changes.
See: 78a0528107
PR Close#47018
The diagnostic of the component missing member comes from the ts service,
so the all code fixes for it are delegated to the ts service.
The code fixes are placed in the LS package because only LS can benefit from
it now, and The LS knows how to provide code fixes by the diagnostic and NgCompiler.
The class `CodeFixes` is useful to extend the code fixes if LS needs to
provide more code fixes for the template in the future. The ts service uses
the same way to provide code fixes.
1622247636/src/services/codeFixProvider.ts (L22)
Fixes https://github.com/angular/vscode-ng-language-service/issues/1610
PR Close#46764
improve the error message for non-standalone components which are not
exported from their module, and that are also imported directly as if
they were standalone
this change simply adds the suggestion to the developer to import the
ngModule instead
resolves#46004
PR Close#46114
The extended diagnostics about missing control flow directive was only mentioning that the `CommonModule` should be imported.
Now that the control flow directives are available as standalone, the message mentions that directive itself can be imported.
The message now also mentions which import should be used for the directive (as it can be tricky to figure out that `NgForOf` is the directive corresponding to `*ngFor`).
PR Close#46846
After a bugfix in #46096, the compiler is now better capable of detecting pipes
which require an inline type constructor. However, there is an issue in how all
pipes are considered when verifying the inline type-ctor requirement: it should
only check actually used pipes.
Fixes#46747
PR Close#46807
This commit adds an extended diagnostics check that is similar to the nullish
coalescing check, but targeting optional chains. If the receiver expression
of the optional chain is non-nullable, then the extended diagnostic can report
an error or warning that can be fixed by changing the optional chain into a
regular access.
Closes#44870
PR Close#46686
This commit adds an extended diagnostic which warns when style suffixes such as '.px'
are used with attribute bindings (attr.width.px).
Fixes#36256
PR Close#46651
In the case that a user accidentally forgot the let keyword, they dont get a very clear indicator of there being a problem.
They get an issue in the template iteration at runtime. This diagnostic will warn the user when the let keyword is missing.
PR Close#46683
https://angular.io/guide/attribute-binding#attribute-class-and-style-bindings
Angular supports `attr.`, `style.`, and `class.` binding prefixes to
bind attributes, styles, and classes. If the key does not have the
binding syntax `[]` or the value does not have an interpolation `{{}}`,
the attribute will not be interpreted as a binding.
This diagnostic warns the user when the attributes listed above will not
be interpreted as bindings.
resolves#46137
PR Close#46161
In Bazel worker-land, workers which use incremental compilation must still
emit all declared outputs and cannot rely on these outputs persisting from
previous builds.
This commit adds a flag to `performCompilation` which can be used by the
worker infrastructure to instruct the compiler to always emit all possible
output files, regardless of any incremental build optimizations.
PR Close#46355
This commit adds an extended diagnostics check that verifies that all control flow directives (such as `ngIf`, `ngFor`) have the necessary directives imported in standalone components. Currently there is no diagnostics produced for such cases, which makes it harder to detect and find problems.
PR Close#46146
An inline type-check block is required when a reference to a component class
cannot be emitted from an ngtypecheck shim file, but the logic to detect this
situation did not consider the configured `rootDir`. When a `rootDir` is
configured the reference emitter does not allow generating an import outside
this directory, which meant that a shim file wouldn't be able to reference
the component class. Consequently, type-check block generation would fail
with a fatal error that is unaccounted for, as gathering diagnostics should
be non-fallible.
This commit fixes the problem by leveraging the existing `canReferenceType`
logic of the type-checking `Environment`, instead of the rudimentary check
whether the class is exported as top-level symbol (`checkIfClassIsExported`).
Instead, `canReferenceType` pre-flights the generation of an import using the
`ReferenceEmitter` to tell exactly whether it will succeed or not; thus taking
into account the `rootDirs` constraint as well.
Fixes#44999
PR Close#46096
Saves us some bytes by not emitting `providers` in `defineInjector`. While the amount of bytes isn't huge, I think that this change is worthwhile, because `ng generate` currently generates `providers: []` with every `NgModule` which users can forget to remove.
PR Close#46301
When generating .d.ts metadata for NgModules, by default we emit type
references to their declarations, imports, and exports. However, this
information is not necessarily useful to consumers. References to private
directives (those that aren't exported by the NgModule) for example aren't
at all useful as they can only affect other components declared in the
NgModule. References to imports are of limited usefulness - they might be
helpful for an IDE to understand the DI structure of an application, but
aren't at all used by a downstream compiler.
Generating this metadata is not without cost. When an incremental build
system uses changes in inputs to determine when a rebuild is necessary, any
changes in .d.ts files might cause downstream targets to rebuild. If those
.d.ts changes are in the "private" side of the NgModule (imports or non-
exported directives/pipes), then these rebuilds are wholly unnecessary.
This commit introduces the `onlyPublishPublicTypingsForNgModules` flag for
the compiler. When this flag is set, the compiler will filter the emitted
references in NgModule .d.ts output and only reference those directives/
pipes that are exported from the NgModule (its public API surface). Omitting
the flag preserves the existing behavior of emitting all references, both
public and private.
This is especially useful for build systems such as Bazel.
PR Close#45894
This commit updates the error message to use correct info depending on whether a component is standalone or not. Previously we were always referring to @NgModules as a place to fix the issue, but not we also mention @Component when needed (for standalone components).
PR Close#46159
Angular generally supports cycles between components in the same NgModule.
We have a mechanism of moving the component scope declaration into the
NgModule file in this case. This ensures that Angular never itself
introduces an import which creates a cycle.
What happens if the cycle already exists in the user's program, though, is a
bit different. In these cases, the "correct" emit for Angular is to generate
the component scope (whether direct or remote) inside of a closure, to
prevent evaluating the scope's references until module evaluation is
complete and all cyclic imports have been resolved. We don't want to do this
for *all* scopes because the code size cost of emitting a function wrapper
is non-zero.
In this fix, we take the presence of a `forwardRef` in a component's
`imports` or in an NgModule `declarations` or `imports` as a sign that
component scopes emitted into those files need to be protected against
cyclic references. In a future commit, we may introduce a warning or error
if cyclic imports are not protected behind `forwardRef` in these cases, but
this will take some time to implement.
PR Close#46139
This commit improves the reported error when importing e.g. `RouterModule.forRoot()`
from within `Component.imports`. Such import is not supported, as standalone components
can only refer to other standalone entities or NgModules in their `imports` array;
`ModuleWithProviders` are not supported as `Component.imports` is meant to be used
for the compilation scope of the component, _not_ for configuring DI.
Closes#46003
PR Close#46009
This commit moves the foreign function resolver logic for detecting a
`ModuleWithProviders` in a return type position of a function call, as the logic can
then be reused for standalone components in a subsequent commit.
PR Close#46009
update the error message presented during aot compilation when an unrecognized
tag/element is found in a standalone component so that it does not mention
the ngModule anymore
Note: the jit variant is present in PR #45920resolves#45818
PR Close#45919
This commit fixes a small issue in the logic around the calculation of
template scopes for standalone components. These scopes include a
`Reference` for each dependency of a standalone component, which is used to
generate references to that dependency in various contexts.
Previously, the `Reference` used for a dependency was the one generated from
its own metadata. For example, a referenced directive used the `Reference`
that was created when analyzing the directive declaration itself. This still
works, as the compiler is always able to emit a reference to any valid
`Reference`. However, it's not optimal.
The `Reference` which should be used instead is the one generated from
analyzing the standalone component's `imports` array, which has knowledge of
how the dependency is referenced from within the standalone component's file
itself. This allows the compiler to skip creating a new import for the
dependency when emitting the standalone component, and use the existing,
user-authored import instead. This saves on code size and avoids taxing the
bundler with unnecessary imports.
PR Close#46029
The Angular compiler performs cycle detection when generating imports within
component files. This was previously necessary as reifying dependencies
discovered via NgModules into the component output could add imports that
weren't present in the original component and potentially create cycles.
Doing this could cause order-of-execution issues with existing user imports,
so the compiler detects this case and falls back to an alternative way of
specifying component dependencies that doesn't risk creating cycles.
For standalone components, Angular does not need to add new imports to the
component file as the user has already explicitly referenced dependencies
in the `@Component.imports`. As a result, the cycle detection can be
skipped.
Correctly authoring a program with import cycles is always challenging. One
side of a cyclic import will always initially evaluate to `undefined`, and
this can result in errors in the component definition when this happens
within component `imports`.
Our compiler _could_ detect the cycle and choose to wrap the component
dependencies in an automatic closure instead, avoiding any issues with
`undefined` during an eager evaluation. However, this commit makes an active
choice not to do that as it only serves to mask the problems with cyclic
imports. Future refactorings may cause the "other half" of the cycle to
break. Users should instead be aware of the potential problems with cycles
and explicitly defer evaluations with `forwardRef` where needed. This
ensures that future implementations of Angular compilation which may not be
able to automatically detect import cycles and correct accordingly can still
compile such components.
PR Close#46029
When an external template is read, adds the template file to to the project which contains.
This is necessary to keep the projects open when navigating away from HTML files.
Since a `tsconfig` cannot express including non-TS files,
we need another way to indicate the template files are considered part of the project.
Note that this does not ensure that the project in question _directly_ contains the component
file. That is, the project might just include the component file through the program rather
than directly in the `include` glob of the `tsconfig`. This distinction is somewhat important
because the TypeScript language service/server prefers projects which _directly_ contain the TS
file (see `projectContainsInfoDirectly` in the TS codebase). What this means it that there can
possibly be a different project used between the TS and HTML files.
For example, in Nx projects, the referenced configs are `tsconfig.app.json` and
`tsconfig.editor.json`. `tsconfig.app.json` comes first in the base `tsconfig.json` and
contains the entry point of the app. `tsconfig.editor.json` contains the `**.ts` glob of all TS
files. This means that `tsconfig.editor.json` will be preferred by the TS server for TS files
but the `tsconfig.app.json` will be used for HTML files since it comes first and we cannot
effectively express `projectContainsInfoDirectly` for HTML files.
We could consider also updating the language server implementation to attempt
to select the project to use for the template file based on which project
contains its component file directly, using either the internal `project.projectContainsInfoDirectly`
or as a workaround, check `project.isRoot(componentTsFile)`.
Finally, keeping the projects open is hugely important in the solution style config case like
Nx. When a TS file is opened, TypeScript will only retain `tsconfig.editor.json` and not
`tsconfig.app.json`. However, if our extension does not also know to select
`tsconfig.editor.json`, it will automatically select `tsconfig.app.json` since it is defined
first in the `tsconfig.json` file. So we need to teach TS server that we are (1) interested in
keeping projects open when there is an HTML file open and (2) optionally attempt to do this
_only_ for projects that we know the TS language service will prioritize in TS files (i.e.,
attempt to only keep `tsconfig.editor.json` open and allow `tsconfig.app.json` to close)
and prioritize that project for all requests.
fixes https://github.com/angular/vscode-ng-language-service/issues/1623
fixes https://github.com/angular/vscode-ng-language-service/issues/876
PR Close#45601
This commit improves the error message for using `imports` on a component
that isn't set to `standalone: true`. Two concrete improvements are made:
* A related information message is added to the diagnostic which suggests
the fix of adding `standalone: true`.
* The component is marked as poisoned, preventing other errors which might
be caused by an incorrectly configured template scope from being generated
and thus masking the original problem.
Fixes#45850
PR Close#45851
In AOT compilations, the `strictInjectionParameters` compiler option can
be enabled to report errors when an `@Injectable` annotated class has a
constructor with parameters that do not provide an injection token, e.g.
only a primitive type or interface.
Since Ivy it's become required that any class with Angular behavior
(e.g. the `ngOnDestroy` lifecycle hook) is decorated using an Angular
decorator, which meant that `@Injectable()` may need to have been added
to abstract base classes. Doing so would then report an error if
`strictInjectionParameters` is enabled, if the abstract class has an
incompatible constructor for DI purposes. This may be fine though, as
a subclass may call the constructor explicitly without relying on
Angular's DI mechanism.
Therefore, this commit excludes abstract classes from the
`strictInjectionParameters` check. This avoids an error from being
reported at compile time. If the constructor ends up being used by
Angular's DI system at runtime, then the factory function of the
abstract class will throw an error by means of the `ɵɵinvalidFactory`
instruction.
In addition to the runtime error, this commit also analyzes the inheritance
chain of an injectable without a constructor to verify that their inherited
constructor is valid.
Closes#37914
PR Close#44615
Excludes styles that resolve to empty strings from the emitted metadata so that they don't result in empty `<style>` tags at runtime.
Fixes#31191.
PR Close#45459
Changes the message from:
```
The component 'HelloComponent' appears in 'imports', but is not standalone
and cannot be imported directly It must be imported via an NgModule.
```
to
```
The component 'HelloComponent' appears in 'imports', but is not standalone
and cannot be imported directly. It must be imported via an NgModule.
```
PR Close#45827
The analysis phase of the compiler should operate on individual classes, independently
of the analysis of other classes. The validation that `Component.imports` only
contains standalone entities or NgModules however did happen during the analysis phase,
introducing a dependency on other classes and causing inconsistencies due to ordering
and/or asynchronous timing differences.
This commit fixes the issue by moving the validation to the resolve phase, which occurs
after all classes have been analyzed.
Fixes#45819
PR Close#45827
This commit updates the logic to detect a situation when a standalone component is used in the NgModule-based bootstrap (`@NgModule.bootstrap`). Both AOT and JIT compilers are updated to handle this situation.
PR Close#45825
Adds support for TypeScript 4.7. Changes include:
* Bumping the TS version as well as some Bazel dependencies to include https://github.com/bazelbuild/rules_nodejs/pull/3420.
* Adding a backwards-compatibility layer for calls to `updateTypeParameterDeclaration`.
* Making `LView` generic in order to make it easier to type the context based on the usage. Currently the context can be 4 different types which coupled with stricter type checking would required a lot of extra casting all over `core`.
* Fixing a bunch of miscellaneous type errors.
* Removing assertions of `ReferenceEntry.isDefinition` in a few of the language service tests. The field isn't returned by TS anymore and we weren't using it for anything.
* Resolving in error in the language service that was caused by TS attempting to parse HTML files when we try to open them. Previous TS was silently setting them as `ScriptKind.Unknown` and ignoring the errors, but now it throws. I've worked around it by setting them as `ScriptKind.JSX`.
PR Close#45749
Before standalone, everything that could appear in an NgModule's `imports`
was relevant to DI, and needed to be emitted in the `imports` of the
generated `InjectorDef` definition. With the introduction of standalone
types, NgModule `imports` can now contain components, directives, and pipes
which are standalone. Only standalone components need to be included in
the `imports` of the generated injector definition - directives and pipes
have no effect on DI. Having them present doesn't cause any errors in the
runtime (they're filtered out by the injector itself) but it does prevent
tree-shaking.
With this commit, the generation of `InjectorDef` now filters the `imports`
to exclude directives and pipes as much as possible. It's not _always_
possible because an expression in `imports` may pull in both a directive and
a `ModuleWithProviders` reference, and we have no way of referencing just
the MWP part of that expression. Therefore this is an optimization, not a
rule of `InjectorDef` compilation.
PR Close#45701
Previously, the NgModule handler would resolve the `imports` field as one
unit, producing an array of `Reference`s. With this refactoring, if
`imports` is a literal array, each individual element will be resolved
independently. This will allow filtering in the future at the element level,
since there will be a separate `ts.Expression` for each individual element.
PR Close#45701
This commit updates the `ForeignFunctionResolver` used by the NgModule
handler to resolve `ModuleWithProvider` types. Previously, this resolver
returned the NgModule `Reference` directly, but there are two problems with
this:
* It's not completely accurate, as the expression returned by the MWP call
will not return the NgModule at runtime.
* We need the ability to distinguish the MWP call itself from an ordinary
NgModule reference in future optimizations.
PR Close#45701