This commit adds the `provideLocationMocks()` function that returns mocks for the `Location` and `LocationStrategy` classes. This function can be used in tests to configure an environment where it's possible to fire simulated location events (helpful when testing Router configuration).
PR Close#47674
This commit updates the `RouterLink` to extend the selector to also include `<a>` and `<area>` elements, which were previously matched by the `RouterLinkWithHref` directive. The code of the directives was merged together (since there was a lot of duplication) and this commit finalizes the merge. The `RouterLinkWithHref` becomes an alias of the `RouterLink` directive.
Now there is no need to import and use the `RouterLinkWithHref` class, the `RouterLink` directive will match any element that has the `routerLink` attribute.
DEPRECATED:
The `RouterLinkWithHref` directive is deprecated, use the `RouterLink` directive instead. The `RouterLink` contains the code from the `RouterLinkWithHref` to handle elements with `href` attributes.
PR Close#47630
The `relativeLinkResolution` is no longer supported. The only behavior
now is the correct behavior.
BREAKING CHANGE: `relativeLinkResolution` is no longer configurable in
the Router. This option was used as a means to opt out of a bug fix.
PR Close#47623
When using `loadChildren` or `loadComponent`, a common pattern is to pass
a function that returns a `Promise` from a dynamic import:
```typescript
{
path: 'lazy',
loadComponent: () => import('./lazy-file').then(m => m.LazyCmp),
}
```
The `.then` part of the expression selects the particular exported
component symbol from the dynamically imported ES module.
ES modules can have a "default export", created with the `export default`
modifier:
```typescript
@Component({...})
export default class LazyCmp { ... }
```
This default export is made available to dynamic imports under the well-
known key of `'default'`, per the ES module spec:
https://tc39.es/ecma262/#table-export-forms-mapping-to-exportentry-records
This commit adds a feature to the router to automatically dereference such
default exports. With this logic, when `export default` is used, a `.then`
operation to select the particular exported symbol is no longer required:
```typescript
{
path: 'lazy',
loadComponent: () => import('./lazy-file'),
}
```
The above `loadComponent` operation will automatically use the `default`
export of the `lazy-file` ES module.
This functionality works for `loadChildren` as well.
PR Close#47586
This commit updates the 'name' of `RouterOutlet` to be an `Input` rather
than an attribute. Note that this change does not affect `[attr.name]=`
because those already would not have worked. The static name was only
read in the constructor and if it wasn't available, it would use
'PRIMARY' instead.
fixes#12522
BREAKING CHANGE: Previously, the `RouterOutlet` would immediately
instantiate the component being activated during navigation. Now the
component is not instantiated until the change detection runs. This
could affect tests which do not trigger change detection after a router
navigation. In rarer cases, this can affect production code that relies
on the exact timing of component availability.
PR Close#46569
ActivatedRouteSnapshot data gets mutated in the resolve phase of the Router. The title is assigned as part of this.
As a result, the title must be a getter in order to pick up the value that was note available during the class creation.
fixes#47459
BREAKING CHANGE: The title property is now required on ActivatedRouteSnapshot
PR Close#47481
This commit creates and exposes the APIs required to use the Angular Router without importing `RouterModule`.
The newly added APIs are tree-shakable and you can add features using special functions rather than using `ExtraOptions` to control the providers via an internal switch in Router code.
```
const appRoutes: Routes = [];
bootstrapApplication(AppComponent,
{
providers: [
provideRouter(appRoutes,
withDebugTracing(), // enables debug tracing feature
withInMemoryScrolling() // enables scrolling feature
]
}
);
```
This "features" pattern allows for router behavior to evolve in a backwards compatible and tree-shakable way in the future. This approach also makes features more discoverable.
The newly added APIs can be used in any application today (doesn't require an application to be bootstrapped using standalone-based APIs).
Note: APIs added in this commit are released in the "Developer Preview" mode, read more about this mode in Angular docs: https://angular.io/guide/releases#developer-preview
PR Close#47010
Add wider typings to setter of preserveFragment, skipLocationChange and replaceUrl inputs of routerLink directives and coerce them to boolean
PR Close#47101
The current error message is absolute in that it thinks there is only
one possible way to provide Router twice. In fact, you can get a new
instance of the Router in several ways so the error message should
indicate the exact failure case with a _potential_ cause.
Based on findings in thread 0cbbd6aeec (commitcomment-80900192)
PR Close#47130
The current Router APIs require guards/resolvers to be present in the DI tree. This is because we want to treat all guards/resolvers equally and some may require dependencies. This requirement results in quite a lot of boilerplate for guards. Here are two examples:
```
const MY_GUARD = new InjectionToken<any>('my_guard');
…
providers: {provide: MY_GUARD, useValue: () => window.someGlobalState}
…
const route = {path: 'somePath', canActivate: [MY_GUARD]}
```
```
@Injectable({providedIn: 'root'})
export class MyGuardWithDependency {
constructor(private myDep: MyDependency) {}
canActivate() {
return myDep.canActivate();
}
}
…
const route = {path: 'somePath', canActivate: [MyGuardWithDependency]}
```
Notice that even when we want to write a simple guard that has no dependencies as in the first example, we still have to write either an InjectionToken or an Injectable class.
With this commit router guards and resolvers can be plain old functions.
For example:
```
const route = {path: 'somePath', component: EditCmp, canDeactivate: [(component: EditCmp) => !component.hasUnsavedChanges]}
```
Additionally, these functions can still use Angular DI with `inject` from `@angular/core`.
```
const route = {path: 'somePath', canActivate: [() => inject(MyDependency).canActivate()]}
```
PR Close#46684
In Angular 14, we introduced the `loadComponent` API for a `Route` to
allow lazy loading of a routed component in addition to the existing
`loadChildren` which allows lazy loading of child routes. As a result,
the `preload` method of the `PreloadingStrategy` needs to sometimes be
called even when there is a `canLoad` guard on the `Route`. `CanLoad`
guards block loading of child routes but _do not_ block loading of the
component.
This change updates the conditional checks in the internal preloader to
skip calling the `PreloadingStrategy.preload` when there is only a
`loadChildren` callback with a `canLoad` guard an no `loadComponent`.
In this case, the callback passed to the `preload` method is already
effectively a no-op so it's not necessary to call it at all.
resolves#47003
PR Close#47007
This commit refactors the `NgModuleRef` implementation to drop functions required by the `EnvironmentInjector` interface. Previously the idea was that the `NgModuleRef` can act as an Injector to facilitate easier transition to standalone. However, from the mental model perspective, the `NgModuleRef` has the `injector` field, which is the correct injector reference and can be used is needed as an `EnvironmentInjector`.
PR Close#46896
Karma jasmine updated the `jasmine-core` dependency. Jasmine is now more
strict when:
* The done callback is invoked multiple times
* The done callback is used, while a promise is also returned
* The done callback is treated as error when e.g. a number is returned
as first argument. This was the case with `requestAnimationFrame`.
The Router transition observable pipe keeps an outer reference to a `t`
variable for use in the `catchError` operator. However, this variable is
not updated with intermediate state. This commit fixes that so the
`catchError` can access properties that get updated in intermediate
states. Specifically, `RouterStateSnapshot` in the `NavigationError` for
now but could be more in the future.
PR Close#46842
Before this commit, the `NavigationCancellationCode` would always be set
to `Redirect` when encountering a "navigationcancelingError". However,
this error can also be thrown when `CanLoad` guars reject. This commit
ensures these cancellation errors have a code as well so this mistake
cannot be made again.
PR Close#46752
The existing logic does something similar but in a more roundabout way.
It reads _the whole array_. If it encounters a pending value, it ignores
the remaining ones. If it hasn't encountered a pending value by the time
it hits false/UrlTree, it returns that result.
The new logic is the same, but reverses what we're looking for. Instead
of processing the whole array, we stop when we encounter an initial
value. When we encounter one that isn't `true`, that gets returned. If
we get to the end and everything was `true`, return `true`.
PR Close#46745
PR Close#46745
Previously, if `initialNavigation` were set to `enabledBlocking`, the
Router's `APP_INITIALIZER` would never resolve if that initial
navigation failed. This results in the application load hanging and
never completing.
fixes#44355
PR Close#46026
There can be timing issues with removing an old outlet and creating a
new one to replace it. Before calling `onChildOutletDestroyed`, the
`RouterOutlet` will first check to ensure that it is still the one
registered for that outlet name.
Fixes#36711Fixes#32453
PR Close#46554
Currently it's not possible to return plain `UrlTree` from `CanMatchFn`,
only wrapped `UrlTree` into Observable or Promise is allowed.
These changes allow to return `UrlTree` from `CanMatchFn`.
PR Close#46455
The `CanMatchFn` is already exposed in the type signature for `canMatch` on the
`Route`. This function type should already be exposed as public API but was
missed in the initial implementation because the older guards use the `any` type
instead.
PR Close#46394
Once a `Route` matches via the `match` or `path` property, we need to
immediately create the injector for the route (if it has providers)
before running the `CanMatch` guards. This is necessary because the
`CanMatch` guards might be provided in the `Route` providers.
Fixes#46386
PR Close#46394
The `Observable` chain is currenlty the most straightforward way to
handle navigation cancellations where we ensure that the cancelled
navigation does not continue to be processed. Until we design and
implement an alternative way to accomplish equivalent functionality,
we need to maintain the `Observable` chain wherever we might execute
user code. One reason for this isthat user code may contain redirects so we do not
want to execute those redirects if the navigation was already cancelled.
PR Close#46021
Currently we have two main types of guards:
`CanLoad`: decides if we can load a module (used with lazy loading)
`CanActivate` and friends. It decides if we can activate/deactivate a route.
So we always decide where we want to navigate first ("recognize") and create a new router state snapshot. And only then we run guards to check if the navigation should be allowed.
This doesn't handle one very important use case where we want to decide where to navigate based on some data (e.g., who the user is).
I suggest to add a new guard that allows us to do that.
```
[
{path: 'home', component: AdminHomePage, canUse: [IsAdmin]},
{path: 'home', component: SimpleHomePage}
]
```
Here, navigating to '/home' will render `AdminHomePage` if the user is an admin and will render 'SimpleHomePage' otherwise. Note that the url will remain '/home'.
With the introduction of standalone components and new features in the Router such as `loadComponent`,
there's a case for deprecating `CanLoad` and replacing it with the `CanMatch` guard. There are a few reasons for this:
* One of the intentions of having separate providers on a Route is that lazy
loading should not be an architectural feature of an application. It's an
optimization you do for code size. That is, there should not be an architectural
feature in the router to specifically control whether to lazy load something or
not based on conditions such as authentication. This is a slight nuanced
difference between the proposed canUse guard: this guard would control whether
you can use the route at all and as a side-effect, whether we download the code.
`CanLoad` only specified whether the code should be downloaded so canUse is more powerful and more appropriate.
* The naming of `CanLoad` will be potentially misunderstood for the `loadComponent` feature.
Because it applies to `loadChildren`, it feels reasonable to think that it will
also apply to `loadComponent`. This isn’t the case: since we don't need
to load the component until right before activation, we defer the
loading until all guards/resolvers have run.
When considering the removal of `CanLoad` and replacing it with `CanMatch`, this
does inform another decision that needed to be made: whether it makes sense for
`CanMatch` guards to return a UrlTree or if they should be restricted to just boolean.
The original thought was that no, these new guards should not allow returning UrlTree
because that significantly expands the intent of the feature from simply
“can I use the route” to “can I use this route, and if not, should I redirect?”
I now believe it should allowed to return `UrlTree` for several reasons:
* For feature parity with `CanLoad`
* Because whether we allow it as a return value or not, developers will still be
able to trigger a redirect from the guards using the `Router.navigate` function.
* Inevitably, there will be developers who disagree with the philosophical decision
to disallow `UrlTree` and we don’t necessarily have a compelling reason to refuse this as a feature.
Relates to #16211 - `CanMatch` instead of `CanActivate` would prevent
blank screen. Additional work is required to close this issue. This can
be accomplished by making the initial navigation result trackable (including
the redirects).
Resolves#14515
Replaces #16416Resolves#34231Resolves#17145Resolves#12088
PR Close#46021
* beforePreactivation hook is unused
* The only place that uses afterPreactivation does not use the arguments
Not to say we won't want to provide hooks similar to this in the future,
but the current state is over-engineered for what it's being used for.
PR Close#46321
This adds a test to illustrate the "canceling" behavior we get from the
`Observable` chain in the Router. A new navigation cancels ongoing ones,
and that means also preventing intermediate results in user guards from
executing. This test is important when thinking about future refactors
which might attempt to change the details of how the `applyRedirects`
operator executes.
PR Close#46231
This exposes a new function from the router public API that allows
developers to create a `UrlTree` from _any_ `ActivatedRouteSnapshot`.
The current Router APIs only support creating a `UrlTree` from an
`ActivatedRoute` which is both active _and_ materially appears in the
`UrlTree` (it cannot be an empty path named outlet). This is because the
implementation of the current way of creating a `UrlTree` attempts to
look up the `UrlSegment` of the `ActivatedRoute` in the currently active
`UrlTree` of the router. When this doesn't work, the `UrlTree` creation
fails.
Note that this API does not replace the current one. That would actually be a
breaking change but should be done at some point in the future (v15). That is,
`router.navigate` should call this new function. At that point, we can
remove `_lastPathIndex`, `_urlSegment`, and `_correctedPathIndex` from
the `ActivatedRoute`, along with all of the logic associated with
determining what those should be. In addition, this would unblock a fix
for #26081 because the `applyRedirects` and `recognize` operations
could be combined into one. Overall, this would simplify logic in the router
and reduce code size. It also exposes core routing capabilities as a helper function
which were previously private API, which is a necessary step towards #42953.
As a stress test for this new function, it _was_ swapped in as the
default for `UrlTree` creation in #45859 and tested internally. The
results indicate that this function behaves correctly.
resolves#42191 (Tested directly)
resolves#38276 (The test with a guard covers this case)
resolves#22763 (Tested directly)
PR Close#45877
Adds additional tests to verify `enabledBlocking` functionality. The
initial attempt to fix#44355 would have broken the scenario where a new
navigation cancels the initial navigation. We also cannot rely on
`NavigationError` like the example workaround in that issue report is
doing because there won't be one if a guard simply rejects
the initial nav (#16211).
PR Close#45733
Currently, the `Router` will create the `EnvironmentInjector` for a
`Route` with `providers` as soon as it _attempts_ to match segments to
the `Route`. Instead, this change updates the logic to only create the
injector once we have confirmed that the `Route` matches. Note that this
will include partial matches where the final navigation still fails with
a "cannot match any routes to segment" error. We need to maintain the
injector hierarchy so we still need to create parent injectors before
descending into the child routes and determining if there is a full
match or just a partial one.
resolves#45988
PR Close#45990
Similarly to the symmetry being strengthened between children and loadChildren,
a new loadComponent property will be introduced as the asynchronous version of component.
This will allow for direct single-component lazy loading:
```
{path: 'lazy/a', loadComponent:
() => import('./lazy/a.component').then(m => m.ACmp)},
{path: 'lazy/b', loadComponent:
() => import('./lazy/b.component').then(m => m.BCmp)},
```
This option requires that the component being loaded is standalone and
is implemented as a runtime check.
Other notes:
* Components are not loaded until all guards and resolvers complete.
* Loading the component is included in the function passed to the router
preloading strategy
* `RouteConfigLoadStart` and `RouteConfigLoadEnd` events emit at the
start and end of the component loading
* `CanLoad` guards _do not_ apply to `loadComponent`. `canActivate`
should be used instead, just like you would do if it were simply
`component` instead.
PR Close#45705
This commit expands the `LoadChildrenCallback` to accept returning `Routes`
in addition to the existing `NgModule` type. In addition, it adds a
check to ensure these loaded routes all use standalone components.
The components must be standalone because if they were not,
we would not have the required `NgModule` which the component is declared in.
Existing API:
```
{path: 'lazy/route', loadChildren: import('./lazy').then(m => m.LazyModule)}
@NgModule({
imports: [
ExtraCmpModule,
RouterModule.forChild([
{path: 'extra/route', component: ExtraCmp},
]),
],
})
export class LazyModule {}
```
The new API for lazy loading route configs with standalone components
(no NgModule) is to expand `loadChildren` to allow returning simply a `Routes` array.
```
// parent.ts
{
path: 'parent',
loadChildren: () => import('./children').then(m => m.ROUTES),
}
// children.ts
export const ROUTES: Route[] = [
{path: 'child', component: ChildCmp},
];
```
Note that this includes minimal documentation updates. We need to
include a holistic update to the documentation for standalone components
in the future that includes this feature.
PR Close#45700
add the ariaCurrentWhenActive input to the RouterLinkActive directive so that
users can easily set the aria-current property to their active router
links
resolves#35051
PR Close#45167
Currently, the only way to specify new providers for a `Route` and the
children is to create a new `NgModule` with those providers and use the
`loadChildren` feature. This is pretty confusing and a wholly indirect
way of accomplishing this task. With this commit, developers will be
able to specify a list of providers directly on the `Route` itself.
These providers will apply the that route and its children.
This feature was inspired by the upcoming standalone components feature.
This ties in there because, as mentioned before, the prior art for lazy
loading configs was to load an `NgModule`. This loaded module contained
new route configs _and_ could specify new providers. Separating those
two concepts, there should be a way to load _just_ some new routes, but
there should also be a way to specify new providers as well (something
you could do in the `NgModule` world and now will be able to do in the
world without any `NgModule` through this feature).
PR Close#45673
The `EnvironmentInjector` should be used instead of `Injector` for the
lazy loading. A future refactor will further update `RouterOutlet` to
use this injector to create the component rather the deprecated
`ComponentFactoryResolver`.
PR Close#45671
In the standalone world, these concepts will no longer be one and the
same. You can load routes without them being inside an `NgModule` with
`RouterModule.forChild`. In addition, routes will be able to define
their own providers, which will be included in an injector that is not
necessarily lazy loaded.
PR Close#45593
The `Injector` is really the piece of information that the `Router` is
interested in keeping track of. Storing the `NgModuleRef` is somewhat
confusing based on how it's used later on. `RouterOutlet` uses it for the
`componentFactoryResolver`, but this is not needed anymore (and deprecated). In
fact, we can get back to the `NgModuleRef` anyways using the injector.
For now, that's what this change does. A different refactor will remove
the use of the `componentFactoryResolver` altogether.
Additionally, in the standalone world, we plan to implement a feature to
allow defining `providers` directly on the `Route`. This means there
won't be an associated `NgModuleRef` so this refactor prepares for that
feature.
PR Close#45593
Lazy loaded configs are not validated at runtime like the initial set of
routes are. This change also validates lazy loaded configs right after
they're loaded.
BREAKING CHANGE: Lazy loaded configs are now also validated once loaded like the
initial set of routes are. Lazy loaded modules which have invalid Route
configs will now error. Note that this is only done in dev mode so
there is no production impact of this change.
Fixes#25431
PR Close#45526
Recently the navigation was on hold even at least one resolver didn't emit any value and completed, but another ones still are in progress to resolve any value. The changes cancel the navigation instantly if at least one resolver doesn't emit any value and completed.
PR Close#45621
This change adds code to compute the corrected value for a link,
regardless of the `relativeLinkResolution` value. Then, if the
`relativeLinkResolution` is set to `legacy` and differs from the correct
value, a warning is printed to the console in dev mode.
This change is meant to assist in notifying developers that they have
code which relies on the deprecated, broken behavior so they can fix and
update the code before the `relativeLinkResolution` option is fully
removed.
PR Close#45523
This change adds code to compute the corrected value for a link,
regardless of the `relativeLinkResolution` value. Then, if the
`relativeLinkResolution` is set to `legacy` and differs from the correct
value, a warning is printed to the console in dev mode.
This change is meant to assist in notifying developers that they have
code which relies on the deprecated, broken behavior so they can fix and
update the code before the `relativeLinkResolution` option is fully
removed.
PR Close#45523
Updates us to version 4.0 of Jasmine and fixes some errors that were the result of us depending upon deprecated APIs. We need to do this both to stay up to date and because it was going to break eventually, because one of the Bazel packages was logging a deprecation warning that version 4.0 was required.
There were also some cases where the state of `ngDevMode` had started leaking out between tests.
PR Close#45558
Updates us to version 4.0 of Jasmine and fixes some errors that were the result of us depending upon deprecated APIs. We need to do this both to stay up to date and because it was going to break eventually, because one of the Bazel packages was logging a deprecation warning that version 4.0 was required.
There were also some cases where the state of `ngDevMode` had started leaking out between tests.
PR Close#45558
in layers
Right now route static data are collected from its parents based on the logic
described in `inheritedParamsDataResolve()`, merged into a single object
and then merged again with merged data from resolvers. This means that a
child's data can be overriden by a resolver in its parent (#34361).
However, what is the expected behavior is not described in the documentation.
This PR changes this behavior and merges static data and resolved data
in "layers" (route by route) so child's static data and resolved data
cannot be overriden by their parents.
Fixes#34361
PR Close#45276