Commit graph

1004 commits

Author SHA1 Message Date
Kristiyan Kostadinov
01722ee637 build: fix size failure (#54756)
Fixes a broken size CI check.

PR Close #54756
2024-03-07 16:13:44 -08:00
Paul Gschwendtner
866271a1c6 refactor(core): EventEmitter implements OutputRef. (#54650)
An `EventEmitter` is a construct owned by Angular that should be
used for outputs as of right now.

As we are introducing the new `OutputRef` interface for the new output
function APIs, we also think `EventEmitter` should implement
`OutputRef`— ensuring all "known" outputs follow the same contract.

This commit ensures `EventEmitter` implements an `OutputRef`

Note: An output ref captures the destroy ref from the current injection
context for clean-up purposes. This is also done for `EventEmitter` in a
backwards compatible way:

- not requiring an injection context. EventEmitter may be used
  elsewhere.
- not cleaning up subscriptions/completing the emitter when the
  directive/component is destroyed. This would be a change in behavior.

Note 2: The dependency on `DestroyRef` causes it to be retained in all
bundling examples because ironically `NgZone` uses `EventEmitter`- not
for outputs. The code is pretty minimal though, so that should be
acceptable.

`EventEmitter` will now always retain `NgZone. This increases the
payload size slightly around 800b for AIO. Note that the other increases
were coming from previous changes. This commit just pushed it over the
threshold.

PR Close #54650
2024-03-06 12:34:39 +01:00
Paul Gschwendtner
30355f6719 refactor(core): model() implements OutputRef (#54650)
A model signal is technically an output, at runtime and conceptually.

This commit re-uses the shared output ref logic and ensures the
interfaces match.

PR Close #54650
2024-03-06 12:34:38 +01:00
Paul Gschwendtner
aff65fd1f4 feat(core): introduce outputToObservable interop helper (#54650)
This commit introduces an addition to `output()` and
`outputFromObservable`()` —called `outputToObservable()`.

The helper lives in the RxJS interop package and allows agnostic
programmatic subscriptions to `OutputRef`s by converting the output
to an observable with `.pipe` etc.

The function is ideally used in all places where you subscribe to an
output programmatically. Those outputs in the future, with the new APIs,
may not be actual RxJS constructs, but abstract `OutputRef`'s that
simply expose a `.subscribe` method. The helper allows you to
agnostically convert outputs to RxJS observables that you can safely
interact with.

The observables are also completed automatically, if possible, when the
owning directive/component is destroyed— Something that is not
guaranteed right now.

PR Close #54650
2024-03-06 12:34:38 +01:00
Paul Gschwendtner
c809069f21 feat(core): introduce outputFromObservable() interop function (#54650)
Introduces a second API in addition to the new `output()` function.

The new function `outputFromObservable()` can be used to declare outputs
using the new `OutputRef` API and `output()` API, while using a custom
RxJS observable as data source.

This is something that is currently possible in Angular and we would
like to keep possible- even though we never intended to support custom
observables aside from RxJS-based `EventEmitter`.

The interop bridges the gap and allows you to continue using
`Subject`, `ReplaySubject`, `BehaivorSubjct,` - or cold custom
observables for outputs. You can still trigger logic only when
the output is subscribed- unlike with imperative `emit`s of
`EventEmitter` or the new `OutputEmitterRef`.

A notable difference is that you need two class members where you
previously could access the `Subject` directly. This is an intentional
trade-off we've made to ensure that all new outputs implement the
`OutputRef` interface and we are exposing a minimal API surface to
consumers of components that currently access the output
programmatically.

PR Close #54650
2024-03-06 12:34:38 +01:00
Paul Gschwendtner
c687b8f453 feat(core): expose new output() API (#54650)
This commit exposes the new `output()` API with numerous benefits:

- Symmetrical API to `input()`, `model()` etc.
- Fixed types for `EventEmitter.emit`— current `emit` method of
  `EventEmitter` is broken and accepts `undefined` via `emit(value?: T)`
- Removal of RxJS specific concepts from outputs. error channels,
  completion channels etc. We now have a simple consistent
  interface.
- Automatic clean-up of subscribers upon directive/component destory-
  when subscribed programmatically.

```ts
@Directive({..})
export class MyDir {
  nameChange = output<string>();     // OutputEmitterRef<string>
  onClick = output();                // OutputEmitterRef<void>
}
```

Note: RxJS custom observable cases will be handled in future commits via
explicit helpers from the interop.

PR Close #54650
2024-03-06 12:34:38 +01:00
Andrew Scott
c1c7384e02 feat(router): Add reusable types for router guards (#54580)
This refactor makes it easier to update the return types of guards.
Rather than having to track what types guards can return, which may
change with new features over time, `MaybeAsync<GuardResult>` can be
used instead.

PR Close #54580
2024-02-28 18:09:33 +01:00
Kristiyan Kostadinov
331b16efd2 feat(core): add API to inject attributes on the host node (#54604)
Angular has the `@Attribute` decorator that allows for attributes to be injected from the host node, but we don't have an equivalent for the `inject` function. These changes introduce the new `HostAttributeToken` class that can be used to inject attributes similarly to `@Attribute`. It can be used as follows:

```typescript
import {HostAttributeToken, inject} from '@angular/core';

class MyDir {
  someAttr = inject(new HostAttributeToken('some-attr'));
}
```

The new API works similarly to `@Attribute` with one key exception: it will throw a DI error when the attribute doesn't exist, instead of returning `null` like `@Attribute`. We made this change to align its behavior closer to other injection tokens.

PR Close #54604
2024-02-27 15:18:41 -08:00
Kristiyan Kostadinov
974958913c feat(core): support TypeScript 5.4 (#54414)
Adds support for TypeScript 5.4 to the project.

PR Close #54414
2024-02-26 18:29:09 -08:00
Andrew Scott
a9741e69d2 docs(router): deprecate RouterTestingModule (#54466)
Deprecate `RouterTestingModule` as it is no longer needed or useful and
is not actively maintained.

fixes #54461

PR Close #54466
2024-02-20 09:33:16 -08:00
Kristiyan Kostadinov
58666e905d refactor(core): reuse input signal node for models (#54387)
Reworks the model so that it reuses `INPUT_SIGNAL_NODE` instead of implementing its own.

PR Close #54387
2024-02-12 11:01:52 -08:00
Kristiyan Kostadinov
4a7ca50328 refactor(core): avoid wrapper around subscribe return value (#54387)
Reworks `ModelSignal.subscribe` so it doesn't have to wrap its value to look like a subscription.

PR Close #54387
2024-02-12 11:01:52 -08:00
Payam Valadkhan
27886cccce refactor(compiler-cli): use a more generic error for unsupported expressions in local compilation mode (#54366)
A new error code `LOCAL_COMPILATION_UNSUPPORTED_EXPRESSION` is added for this purpose, replacing a narrow one.

PR Close #54366
2024-02-12 08:49:03 -08:00
Kristiyan Kostadinov
dab5fc30ee fix(core): expose model signal subcribe for type checking purposes (#54357)
The `@internal` in the comment above `ModelSignal.subscribe` ended up marking the method as internal even though it wasn't meant to be.

PR Close #54357
2024-02-09 09:58:55 +00:00
ascorbic
03c3b3eb79 feat(common): add Netlify image loader (#54311)
Add an image loader for Netlify Image CDN. It is slightly different in implementation from existing loaders, because it allows absolute URLs

Fixes #54303

PR Close #54311
2024-02-08 16:17:57 +00:00
Kristiyan Kostadinov
e921e108e1 refactor(core): correctly distinguish getter functions from writable signals (#54252)
Fixes that `ɵunwrapWritableSignal` inferring getter functions as not matching the interface of `WritableSignal` instead of preserving them.

PR Close #54252
2024-02-07 16:36:15 +00:00
Kristiyan Kostadinov
243b94c6e1 refactor(compiler-cli): fix regression in two-way bindings to inputs with different getter/setter types (#54252)
In a previous commit the TCB was changed to cast the assignment to an input in order to widen its type to allow `WritableSignal`. This ended up breaking existing inputs whose setter has a wider type than its getter. These changes switch to unwrapping the value on the binding side.

PR Close #54252
2024-02-07 16:36:13 +00:00
Kristiyan Kostadinov
702ab28b4c feat(core): add support for model inputs (#54252)
Adds support for model inputs in the framework. `model()` returns a writable signal that implicitly defines a input/output pair that can be used either in two-way bindings to keep two values in sync or by binding individually to the input and output. When the value of the `model` changes, it will emit an event with the current value.

Furthermore, these changes expand two-way bindings to accept `WritableSignal`. This will make it easier to transition existing code to signals in a backwards-compatible way.

Example:

```ts
@Directive({
  selector: 'counter',
  standalone: true,
  host: {
    '(click)': 'increment()',
  }
})
export class Counter {
  value = model(0);

  increment(): void {
    this.value.update(current => current + 1);
  }
}

@Component({
  template: `<counter [(value)]="count"/> The current count is: {{count()}}`,
})
class App {
  count = signal(0);
}
```

PR Close #54252
2024-02-07 16:36:09 +00:00
Paul Gschwendtner
c023e8d58f refactor(core): improve IDE completion of read option for signal queries (#54280)
This commit improves IDE completion of the `read` option for
signal-based queries.

Currently, TS only matches the first overload when starting out with
defining a query. TS doesn't build up the combination of possible
options from the second overload- so in practice users will only see
IDE completions for the `descendants` option.

This is not a problem for view queries as the only option is `read`, so
TS will always match the overload with the `read` option.

```
class X {
  query = contentChild('', {^^ <--
    here we should completion for `read` an `descendants`
}
```

PR Close #54280
2024-02-07 16:35:14 +00:00
Payam Valadkhan
df74ed94e2 refactor(compiler-cli): upgrade error codes and messages for unresolved symbol errors in local compilation mode (#54230)
A single error code is created to unify the common error pattern in local compilation mode where an imported const cannot be resolved, but needs to be resolved. This mainly happens for Angular decorator fields such as @Component.template.

The error messages are also upgraded to be more centered around this unifying theme.

PR Close #54230
2024-02-06 21:33:29 +00:00
Pawel Kozlowski
e95ef2cbc6 feat(core): expose queries as signals (#54283)
This commit exposes authoring functions for queries as signals
thus making those generally available.

PR Close #54283
2024-02-06 19:31:58 +00:00
Pawel Kozlowski
99bfbabe50 refactor(core): break circular dependencies in preparation for queries as signals (#54103)
Break circular dependencies by using type imports and code moves.

PR Close #54103
2024-02-06 15:04:36 +00:00
Pawel Kozlowski
3a2ce9e0a2 refactor(core): add error code for required query results (#54103)
This commit introduces a dedicated error code for queries that require
results but none are available.

PR Close #54103
2024-02-06 15:04:36 +00:00
Pawel Kozlowski
20008a6b56 refactor(core): rework runtime implementation to simplify and fix issues (#54103)
This commit changes the approach to the reactive node representing query
results: instead of creating a custom node type we can use a computed -
the main change to get there is representing dirty change notification as
a signal (a counter updated every time a query changes its dirty status).

This change is dictated by simplification (we can avoid creation of a custom
signal type) as well as fixes to the multiple issues not covered by the
initial implementation:
- assuring referential stability of results (ex.: the same array instance
  returned from child queries until results change);
- per-view results collection to avoid a situation where accessing query
  results during view creation would return partial / inconsistent results;
- proper refresh of query results for both live and non-connected consumers.

All the above cases are covered by the additional tests in this commit.

PR Close #54103
2024-02-06 15:04:36 +00:00
Paul Gschwendtner
f7da77b90d refactor(compiler-cli): detect output() function (#54217)
As we are introducing the new `output()` function as an inituive
alternative to `@Output()` that matches with signal-based inputs,
this commit prepares the compiler to detect such initializer-based
outputs.

PR Close #54217
2024-02-05 15:08:34 +00:00
Joey Perrott
0460a9dfaf refactor: migrate common to prettier formatting (#54150)
Migrate formatting to prettier for common from clang-format

PR Close #54150
2024-01-30 16:08:07 +00:00
Payam Valadkhan
fc55de1416 refactor(compiler-cli): incorporate LocalCompilationExtraImportsTracker in the compilation workflow (#53543)
This commit includes a skeleton of how the tool `LocalCompilationExtraImportsTracker` is used in the overall compilation workflow end-to-end.

First of all, a new option `generateExtraImportsInLocalMode` is added, whose presence will make `LocalCompilationExtraImportsTracker` part of the compilation process. When this option is set an instance of `LocalCompilationExtraImportsTracker` is created within the NgCompiler. Then it is passed to the Ivy transformer and plumbed all the way down and the extra imports registered in it are added to the `ImportManager` instances before the imports are added from `ImportManager` to the generated file. This required adding a new method `generateSideEffectImport` to the `ImportManager`, which is an empty method and will be implemented in the subsequent commits.

This commit expected to make no change in the compilation behavior as the methods are not implemented yet.

PR Close #53543
2024-01-30 15:05:42 +00:00
Andrew Scott
3ca34e606d refactor(core): Update ComponentFixture behavior when using zoneless scheduler (#54024)
When the zoneless scheduler is provided, we want to update the behavior
of `ComponentFixture` to address common issues and painpoints in testing.
Developers should never have to call `detectChanges` on a fixture
manually. Instead of calling `detectChanges` after performing an
action that updates state and requies a template refresh, developers
should wait for change detection to run because the update needs to also have
notified the scheduler. If this was not the case, the component would
not work correctly in the application. Calling `detectChanges` to force
an update could hide real bugs.

This commit also updates the zoneless tests to uses `ComponentFixture`
instead of manually attaching to the `ApplicationRef` and rewriting a
lot of the helpers (`getDebugNode`, `isStable` as a value, `whenStable` as a
Promise).

PR Close #54024
2024-01-29 20:21:47 +00:00
Alex Castle
f5c520b836 feat(common): add placeholder to NgOptimizedImage (#53783)
Add a automatic placeholder implementation supporting loader-based and data URL placeholders

PR Close #53783
2024-01-29 16:00:38 +00:00
Paul Gschwendtner
b78042f3a5 refactor(core): separate InputSignal and InputSignalWithTransform (#54053)
This commit separates `InputSignal` for input signals with transforms.
The reason being that most of the time, signal inputs are not using
transforms and the generics are rather confusing.

Especially for users with inferred types displayed in their IDEs, the
input signal types are seemingly complex, even if no transform is used.

For this reason, we are introducing a new type called
`InputSignalWithTransform`. This type will be used for inputs with
transforms, while non-transform inputs just use `InputSignal`.

A notable fact is that `InputSignal` extends `InputSignalWithTransform`,
with the "identity transform". i.e. there is no transform. This allows
us to share the code for input signals. In practice, we don't expect
users to pass around `InputSignal`'s anyway.

PR Close #54053
2024-01-26 19:10:56 +00:00
Pawel Kozlowski
c04312860b refactor(core): introduce instructions for view queries as signals (#54017)
This commit adds new instructions to support view queries as signals.

PR Close #54017
2024-01-24 18:39:51 -05:00
Dylan Hunn
47e6e84101 feat(compiler): Add a TSConfig option useTemplatePipeline (#54057)
The Template Pipeline is a brand new backend for the Angular compiler, replacing `TemplateDefinitionBuilder`. It generates the Ivy instructions corresponding to an input template (or host binding). The Template Pipeline has an all-new design based on an intermediate representation compiled over many phases, which will allow us to experiment with compiler changes more easily in the future.

With this commit, the template pipeline can now be enabled in any project via the `useTemplatePipeline` TSConfig option. However, it is still disabled by default.

PR Close #54057
2024-01-24 18:36:23 -05:00
Paul Gschwendtner
17a47c4c54 refactor(compiler-cli): additional diagnostics for signal-based queries (#54019)
This commit introduces three additional diagnostics for queries:

- If a query (either using decorator or signal-based) is declared on a
  static class member, a diagnostic is raised.
- If a signal-based query is mixed with a query decorator, a diagnostic
  is raised. Similar to signal inputs.
- If a singal-based query is also declared in the directive/component
  class decorator metadata, a diagnostic is raised.

PR Close #54019
2024-01-24 16:13:31 +01:00
Payam Valadkhan
3e1384048e feat(compiler-cli): support host directives for local compilation mode (#53877)
At the moment local compilation breaks for host directives because the current logic relies on global static analysis. This change creates a local version by cutting the diagnostics and copying the directive identifier as it is to the generated code without attempting to statically resolve it.

PR Close #53877
2024-01-22 14:44:24 +01:00
Dylan Hunn
d0ce0110e8 Revert "refactor(core): improve forwardRef typings (#53880)" (#53961)
This reverts commit af6f6e6448.

PR Close #53961
2024-01-17 13:56:07 -08:00
Pawel Kozlowski
af6f6e6448 refactor(core): improve forwardRef typings (#53880)
This commit improves the forwardRef typings for better
type safety and inference.

PR Close #53880
2024-01-12 10:26:01 -08:00
Andrew Kushnir
a2aa23d8b5 refactor(compiler): add support for internal deferredImports field (#53591)
This commit updates the logic to add support for internal `deferredImports` field in compiler.

PR Close #53591
2024-01-10 15:28:58 -08:00
Andrew Kushnir
d28cf00df6 refactor(compiler-cli): add an internal config to enforce explicit deps in @defer for local compilation mode (#53591)
This commit adds an internal config option to enforce explicit deps in `@defer` for local compilation mode.

PR Close #53591
2024-01-10 15:28:58 -08:00
Paul Gschwendtner
863be4b698 feat(core): expose new input API for signal-based inputs (#53872)
Enables signal inputs for existing Zone based components.
This is a next step we are taking to bring signal inputs earlier to the Angular community.

The goal is to enable early access for the ecosystem to signal inputs, while we are continuing
development of full signal components as outlined in the RFC. This will allow the ecosystem
to start integrating signals more deeply, prepare for future migrations, and improves code quality
and DX for existing components (especially for OnPush).

Based on our work on full signal components, we've gathered more information and learned
new things. We've improved the API by introducing a way to intuitively declare required inputs,
as well as improved the API around initial values. We even support non-primitive initial values
as the first argument to the `input` function now.

```ts
@Directive({..})
export class MyDir {
  firstName = input<string>();            // string|undefined
  lastName = input.required<string>();    // string
  age = input(0);                         // number
```

PR Close #53872
2024-01-10 12:33:31 -08:00
Paul Gschwendtner
e934f3a581 refactor(compiler-cli): add diagnostic for inputs declared on static members (#53808)
Currently when someone declares a signal or non-signal input on a static
class member, the compiler will not yield any diagnostic. We can detect
these mistakes and report a diagnostic to help our users.

PR Close #53808
2024-01-10 12:21:06 +00:00
Paul Gschwendtner
40b0467d3e refactor(compiler-cli): diagnostics ensuring signal inputs are declared properly (#53808)
This commit addds two diagnostics for two scenarios where signal inputs
are declared incorrectly:

- a signal input is also annotated with `@Input` in the TypeScript
  sources.
- a signal input is also declared in the `inputs` option of
  `@Directive/`@Component`.

PR Close #53808
2024-01-10 12:21:05 +00:00
Paul Gschwendtner
1df95cd1c1 refactor(core): improve error message and add guide for required inputs (#53808)
Whenever a required input is accessed too early in a
directive/component, the signal input will throw an error.

This is necessary so that we can support required inputs
with intuitive typings that do not include `undefined` for
the short period of time where Angular is creating the component and
then assigning inputs later (Angular currently has no way of setting
inputs as part of the class creation when `new Dir()` happens)

PR Close #53808
2024-01-10 12:21:05 +00:00
Matthieu Riegler
09baed082b refactor(core): remove signal mutate implementation (#52348)
It's not used anymore.

PR Close #52348
2024-01-09 12:23:07 -08:00
Joey Perrott
1be6b0a58a fix(common): remove unused parameters from the ngClass constructor (#53831)
Remove unused parameters which were only being kept because of a downstream usage in flex layout which is deprecated and end of life

PR Close #53831
2024-01-08 14:38:50 -08:00
Angular Robot
4a87a8ac10 build: update cross-repo angular dependencies (#53836)
See associated pull request for more information.

PR Close #53836
2024-01-08 11:31:57 -08:00
Andrew Scott
dfcf0d5882 fix(core): afterRender hooks now only run on ApplicationRef.tick (#52455)
The `afterRender` hooks currently run after `ApplicationRef.tick` but
also run after any call to `ChangeDetectorRef.detectChanges`. This is
problematic because code which uses `afterRender` cannot expect the
component it's registered from to be rendered when the callback
executes. If there is a call to `ChangeDetectorRef.detectChanges` before
the global change detection, that will cause the hooks to run earlier
than expected.

This behavior is somewhat of a blocker for the zoneless project. There
is plenty of application code that do things like `setTimeout(() =>
doSomethingThatExpectsComponentToBeRendered())`, `NgZone.onStable(() =>
...)` or `ApplicationRef.onStable...`. `ApplicationRef.onStable` is a
should likely work similarly, but all of these are really wanting an API
that is `afterRender` with the requirement that the hook runs after the
global render, not an individual CDRef instance.

This change updates the `afterRender` hooks to only run when
`ApplicationRef.tick` happens.

fixes #52429
fixes #53232

PR Close #52455
2024-01-08 11:30:27 -08:00
Andrew Scott
a5a9b408e2 feat(router): Add transient info to RouterLink input (#53784)
This is a follow up to 5c1d441029
which added the `info` property to navigation requests. `RouterLink` now
supports passing that transient navigation info to the navigation
request.

This info object can be anything and doesn't have to be serializable.
One use-case might be for passing the element that was clicked. This
might be useful for something like view transitions. In the "animating
with javascript" example from the blog (https://stackblitz.com/edit/stackblitz-starters-cklnkm)
those links could have done this instead of needing to create a separate
directive that tracks clicks.

PR Close #53784
2024-01-05 11:28:31 -08:00
Paul Gschwendtner
7fb4a37f7d refactor(core): introduce runtime InputSignal implementation (#53571)
This commit introduces the runtime `InputSignal` implementation.
Input initializers using `input` or `input.required` will result in
an instance of `InputSignal` to be created.

An input signal extends the signal primtive, with a couple of small
differences:

 - it's a readonly signal. There is no public `set` or `update`.
 - equality is non-configurable. As per CD semantics, the value is
   guaranteed to be different when the `property` instruction attempts
   to update an input signal.
 - we support a `transform` function, that allows transforming input
   values. The transform is called whenever the input is set. An
   alternative could have been to follow computed-semantics and call the
   transform upon accessing, if dirty.

In the future, we might change this to extend the computed reactive
node, so that we can support computed inputs that do not rely on
continious bound value assignments. See signal based components RFC.

PR Close #53571
2024-01-04 12:07:13 -08:00
Paul Gschwendtner
caf3eec51a refactor(core): expose SIGNAL_NODE to allow for advanced extensions of signals (#53571)
For the implementation of input signals, we want to extend the signal
primitive. The basic methods exposed here are not suitable as we'd like
to store additional metadata on the reactive node, and also have a
custom getter (for required inputs and throwing).

To enable this, one small piece was missing. This commit exposes it and
also improves type safety, now that `SignalNode` is typed properly after
the previous commit.

PR Close #53571
2024-01-04 12:07:12 -08:00
Paul Gschwendtner
69b384c0d1 fix(core): SignalNode reactive node incorrectly exposing unset field (#53571)
The `SignalNode` interface, describing the reactive node for a `Signal`,
seemingly exposes the `SIGNAL` symbol as a class member. This is not
true as the `SIGNAL` reactive node only exists on the getter function,
as a way to retrieve the signal underlying reactive node.

This commit fixes this, enabling improved type-safety later, in a
follow-up commit where `SIGNAL_NODE` can now be typed to match the
`SignalNode` interface (unlike now where it's typed as just `object`).

PR Close #53571
2024-01-04 12:07:12 -08:00