diff --git a/.gitignore b/.gitignore
index 460a9f4dcf..1b6531e7c7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -72,6 +72,8 @@ vite.config.ts.timestamp_*
.idea
*.vitest-temp.json
+.angular
+
# Handling VSCode settings
/.vscode/
!/examples/react/**/.vscode/settings.json
diff --git a/examples/angular/basic/.editorconfig b/examples/angular/basic/.editorconfig
new file mode 100644
index 0000000000..f166060da1
--- /dev/null
+++ b/examples/angular/basic/.editorconfig
@@ -0,0 +1,17 @@
+# Editor configuration, see https://editorconfig.org
+root = true
+
+[*]
+charset = utf-8
+indent_style = space
+indent_size = 2
+insert_final_newline = true
+trim_trailing_whitespace = true
+
+[*.ts]
+quote_type = single
+ij_typescript_use_double_quotes = false
+
+[*.md]
+max_line_length = off
+trim_trailing_whitespace = false
diff --git a/examples/angular/basic/.gitignore b/examples/angular/basic/.gitignore
new file mode 100644
index 0000000000..cc7b141350
--- /dev/null
+++ b/examples/angular/basic/.gitignore
@@ -0,0 +1,42 @@
+# See https://docs.github.com/get-started/getting-started-with-git/ignoring-files for more about ignoring files.
+
+# Compiled output
+/dist
+/tmp
+/out-tsc
+/bazel-out
+
+# Node
+/node_modules
+npm-debug.log
+yarn-error.log
+
+# IDEs and editors
+.idea/
+.project
+.classpath
+.c9/
+*.launch
+.settings/
+*.sublime-workspace
+
+# Visual Studio Code
+.vscode/*
+!.vscode/settings.json
+!.vscode/tasks.json
+!.vscode/launch.json
+!.vscode/extensions.json
+.history/*
+
+# Miscellaneous
+/.angular/cache
+.sass-cache/
+/connect.lock
+/coverage
+/libpeerconnection.log
+testem.log
+/typings
+
+# System files
+.DS_Store
+Thumbs.db
diff --git a/examples/angular/basic/.vscode/extensions.json b/examples/angular/basic/.vscode/extensions.json
new file mode 100644
index 0000000000..77b374577d
--- /dev/null
+++ b/examples/angular/basic/.vscode/extensions.json
@@ -0,0 +1,4 @@
+{
+ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846
+ "recommendations": ["angular.ng-template"]
+}
diff --git a/examples/angular/basic/.vscode/launch.json b/examples/angular/basic/.vscode/launch.json
new file mode 100644
index 0000000000..925af83705
--- /dev/null
+++ b/examples/angular/basic/.vscode/launch.json
@@ -0,0 +1,20 @@
+{
+ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
+ "version": "0.2.0",
+ "configurations": [
+ {
+ "name": "ng serve",
+ "type": "chrome",
+ "request": "launch",
+ "preLaunchTask": "npm: start",
+ "url": "http://localhost:4200/"
+ },
+ {
+ "name": "ng test",
+ "type": "chrome",
+ "request": "launch",
+ "preLaunchTask": "npm: test",
+ "url": "http://localhost:9876/debug.html"
+ }
+ ]
+}
diff --git a/examples/angular/basic/.vscode/tasks.json b/examples/angular/basic/.vscode/tasks.json
new file mode 100644
index 0000000000..a298b5bd87
--- /dev/null
+++ b/examples/angular/basic/.vscode/tasks.json
@@ -0,0 +1,42 @@
+{
+ // For more information, visit: https://go.microsoft.com/fwlink/?LinkId=733558
+ "version": "2.0.0",
+ "tasks": [
+ {
+ "type": "npm",
+ "script": "start",
+ "isBackground": true,
+ "problemMatcher": {
+ "owner": "typescript",
+ "pattern": "$tsc",
+ "background": {
+ "activeOnStart": true,
+ "beginsPattern": {
+ "regexp": "(.*?)"
+ },
+ "endsPattern": {
+ "regexp": "bundle generation complete"
+ }
+ }
+ }
+ },
+ {
+ "type": "npm",
+ "script": "test",
+ "isBackground": true,
+ "problemMatcher": {
+ "owner": "typescript",
+ "pattern": "$tsc",
+ "background": {
+ "activeOnStart": true,
+ "beginsPattern": {
+ "regexp": "(.*?)"
+ },
+ "endsPattern": {
+ "regexp": "bundle generation complete"
+ }
+ }
+ }
+ }
+ ]
+}
diff --git a/examples/angular/basic/README.md b/examples/angular/basic/README.md
new file mode 100644
index 0000000000..5134787e5c
--- /dev/null
+++ b/examples/angular/basic/README.md
@@ -0,0 +1,59 @@
+# Basic
+
+This project was generated using [Angular CLI](https://github.com/angular/angular-cli) version 19.2.5.
+
+## Development server
+
+To start a local development server, run:
+
+```bash
+ng serve
+```
+
+Once the server is running, open your browser and navigate to `http://localhost:4200/`. The application will automatically reload whenever you modify any of the source files.
+
+## Code scaffolding
+
+Angular CLI includes powerful code scaffolding tools. To generate a new component, run:
+
+```bash
+ng generate component component-name
+```
+
+For a complete list of available schematics (such as `components`, `directives`, or `pipes`), run:
+
+```bash
+ng generate --help
+```
+
+## Building
+
+To build the project run:
+
+```bash
+ng build
+```
+
+This will compile your project and store the build artifacts in the `dist/` directory. By default, the production build optimizes your application for performance and speed.
+
+## Running unit tests
+
+To execute unit tests with the [Karma](https://karma-runner.github.io) test runner, use the following command:
+
+```bash
+ng test
+```
+
+## Running end-to-end tests
+
+For end-to-end (e2e) testing, run:
+
+```bash
+ng e2e
+```
+
+Angular CLI does not come with an end-to-end testing framework by default. You can choose one that suits your needs.
+
+## Additional Resources
+
+For more information on using the Angular CLI, including detailed command references, visit the [Angular CLI Overview and Command Reference](https://angular.dev/tools/cli) page.
diff --git a/examples/angular/basic/package.json b/examples/angular/basic/package.json
new file mode 100644
index 0000000000..cf7140b5e5
--- /dev/null
+++ b/examples/angular/basic/package.json
@@ -0,0 +1,29 @@
+{
+ "name": "tanstack-router-angular-example-basic",
+ "version": "0.0.0",
+ "scripts": {},
+ "private": true,
+ "dependencies": {
+ "@angular/common": "^20.0.0",
+ "@angular/compiler": "^20.0.0",
+ "@angular/core": "^20.0.0",
+ "@angular/forms": "^20.0.0",
+ "@angular/platform-browser": "^20.0.0",
+ "@angular/platform-browser-dynamic": "^20.0.0",
+ "@tanstack/angular-router": "workspace:*",
+ "@tanstack/angular-router-devtools": "workspace:*",
+ "@tanstack/history": "workspace:*",
+ "@tanstack/router-core": "workspace:*",
+ "@tanstack/router-devtools-core": "workspace:*",
+ "rxjs": "~7.8.0",
+ "tiny-invariant": "^1.3.3",
+ "tiny-warning": "^1.0.3",
+ "tslib": "^2.3.0",
+ "zone.js": "~0.15.0"
+ },
+ "devDependencies": {
+ "@angular/build": "^20.0.0",
+ "@angular/compiler-cli": "^20.0.0",
+ "typescript": "~5.8.0"
+ }
+}
diff --git a/examples/angular/basic/project.json b/examples/angular/basic/project.json
new file mode 100644
index 0000000000..6febc19e69
--- /dev/null
+++ b/examples/angular/basic/project.json
@@ -0,0 +1,80 @@
+{
+ "name": "angular-basic",
+ "projectType": "application",
+ "sourceRoot": "examples/angular/basic/src",
+ "prefix": "app",
+ "targets": {
+ "build": {
+ "executor": "@angular/build:application",
+ "options": {
+ "outputPath": "examples/angular/basic/dist/basic",
+ "index": "examples/angular/basic/src/index.html",
+ "browser": "examples/angular/basic/src/main.ts",
+ "polyfills": ["zone.js"],
+ "tsConfig": "examples/angular/basic/tsconfig.app.json",
+ "assets": [{ "glob": "**/*", "input": "public" }],
+ "styles": ["examples/angular/basic/src/styles.css"],
+ "scripts": []
+ },
+ "configurations": {
+ "production": {
+ "budgets": [
+ {
+ "type": "initial",
+ "maximumWarning": "500kB",
+ "maximumError": "1MB"
+ },
+ {
+ "type": "anyComponentStyle",
+ "maximumWarning": "4kB",
+ "maximumError": "8kB"
+ }
+ ],
+ "outputHashing": "all"
+ },
+ "development": {
+ "optimization": false,
+ "extractLicenses": false,
+ "sourceMap": true
+ }
+ },
+ "defaultConfiguration": "production"
+ },
+ "serve": {
+ "executor": "@angular/build:dev-server",
+ "configurations": {
+ "production": {
+ "buildTarget": "angular-basic:build:production"
+ },
+ "development": {
+ "buildTarget": "angular-basic:build:development"
+ }
+ },
+ "defaultConfiguration": "development"
+ },
+ "extract-i18n": {
+ "executor": "@angular/build:extract-i18n"
+ },
+ "test": {
+ "executor": "@angular/build:karma",
+ "options": {
+ "polyfills": ["zone.js", "zone.js/testing"],
+ "tsConfig": "examples/angular/basic/tsconfig.spec.json",
+ "assets": [
+ {
+ "glob": "**/*",
+ "input": "public"
+ }
+ ],
+ "styles": ["examples/angular/basic/src/styles.css"],
+ "scripts": []
+ }
+ }
+ },
+ "schematics": {
+ "@schematics/angular:component": {
+ "inlineTemplate": true,
+ "inlineStyle": true
+ }
+ }
+}
diff --git a/examples/angular/basic/public/favicon.ico b/examples/angular/basic/public/favicon.ico
new file mode 100644
index 0000000000..57614f9c96
Binary files /dev/null and b/examples/angular/basic/public/favicon.ico differ
diff --git a/examples/angular/basic/src/app/app.config.ts b/examples/angular/basic/src/app/app.config.ts
new file mode 100644
index 0000000000..c7903d52dc
--- /dev/null
+++ b/examples/angular/basic/src/app/app.config.ts
@@ -0,0 +1,13 @@
+import { provideZoneChangeDetection } from '@angular/core'
+import { provideRouter } from '@tanstack/angular-router'
+
+import { router } from './app.routes'
+
+import type { ApplicationConfig } from '@angular/core'
+
+export const appConfig: ApplicationConfig = {
+ providers: [
+ provideZoneChangeDetection({ eventCoalescing: true }),
+ provideRouter(router),
+ ],
+}
diff --git a/examples/angular/basic/src/app/app.routes.ts b/examples/angular/basic/src/app/app.routes.ts
new file mode 100644
index 0000000000..c89c5efe4b
--- /dev/null
+++ b/examples/angular/basic/src/app/app.routes.ts
@@ -0,0 +1,30 @@
+import { createRouter } from '@tanstack/angular-router'
+
+import { rootRoute } from './root'
+import { indexRoute } from './home'
+import { postsLayoutRoute } from './posts/layout'
+import { postRoute } from './posts/post'
+import { postsIndexRoute } from './posts/index'
+import { nestedPathlessLayout2Route } from './pathless/nested'
+import { pathlessLayoutRoute } from './pathless/a-layout'
+import { pathlessLayoutARoute } from './pathless/a'
+import { pathlessLayoutBRoute } from './pathless/b'
+
+export const routeTree = rootRoute.addChildren([
+ postsLayoutRoute.addChildren([postRoute, postsIndexRoute]),
+ pathlessLayoutRoute.addChildren([
+ nestedPathlessLayout2Route.addChildren([
+ pathlessLayoutARoute,
+ pathlessLayoutBRoute,
+ ]),
+ ]),
+ indexRoute,
+])
+
+export const router = createRouter({ routeTree })
+
+declare module '@tanstack/angular-router' {
+ interface Register {
+ router: typeof router
+ }
+}
diff --git a/examples/angular/basic/src/app/app.ts b/examples/angular/basic/src/app/app.ts
new file mode 100644
index 0000000000..921d2b12c3
--- /dev/null
+++ b/examples/angular/basic/src/app/app.ts
@@ -0,0 +1,9 @@
+import { Component } from '@angular/core'
+import { RouterRoot } from '@tanstack/angular-router'
+
+@Component({
+ selector: 'app-root',
+ imports: [RouterRoot],
+ template: ` `,
+})
+export class AppComponent {}
diff --git a/examples/angular/basic/src/app/home/index.ts b/examples/angular/basic/src/app/home/index.ts
new file mode 100644
index 0000000000..14ad55b43f
--- /dev/null
+++ b/examples/angular/basic/src/app/home/index.ts
@@ -0,0 +1,19 @@
+import { Component } from '@angular/core'
+import { createRoute } from '@tanstack/angular-router'
+
+import { rootRoute } from '../root'
+
+export const indexRoute = createRoute({
+ getParentRoute: () => rootRoute,
+ path: '/',
+ component: () => Index,
+})
+
+@Component({
+ template: `
+
+
Welcome Home!
+
+ `,
+})
+export class Index {}
diff --git a/examples/angular/basic/src/app/pathless/a-layout.ts b/examples/angular/basic/src/app/pathless/a-layout.ts
new file mode 100644
index 0000000000..f8122069f0
--- /dev/null
+++ b/examples/angular/basic/src/app/pathless/a-layout.ts
@@ -0,0 +1,23 @@
+import { Component } from '@angular/core'
+import { Outlet, createRoute } from '@tanstack/angular-router'
+
+import { rootRoute } from '../root'
+
+export const pathlessLayoutRoute = createRoute({
+ getParentRoute: () => rootRoute,
+ id: '_pathlessLayout',
+ component: () => PathlessLayout,
+})
+
+@Component({
+ imports: [Outlet],
+ template: `
+
+
I'm a pathless layout
+
+
+
+
+ `,
+})
+export class PathlessLayout {}
diff --git a/examples/angular/basic/src/app/pathless/a.ts b/examples/angular/basic/src/app/pathless/a.ts
new file mode 100644
index 0000000000..3c76f72a21
--- /dev/null
+++ b/examples/angular/basic/src/app/pathless/a.ts
@@ -0,0 +1,15 @@
+import { Component } from '@angular/core'
+import { createRoute } from '@tanstack/angular-router'
+
+import { nestedPathlessLayout2Route } from './nested'
+
+export const pathlessLayoutARoute = createRoute({
+ getParentRoute: () => nestedPathlessLayout2Route,
+ path: '/route-a',
+ component: () => PathlessLayoutA,
+})
+
+@Component({
+ template: ` I'm route A!
`,
+})
+export class PathlessLayoutA {}
diff --git a/examples/angular/basic/src/app/pathless/b.ts b/examples/angular/basic/src/app/pathless/b.ts
new file mode 100644
index 0000000000..1776ee32a1
--- /dev/null
+++ b/examples/angular/basic/src/app/pathless/b.ts
@@ -0,0 +1,15 @@
+import { Component } from '@angular/core'
+import { createRoute } from '@tanstack/angular-router'
+
+import { nestedPathlessLayout2Route } from './nested'
+
+export const pathlessLayoutBRoute = createRoute({
+ getParentRoute: () => nestedPathlessLayout2Route,
+ path: '/route-b',
+ component: () => PathlessLayoutB,
+})
+
+@Component({
+ template: ` I'm route B!
`,
+})
+export class PathlessLayoutB {}
diff --git a/examples/angular/basic/src/app/pathless/nested.ts b/examples/angular/basic/src/app/pathless/nested.ts
new file mode 100644
index 0000000000..8a737e76d7
--- /dev/null
+++ b/examples/angular/basic/src/app/pathless/nested.ts
@@ -0,0 +1,26 @@
+import { Component } from '@angular/core'
+import { Link, Outlet, createRoute } from '@tanstack/angular-router'
+import { pathlessLayoutRoute } from './a-layout'
+
+export const nestedPathlessLayout2Route = createRoute({
+ getParentRoute: () => pathlessLayoutRoute,
+ id: '_nestedPathlessLayout',
+ component: () => PathlessLayout2,
+})
+
+@Component({
+ imports: [Outlet, Link],
+ template: `
+
+
I'm a nested pathless layout
+
+
+
+
+
+ `,
+})
+export class PathlessLayout2 {}
diff --git a/examples/angular/basic/src/app/posts.ts b/examples/angular/basic/src/app/posts.ts
new file mode 100644
index 0000000000..54d62e5788
--- /dev/null
+++ b/examples/angular/basic/src/app/posts.ts
@@ -0,0 +1,32 @@
+import axios from 'redaxios'
+
+export class NotFoundError extends Error {}
+
+type PostType = {
+ id: string
+ title: string
+ body: string
+}
+
+export const fetchPosts = async () => {
+ console.info('Fetching posts...')
+ await new Promise((r) => setTimeout(r, 500))
+ return axios
+ .get>('https://jsonplaceholder.typicode.com/posts')
+ .then((r) => r.data.slice(0, 10))
+}
+
+export const fetchPost = async (postId: string) => {
+ console.info(`Fetching post with id ${postId}...`)
+ await new Promise((r) => setTimeout(r, 500))
+ const post = await axios
+ .get(`https://jsonplaceholder.typicode.com/posts/${postId}`)
+ .then((r) => r.data)
+
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
+ if (!post) {
+ throw new NotFoundError(`Post with id "${postId}" not found!`)
+ }
+
+ return post
+}
diff --git a/examples/angular/basic/src/app/posts/index.ts b/examples/angular/basic/src/app/posts/index.ts
new file mode 100644
index 0000000000..4d408dbad4
--- /dev/null
+++ b/examples/angular/basic/src/app/posts/index.ts
@@ -0,0 +1,15 @@
+import { Component } from '@angular/core'
+import { createRoute } from '@tanstack/angular-router'
+
+import { postsLayoutRoute } from './layout'
+
+export const postsIndexRoute = createRoute({
+ getParentRoute: () => postsLayoutRoute,
+ path: '/',
+ component: () => PostsIndex,
+})
+
+@Component({
+ template: ` Select a post.
`,
+})
+export class PostsIndex {}
diff --git a/examples/angular/basic/src/app/posts/layout.ts b/examples/angular/basic/src/app/posts/layout.ts
new file mode 100644
index 0000000000..b6fe7eb137
--- /dev/null
+++ b/examples/angular/basic/src/app/posts/layout.ts
@@ -0,0 +1,10 @@
+import { createRoute } from '@tanstack/angular-router'
+
+import { rootRoute } from '../root';
+import { fetchPosts } from '../posts';
+
+export const postsLayoutRoute = createRoute({
+ getParentRoute: () => rootRoute,
+ path: 'posts',
+ loader: () => fetchPosts(),
+}).lazy(() => import('./posts.lazy').then((d) => d.Route))
diff --git a/examples/angular/basic/src/app/posts/post.ts b/examples/angular/basic/src/app/posts/post.ts
new file mode 100644
index 0000000000..5f3a7ebd55
--- /dev/null
+++ b/examples/angular/basic/src/app/posts/post.ts
@@ -0,0 +1,24 @@
+import { Component } from '@angular/core'
+import { createRoute } from '@tanstack/angular-router'
+import { fetchPost } from '../posts'
+import { postsLayoutRoute } from './layout'
+
+export const postRoute = createRoute({
+ getParentRoute: () => postsLayoutRoute,
+ path: '$postId',
+ loader: ({ params }) => fetchPost(params.postId),
+ component: () => PostComponent,
+})
+
+@Component({
+ template: `
+
+
{{ post().title }}
+
+
{{ post().body }}
+
+ `,
+})
+export class PostComponent {
+ post = postRoute.loaderData()
+}
diff --git a/examples/angular/basic/src/app/posts/posts.lazy.ts b/examples/angular/basic/src/app/posts/posts.lazy.ts
new file mode 100644
index 0000000000..cc45e77988
--- /dev/null
+++ b/examples/angular/basic/src/app/posts/posts.lazy.ts
@@ -0,0 +1,31 @@
+import { Component } from '@angular/core'
+import { Link, Outlet, createLazyRoute } from '@tanstack/angular-router'
+
+export const Route = createLazyRoute('/posts')({
+ component: () => PostsLayoutComponent,
+})
+
+@Component({
+ imports: [Outlet, Link],
+ template: `
+
+ `,
+})
+export class PostsLayoutComponent {
+ posts = Route.loaderData()
+}
diff --git a/examples/angular/basic/src/app/root.ts b/examples/angular/basic/src/app/root.ts
new file mode 100644
index 0000000000..9be3e127ce
--- /dev/null
+++ b/examples/angular/basic/src/app/root.ts
@@ -0,0 +1,34 @@
+import {
+ DefaultNotFound,
+ Link,
+ Outlet,
+ createRootRoute,
+} from '@tanstack/angular-router'
+import { ChangeDetectionStrategy, Component } from '@angular/core'
+import { TanstackRouterDevtools } from '@tanstack/angular-router-devtools'
+
+export const rootRoute = createRootRoute({
+ component: () => Root,
+ notFoundComponent: () => DefaultNotFound,
+})
+
+@Component({
+ selector: 'Root',
+ template: `
+
+
+
+ `,
+ changeDetection: ChangeDetectionStrategy.OnPush,
+ imports: [Link, Outlet, TanstackRouterDevtools],
+})
+export class Root {
+ protected doesNotExist: any = '/this-route-does-not-exist'
+}
diff --git a/examples/angular/basic/src/index.html b/examples/angular/basic/src/index.html
new file mode 100644
index 0000000000..1e6f7a02a1
--- /dev/null
+++ b/examples/angular/basic/src/index.html
@@ -0,0 +1,13 @@
+
+
+
+
+ Basic
+
+
+
+
+
+
+
+
diff --git a/examples/angular/basic/src/main.ts b/examples/angular/basic/src/main.ts
new file mode 100644
index 0000000000..a934af599e
--- /dev/null
+++ b/examples/angular/basic/src/main.ts
@@ -0,0 +1,5 @@
+import { bootstrapApplication } from '@angular/platform-browser'
+import { appConfig } from './app/app.config'
+import { AppComponent } from './app/app'
+
+bootstrapApplication(AppComponent, appConfig).catch((err) => console.error(err))
diff --git a/examples/angular/basic/src/styles.css b/examples/angular/basic/src/styles.css
new file mode 100644
index 0000000000..90d4ee0072
--- /dev/null
+++ b/examples/angular/basic/src/styles.css
@@ -0,0 +1 @@
+/* You can add global styles to this file, and also import other style files */
diff --git a/examples/angular/basic/tsconfig.app.json b/examples/angular/basic/tsconfig.app.json
new file mode 100644
index 0000000000..3775b37e3b
--- /dev/null
+++ b/examples/angular/basic/tsconfig.app.json
@@ -0,0 +1,15 @@
+/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
+/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "outDir": "./out-tsc/app",
+ "types": []
+ },
+ "files": [
+ "src/main.ts"
+ ],
+ "include": [
+ "src/**/*.d.ts"
+ ]
+}
diff --git a/examples/angular/basic/tsconfig.json b/examples/angular/basic/tsconfig.json
new file mode 100644
index 0000000000..0cc518b718
--- /dev/null
+++ b/examples/angular/basic/tsconfig.json
@@ -0,0 +1,27 @@
+/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
+/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
+{
+ "compileOnSave": false,
+ "compilerOptions": {
+ "outDir": "./dist/out-tsc",
+ "strict": true,
+ "noImplicitOverride": true,
+ "noPropertyAccessFromIndexSignature": true,
+ "noImplicitReturns": true,
+ "noFallthroughCasesInSwitch": true,
+ "skipLibCheck": true,
+ "isolatedModules": true,
+ "esModuleInterop": true,
+ "experimentalDecorators": true,
+ "importHelpers": true,
+ "target": "ESNext",
+ "moduleResolution": "Bundler",
+ "module": "preserve"
+ },
+ "angularCompilerOptions": {
+ "enableI18nLegacyMessageIdFormat": false,
+ "strictInjectionParameters": true,
+ "strictInputAccessModifiers": true,
+ "strictTemplates": true
+ }
+}
diff --git a/examples/angular/basic/tsconfig.spec.json b/examples/angular/basic/tsconfig.spec.json
new file mode 100644
index 0000000000..5fb748d920
--- /dev/null
+++ b/examples/angular/basic/tsconfig.spec.json
@@ -0,0 +1,15 @@
+/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
+/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "outDir": "./out-tsc/spec",
+ "types": [
+ "jasmine"
+ ]
+ },
+ "include": [
+ "src/**/*.spec.ts",
+ "src/**/*.d.ts"
+ ]
+}
diff --git a/package.json b/package.json
index ebf7008739..e0ba31a056 100644
--- a/package.json
+++ b/package.json
@@ -67,7 +67,8 @@
"typescript57": "npm:typescript@5.7",
"typescript58": "npm:typescript@5.8",
"vite": "^7.1.7",
- "vitest": "^3.2.4"
+ "vitest": "^3.2.4",
+ "zone.js": "~0.15.1"
},
"pnpm": {
"overrides": {
@@ -112,8 +113,11 @@
"@tanstack/server-functions-plugin": "workspace:*",
"@tanstack/directive-functions-plugin": "workspace:*",
"@tanstack/router-utils": "workspace:*",
- "@tanstack/start-static-server-functions": "workspace:*",
- "@tanstack/nitro-v2-vite-plugin": "workspace:*"
+ "@tanstack/angular-router": "workspace:*",
+ "@tanstack/angular-router-devtools": "workspace:*"
+ },
+ "patchedDependencies": {
+ "@angular/build": "patches/@angular__build.patch"
}
}
}
diff --git a/packages/angular-router-devtools/README.md b/packages/angular-router-devtools/README.md
new file mode 100644
index 0000000000..9d6136c549
--- /dev/null
+++ b/packages/angular-router-devtools/README.md
@@ -0,0 +1,31 @@
+
+
+# TanStack Angular Router Devtools
+
+
+
+🤖 Type-safe router w/ built-in caching & URL state management for Angular!
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Enjoy this library? Try the entire [TanStack](https://tanstack.com)! [Angular Query](https://github.com/tanstack/query), [Angular Table](https://github.com/tanstack/table), [Angular Store](https://github.com/tanstack/store).
+
+## Visit [tanstack.com/router](https://tanstack.com/router) for docs, guides, API and more!
diff --git a/packages/angular-router-devtools/ng-package.json b/packages/angular-router-devtools/ng-package.json
new file mode 100644
index 0000000000..2c583ca1be
--- /dev/null
+++ b/packages/angular-router-devtools/ng-package.json
@@ -0,0 +1,9 @@
+{
+ "$schema": "./node_modules/ng-packagr/ng-package.schema.json",
+ "lib": {
+ "entryFile": "src/index.ts"
+ },
+ "allowedNonPeerDependencies": ["@tanstack/router-devtools-core", "solid-js"],
+ "dest": "dist",
+ "deleteDestPath": false
+}
diff --git a/packages/angular-router-devtools/package.json b/packages/angular-router-devtools/package.json
new file mode 100644
index 0000000000..2058ab16b4
--- /dev/null
+++ b/packages/angular-router-devtools/package.json
@@ -0,0 +1,67 @@
+{
+ "name": "@tanstack/angular-router-devtools",
+ "version": "1.115.2",
+ "description": "Modern and scalable routing for Angular applications",
+ "author": "Tanner Linsley",
+ "license": "MIT",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/TanStack/router.git",
+ "directory": "packages/angular-router-devtools"
+ },
+ "homepage": "https://tanstack.com/router",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/tannerlinsley"
+ },
+ "keywords": [
+ "angular",
+ "router",
+ "routing",
+ "async",
+ "async router",
+ "typescript"
+ ],
+ "scripts": {
+ "clean": "rimraf ./dist && rimraf ./coverage",
+ "test:eslint": "eslint",
+ "build": "ng-packagr -p ng-package.json -c tsconfig.lib.prod.json && premove ./dist/package.json",
+ "test:unit": "vitest"
+ },
+ "peerDependencies": {
+ "@angular/common": ">=20.0.0",
+ "@angular/core": ">=20.0.0",
+ "@angular/platform-browser-dynamic": ">=20.0.0",
+ "@tanstack/angular-router": "workspace:*",
+ "rxjs": "^7.8.0"
+ },
+ "dependencies": {
+ "@tanstack/router-devtools-core": "workspace:*",
+ "solid-js": "^1.9.5",
+ "tslib": "^2.3.0"
+ },
+ "files": [
+ "src",
+ "dist"
+ ],
+ "devDependencies": {
+ "@analogjs/vite-plugin-angular": "1.15.1-beta.3",
+ "@analogjs/vitest-angular": "1.15.1-beta.3",
+ "@tanstack/angular-router": "workspace:*",
+ "ng-packagr": "^20.0.0",
+ "premove": "^4.0.0"
+ },
+ "sideEffects": false,
+ "type": "module",
+ "types": "dist/index.d.ts",
+ "module": "dist/fesm2022/tanstack-angular-router-devtools.mjs",
+ "exports": {
+ "./package.json": {
+ "default": "./package.json"
+ },
+ ".": {
+ "types": "./dist/index.d.ts",
+ "default": "./dist/fesm2022/tanstack-angular-router-devtools.mjs"
+ }
+ }
+}
diff --git a/packages/angular-router-devtools/src/index.ts b/packages/angular-router-devtools/src/index.ts
new file mode 100644
index 0000000000..cdedbab341
--- /dev/null
+++ b/packages/angular-router-devtools/src/index.ts
@@ -0,0 +1 @@
+export * from './router-devtools'
diff --git a/packages/angular-router-devtools/src/router-devtools.ts b/packages/angular-router-devtools/src/router-devtools.ts
new file mode 100644
index 0000000000..0b16d89f96
--- /dev/null
+++ b/packages/angular-router-devtools/src/router-devtools.ts
@@ -0,0 +1,126 @@
+import {
+ Directive,
+ ElementRef,
+ NgZone,
+ afterNextRender,
+ booleanAttribute,
+ effect,
+ inject,
+ input,
+ signal,
+ untracked,
+} from '@angular/core'
+import { TanStackRouterDevtoolsCore } from '@tanstack/router-devtools-core'
+import { injectRouter, isDevMode } from '@tanstack/angular-router'
+
+@Directive({
+ selector: 'tanstack-router-devtools,TanstackRouterDevtools',
+ host: { style: 'display: block;' },
+})
+export class TanstackRouterDevtools {
+ private injectedRouter = injectRouter()
+ private host = inject>(ElementRef)
+ private ngZone = inject(NgZone)
+
+ router = input(this.injectedRouter)
+ show = input(isDevMode(), { transform: booleanAttribute })
+ initialIsOpen = input(undefined, { transform: booleanAttribute })
+ panelOptions = input>({})
+ closeButtonOptions = input>({})
+ toggleButtonOptions = input>({})
+ shadowDOMTarget = input()
+ containerElement = input()
+ position = input<'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'>()
+
+ private devtools = signal(null)
+
+ constructor() {
+ afterNextRender(() => {
+ const show = this.show()
+ if (!show) return
+
+ const router = untracked(this.router)
+ const [
+ initialIsOpen,
+ panelOptions,
+ closeButtonOptions,
+ toggleButtonOptions,
+ shadowDOMTarget,
+ containerElement,
+ position,
+ activeRouterState,
+ ] = [
+ untracked(this.initialIsOpen),
+ untracked(this.panelOptions),
+ untracked(this.closeButtonOptions),
+ untracked(this.toggleButtonOptions),
+ untracked(this.shadowDOMTarget),
+ untracked(this.containerElement),
+ untracked(this.position),
+ router.state,
+ ]
+
+ // initial devTools
+ this.devtools.set(
+ new TanStackRouterDevtoolsCore({
+ router,
+ routerState: activeRouterState,
+ initialIsOpen,
+ position,
+ panelProps: panelOptions,
+ closeButtonProps: closeButtonOptions,
+ toggleButtonProps: toggleButtonOptions,
+ shadowDOMTarget,
+ containerElement,
+ }),
+ )
+ })
+
+ effect(() => {
+ const devtools = this.devtools()
+ if (!devtools) return
+ this.ngZone.runOutsideAngular(() => devtools.setRouter(this.router()))
+ })
+
+ effect((onCleanup) => {
+ const devtools = this.devtools()
+ if (!devtools) return
+ this.ngZone.runOutsideAngular(() => {
+ const unsub = untracked(this.router).__store.subscribe(
+ ({ currentVal }) => {
+ devtools.setRouterState(currentVal)
+ },
+ )
+ onCleanup(() => unsub())
+ })
+ })
+
+ effect(() => {
+ const devtools = this.devtools()
+ if (!devtools) return
+
+ this.ngZone.runOutsideAngular(() => {
+ devtools.setOptions({
+ initialIsOpen: this.initialIsOpen(),
+ panelProps: this.panelOptions(),
+ closeButtonProps: this.closeButtonOptions(),
+ toggleButtonProps: this.toggleButtonOptions(),
+ position: this.position(),
+ containerElement: this.containerElement(),
+ shadowDOMTarget: this.shadowDOMTarget(),
+ })
+ })
+ })
+
+ effect((onCleanup) => {
+ const devtools = this.devtools()
+ if (!devtools) return
+ this.ngZone.runOutsideAngular(() =>
+ devtools.mount(this.host.nativeElement),
+ )
+ onCleanup(() => {
+ this.ngZone.runOutsideAngular(() => devtools.unmount())
+ })
+ })
+ }
+}
diff --git a/packages/angular-router-devtools/tests/index.spec.ts b/packages/angular-router-devtools/tests/index.spec.ts
new file mode 100644
index 0000000000..186a27cc93
--- /dev/null
+++ b/packages/angular-router-devtools/tests/index.spec.ts
@@ -0,0 +1,5 @@
+describe('', () => {
+ it('should work', () => {
+ expect(true).toBe(true);
+ });
+});
diff --git a/packages/angular-router-devtools/tests/setup-tests.ts b/packages/angular-router-devtools/tests/setup-tests.ts
new file mode 100644
index 0000000000..b56bce0e3f
--- /dev/null
+++ b/packages/angular-router-devtools/tests/setup-tests.ts
@@ -0,0 +1,15 @@
+import '@analogjs/vitest-angular/setup-zone';
+
+/**
+ * Initialize TestBed for all tests inside of content
+ */
+import { TestBed } from '@angular/core/testing';
+import {
+ BrowserDynamicTestingModule,
+ platformBrowserDynamicTesting,
+} from '@angular/platform-browser-dynamic/testing';
+
+TestBed.initTestEnvironment(
+ BrowserDynamicTestingModule,
+ platformBrowserDynamicTesting(),
+);
diff --git a/packages/angular-router-devtools/tsconfig.build.json b/packages/angular-router-devtools/tsconfig.build.json
new file mode 100644
index 0000000000..8d7766f377
--- /dev/null
+++ b/packages/angular-router-devtools/tsconfig.build.json
@@ -0,0 +1,15 @@
+{
+ "extends": "./node_modules/ng-packagr/lib/ts/conf/tsconfig.ngc.json",
+ "compilerOptions": {
+ "allowJs": true,
+ "module": "ESNext",
+ "moduleDetection": "force",
+ "moduleResolution": "Bundler"
+ },
+ "angularCompilerOptions": {
+ "enableI18nLegacyMessageIdFormat": false,
+ "strictInjectionParameters": true,
+ "strictInputAccessModifiers": true
+ },
+ "include": ["src"]
+}
\ No newline at end of file
diff --git a/packages/angular-router-devtools/tsconfig.json b/packages/angular-router-devtools/tsconfig.json
new file mode 100644
index 0000000000..5525117c67
--- /dev/null
+++ b/packages/angular-router-devtools/tsconfig.json
@@ -0,0 +1,27 @@
+/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
+/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
+{
+ "compileOnSave": false,
+ "compilerOptions": {
+ "outDir": "./dist/out-tsc",
+ "strict": true,
+ "noImplicitOverride": true,
+ "noPropertyAccessFromIndexSignature": true,
+ "noImplicitReturns": true,
+ "noFallthroughCasesInSwitch": true,
+ "skipLibCheck": true,
+ "isolatedModules": true,
+ "esModuleInterop": true,
+ "experimentalDecorators": true,
+ "moduleResolution": "bundler",
+ "importHelpers": true,
+ "target": "ES2022",
+ "module": "ES2022"
+ },
+ "angularCompilerOptions": {
+ "enableI18nLegacyMessageIdFormat": false,
+ "strictInjectionParameters": true,
+ "strictInputAccessModifiers": true,
+ "strictTemplates": true
+ }
+}
diff --git a/packages/angular-router-devtools/tsconfig.lib.json b/packages/angular-router-devtools/tsconfig.lib.json
new file mode 100644
index 0000000000..6886b6bcba
--- /dev/null
+++ b/packages/angular-router-devtools/tsconfig.lib.json
@@ -0,0 +1,13 @@
+/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
+/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "outDir": "../../out-tsc/lib",
+ "declaration": true,
+ "declarationMap": true,
+ "inlineSources": true,
+ "types": []
+ },
+ "exclude": ["**/*.spec.ts"]
+}
diff --git a/packages/angular-router-devtools/tsconfig.lib.prod.json b/packages/angular-router-devtools/tsconfig.lib.prod.json
new file mode 100644
index 0000000000..80e5438629
--- /dev/null
+++ b/packages/angular-router-devtools/tsconfig.lib.prod.json
@@ -0,0 +1,12 @@
+/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
+/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
+{
+ "extends": "./tsconfig.lib.json",
+ "compilerOptions": {
+ "declarationMap": false,
+ "strictNullChecks": true
+ },
+ "angularCompilerOptions": {
+ "compilationMode": "partial"
+ }
+}
diff --git a/packages/angular-router-devtools/tsconfig.spec.json b/packages/angular-router-devtools/tsconfig.spec.json
new file mode 100644
index 0000000000..82623f332f
--- /dev/null
+++ b/packages/angular-router-devtools/tsconfig.spec.json
@@ -0,0 +1,11 @@
+/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
+/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "outDir": "../../out-tsc/spec",
+ "types": ["vitest/globals"]
+ },
+ "files": ["tests/setup-tests.ts"],
+ "include": ["**/*.spec.ts", "**/*.test.ts", "**/*.d.ts"]
+}
diff --git a/packages/angular-router-devtools/vite.config.ts b/packages/angular-router-devtools/vite.config.ts
new file mode 100644
index 0000000000..a533656879
--- /dev/null
+++ b/packages/angular-router-devtools/vite.config.ts
@@ -0,0 +1,13 @@
+import { defineConfig } from 'vitest/config'
+import packageJson from './package.json'
+
+export default defineConfig({
+ test: {
+ name: packageJson.name,
+ dir: './tests',
+ watch: false,
+ environment: 'jsdom',
+ setupFiles: ['./tests/setup-tests.ts'],
+ globals: true,
+ },
+})
diff --git a/packages/angular-router/README.md b/packages/angular-router/README.md
new file mode 100644
index 0000000000..439e522584
--- /dev/null
+++ b/packages/angular-router/README.md
@@ -0,0 +1,31 @@
+
+
+# TanStack Angular Router
+
+
+
+🤖 Type-safe router w/ built-in caching & URL state management for Angular!
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Enjoy this library? Try the entire [TanStack](https://tanstack.com)! [Angular Query](https://github.com/tanstack/query), [Angular Table](https://github.com/tanstack/table), [Angular Store](https://github.com/tanstack/store).
+
+## Visit [tanstack.com/router](https://tanstack.com/router) for docs, guides, API and more!
diff --git a/packages/angular-router/ng-package.json b/packages/angular-router/ng-package.json
new file mode 100644
index 0000000000..ac9bc3f223
--- /dev/null
+++ b/packages/angular-router/ng-package.json
@@ -0,0 +1,15 @@
+{
+ "$schema": "./node_modules/ng-packagr/ng-package.schema.json",
+ "lib": {
+ "entryFile": "src/index.ts"
+ },
+ "allowedNonPeerDependencies": [
+ "@tanstack/router-core",
+ "@tanstack/history",
+ "jsesc",
+ "tiny-invariant",
+ "tiny-warning"
+ ],
+ "dest": "dist",
+ "deleteDestPath": false
+}
\ No newline at end of file
diff --git a/packages/angular-router/package.json b/packages/angular-router/package.json
new file mode 100644
index 0000000000..527b5200c0
--- /dev/null
+++ b/packages/angular-router/package.json
@@ -0,0 +1,73 @@
+{
+ "name": "@tanstack/angular-router",
+ "version": "1.115.2",
+ "description": "Modern and scalable routing for Angular applications",
+ "author": "Tanner Linsley",
+ "license": "MIT",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/TanStack/router.git",
+ "directory": "packages/angular-router"
+ },
+ "homepage": "https://tanstack.com/router",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/tannerlinsley"
+ },
+ "keywords": [
+ "angular",
+ "router",
+ "routing",
+ "async",
+ "async router",
+ "typescript"
+ ],
+ "scripts": {
+ "clean": "rimraf ./dist && rimraf ./coverage",
+ "test:eslint": "eslint",
+ "build": "ng-packagr -p ng-package.json -c tsconfig.lib.prod.json && premove ./dist/package.json",
+ "test:unit": "vitest"
+ },
+ "peerDependencies": {
+ "@angular/common": ">=20.0.0",
+ "@angular/core": ">=20.0.0",
+ "@angular/platform-browser-dynamic": ">=20.0.0",
+ "rxjs": "^7.8.0"
+ },
+ "dependencies": {
+ "@tanstack/history": "workspace:*",
+ "@tanstack/router-core": "workspace:*",
+ "jsesc": "^3.0.2",
+ "tiny-invariant": "^1.3.3",
+ "tiny-warning": "^1.0.3",
+ "tslib": "^2.3.0"
+ },
+ "files": [
+ "src",
+ "dist"
+ ],
+ "devDependencies": {
+ "@analogjs/vite-plugin-angular": "1.21.1",
+ "@analogjs/vitest-angular": "1.21.1",
+ "@testing-library/angular": "^17.3.7",
+ "@testing-library/dom": "^10.4.0",
+ "@testing-library/jest-dom": "^6.6.3",
+ "ng-packagr": "^20.0.0",
+ "premove": "^4.0.0",
+ "typescript": "~5.8.0",
+ "zod": "^3.23.8"
+ },
+ "sideEffects": false,
+ "type": "module",
+ "types": "dist/index.d.ts",
+ "module": "dist/fesm2022/tanstack-angular-router.mjs",
+ "exports": {
+ "./package.json": {
+ "default": "./package.json"
+ },
+ ".": {
+ "types": "./dist/index.d.ts",
+ "default": "./dist/fesm2022/tanstack-angular-router.mjs"
+ }
+ }
+}
diff --git a/packages/angular-router/src/can-go-back.ts b/packages/angular-router/src/can-go-back.ts
new file mode 100644
index 0000000000..8c20355eb3
--- /dev/null
+++ b/packages/angular-router/src/can-go-back.ts
@@ -0,0 +1,35 @@
+import {
+ Injector,
+ assertInInjectionContext,
+ inject,
+ runInInjectionContext,
+} from '@angular/core'
+import { toSignal } from '@angular/core/rxjs-interop'
+import { routerState$ } from './router-state'
+
+export function canGoBack$({ injector }: { injector?: Injector } = {}) {
+ !injector && assertInInjectionContext(canGoBack$)
+
+ if (!injector) {
+ injector = inject(Injector)
+ }
+
+ return runInInjectionContext(injector, () => {
+ return routerState$({
+ select: (s) => s.location.state.__TSR_index !== 0,
+ injector,
+ })
+ })
+}
+
+export function canGoBack({ injector }: { injector?: Injector } = {}) {
+ !injector && assertInInjectionContext(canGoBack)
+
+ if (!injector) {
+ injector = inject(Injector)
+ }
+
+ return runInInjectionContext(injector, () => {
+ return toSignal(canGoBack$({ injector }))
+ })
+}
diff --git a/packages/angular-router/src/default-error.ts b/packages/angular-router/src/default-error.ts
new file mode 100644
index 0000000000..b64bfd562a
--- /dev/null
+++ b/packages/angular-router/src/default-error.ts
@@ -0,0 +1,46 @@
+import {
+ ChangeDetectionStrategy,
+ Component,
+ inject,
+ signal,
+} from '@angular/core'
+import { ERROR_COMPONENT_CONTEXT } from './route'
+
+@Component({
+ selector: 'default-error,DefaultError',
+ template: `
+
+ Something went wrong!
+
+
+
+ @if (show()) {
+
+
+ @if (context.error.message; as message) {
+ {{ message }}
+ }
+
+
+ }
+ `,
+ styles: `
+ :host {
+ display: block;
+ padding: 0.5rem;
+ max-width: 100%;
+ }
+ `,
+ changeDetection: ChangeDetectionStrategy.OnPush,
+})
+export class DefaultError {
+ protected context = inject(ERROR_COMPONENT_CONTEXT)
+ protected show = signal(false)
+}
diff --git a/packages/angular-router/src/default-not-found.ts b/packages/angular-router/src/default-not-found.ts
new file mode 100644
index 0000000000..c36358bd09
--- /dev/null
+++ b/packages/angular-router/src/default-not-found.ts
@@ -0,0 +1,9 @@
+import { ChangeDetectionStrategy, Component } from '@angular/core'
+
+@Component({
+ selector: 'default-not-found,DefaultNotFound',
+ template: ` Page not found
`,
+ changeDetection: ChangeDetectionStrategy.OnPush,
+ host: { style: 'display: contents;' },
+})
+export class DefaultNotFound {}
diff --git a/packages/angular-router/src/file-route.ts b/packages/angular-router/src/file-route.ts
new file mode 100644
index 0000000000..bea9ac3f51
--- /dev/null
+++ b/packages/angular-router/src/file-route.ts
@@ -0,0 +1,223 @@
+import warning from 'tiny-warning'
+import { loaderData, loaderData$ } from './loader-data'
+import { loaderDeps, loaderDeps$ } from './loader-deps'
+import { match, match$ } from './match'
+import { params, params$ } from './params'
+import { createRoute } from './route'
+import { routeContext, routeContext$ } from './route-context'
+import { search, search$ } from './search'
+
+import type {
+ AnyContext,
+ AnyRoute,
+ AnyRouter,
+ Constrain,
+ ConstrainLiteral,
+ FileBaseRouteOptions,
+ FileRoutesByPath,
+ LazyRouteOptions,
+ RegisteredRouter,
+ ResolveParams,
+ RouteById,
+ RouteConstraints,
+ RouteIds,
+ RouteLoaderFn,
+ UpdatableRouteOptions,
+} from '@tanstack/router-core'
+import type { LoaderDataRoute } from './loader-data'
+import type { LoaderDepsRoute } from './loader-deps'
+import type { MatchRoute } from './match'
+import type { ParamsRoute } from './params'
+import type { Route } from './route'
+import type { RouteContextRoute } from './route-context'
+import type { SearchRoute } from './search'
+
+export function createFileRoute<
+ TFilePath extends keyof FileRoutesByPath,
+ TParentRoute extends AnyRoute = FileRoutesByPath[TFilePath]['parentRoute'],
+ TId extends RouteConstraints['TId'] = FileRoutesByPath[TFilePath]['id'],
+ TPath extends RouteConstraints['TPath'] = FileRoutesByPath[TFilePath]['path'],
+ TFullPath extends
+ RouteConstraints['TFullPath'] = FileRoutesByPath[TFilePath]['fullPath'],
+>(
+ path: TFilePath,
+): FileRoute['createRoute'] {
+ return new FileRoute(path, {
+ silent: true,
+ }).createRoute
+}
+
+/**
+ @deprecated It's no longer recommended to use the `FileRoute` class directly.
+ Instead, use `createFileRoute('/path/to/file')(options)` to create a file route.
+ */
+export class FileRoute<
+ TFilePath extends keyof FileRoutesByPath,
+ TParentRoute extends AnyRoute = FileRoutesByPath[TFilePath]['parentRoute'],
+ TId extends RouteConstraints['TId'] = FileRoutesByPath[TFilePath]['id'],
+ TPath extends RouteConstraints['TPath'] = FileRoutesByPath[TFilePath]['path'],
+ TFullPath extends
+ RouteConstraints['TFullPath'] = FileRoutesByPath[TFilePath]['fullPath'],
+> {
+ silent?: boolean
+
+ constructor(
+ public path: TFilePath,
+ _opts?: { silent: boolean },
+ ) {
+ this.silent = _opts?.silent
+ }
+
+ createRoute = <
+ TSearchValidator = undefined,
+ TParams = ResolveParams,
+ TRouteContextFn = AnyContext,
+ TBeforeLoadFn = AnyContext,
+ TLoaderDeps extends Record = {},
+ TLoaderFn = undefined,
+ TChildren = unknown,
+ >(
+ options?: FileBaseRouteOptions<
+ TParentRoute,
+ AnyRoute,
+ TId,
+ TPath,
+ TSearchValidator,
+ TParams,
+ TLoaderDeps,
+ TLoaderFn,
+ AnyContext,
+ TRouteContextFn,
+ TBeforeLoadFn
+ > &
+ UpdatableRouteOptions<
+ TParentRoute,
+ TId,
+ TFullPath,
+ TParams,
+ TSearchValidator,
+ TLoaderFn,
+ TLoaderDeps,
+ AnyContext,
+ TRouteContextFn,
+ TBeforeLoadFn
+ >,
+ ): Route<
+ TParentRoute,
+ TPath,
+ TFullPath,
+ TFilePath,
+ TId,
+ TSearchValidator,
+ TParams,
+ AnyContext,
+ TRouteContextFn,
+ TBeforeLoadFn,
+ TLoaderDeps,
+ TLoaderFn,
+ TChildren,
+ unknown
+ > => {
+ warning(
+ this.silent,
+ 'FileRoute is deprecated and will be removed in the next major version. Use the createFileRoute(path)(options) function instead.',
+ )
+ const route = createRoute(options as any)
+ ;(route as any).isRoot = false
+ return route as any
+ }
+}
+
+/**
+ @deprecated It's recommended not to split loaders into separate files.
+ Instead, place the loader function in the the main route file, inside the
+ `createFileRoute('/path/to/file)(options)` options.
+ */
+export function FileRouteLoader<
+ TFilePath extends keyof FileRoutesByPath,
+ TRoute extends FileRoutesByPath[TFilePath]['preLoaderRoute'],
+>(
+ _path: TFilePath,
+): (
+ loaderFn: Constrain<
+ TLoaderFn,
+ RouteLoaderFn<
+ TRoute['parentRoute'],
+ TRoute['types']['id'],
+ TRoute['types']['params'],
+ TRoute['types']['loaderDeps'],
+ TRoute['types']['routerContext'],
+ TRoute['types']['routeContextFn'],
+ TRoute['types']['beforeLoadFn']
+ >
+ >,
+) => TLoaderFn {
+ warning(
+ false,
+ `FileRouteLoader is deprecated and will be removed in the next major version. Please place the loader function in the the main route file, inside the \`createFileRoute('/path/to/file')(options)\` options`,
+ )
+ return (loaderFn) => loaderFn as any
+}
+
+export class LazyRoute {
+ options: {
+ id: string
+ } & LazyRouteOptions
+
+ constructor(
+ opts: {
+ id: string
+ } & LazyRouteOptions,
+ ) {
+ this.options = opts
+ }
+
+ match$: MatchRoute = (opts) =>
+ match$({ ...opts, from: this.options.id } as any) as any
+ match: MatchRoute = (opts) =>
+ match({ ...opts, from: this.options.id } as any) as any
+
+ routeContext$: RouteContextRoute = (opts) =>
+ routeContext$({ ...opts, from: this.options.id } as unknown as any)
+ routeContext: RouteContextRoute = (opts) =>
+ routeContext({ ...opts, from: this.options.id } as unknown as any)
+
+ search$: SearchRoute = (opts) =>
+ search$({ ...opts, from: this.options.id } as any) as any
+ search: SearchRoute = (opts) =>
+ search({ ...opts, from: this.options.id } as any) as any
+
+ params$: ParamsRoute = (opts) =>
+ params$({ ...opts, from: this.options.id } as any) as any
+ params: ParamsRoute = (opts) =>
+ params({ ...opts, from: this.options.id } as any) as any
+
+ loaderDeps$: LoaderDepsRoute = (opts) =>
+ loaderDeps$({ ...opts, from: this.options.id } as any)
+ loaderDeps: LoaderDepsRoute = (opts) =>
+ loaderDeps({ ...opts, from: this.options.id } as any)
+
+ loaderData$: LoaderDataRoute = (opts) =>
+ loaderData$({ ...opts, from: this.options.id } as any)
+ loaderData: LoaderDataRoute = (opts) =>
+ loaderData({ ...opts, from: this.options.id } as any)
+}
+
+export function createLazyRoute<
+ TRouter extends AnyRouter = RegisteredRouter,
+ TId extends string = string,
+ TRoute extends AnyRoute = RouteById,
+>(id: ConstrainLiteral>) {
+ return (opts: LazyRouteOptions) => {
+ return new LazyRoute({
+ id: id,
+ ...opts,
+ })
+ }
+}
+export function createLazyFileRoute<
+ TFilePath extends keyof FileRoutesByPath,
+ TRoute extends FileRoutesByPath[TFilePath]['preLoaderRoute'],
+>(id: TFilePath) {
+ return (opts: LazyRouteOptions) => new LazyRoute({ id, ...opts })
+}
diff --git a/packages/angular-router/src/index.ts b/packages/angular-router/src/index.ts
new file mode 100644
index 0000000000..7f78fa0d73
--- /dev/null
+++ b/packages/angular-router/src/index.ts
@@ -0,0 +1,305 @@
+export { default as invariant } from 'tiny-invariant'
+export { default as warning } from 'tiny-warning'
+
+export {
+ TSR_DEFERRED_PROMISE,
+ cleanPath,
+ createControlledPromise,
+ decode,
+ deepEqual,
+ defaultParseSearch,
+ defaultSerializeError,
+ defaultStringifySearch,
+ defer,
+ encode,
+ functionalUpdate,
+ interpolatePath,
+ isMatch,
+ isPlainArray,
+ isPlainObject,
+ joinPaths,
+ matchByPath,
+ matchPathname,
+ parsePathname,
+ parseSearchWith, // SSR
+ replaceEqualDeep,
+ resolvePath,
+ retainSearchParams,
+ rootRouteId,
+ stringifySearchWith,
+ stripSearchParams,
+ trimPath,
+ trimPathLeft,
+ trimPathRight,
+} from '@tanstack/router-core'
+
+export type {
+ AbsoluteToPath,
+ ActiveOptions,
+ AllContext,
+ AllLoaderData,
+ AllParams,
+ AnyContext,
+ AnyPathParams,
+ AnyRedirect,
+ AnyRoute,
+ AnyRouteMatch,
+ AnyRouteWithContext,
+ AnyRouter,
+ AnyRouterWithContext,
+ AnySchema,
+ AnyValidator,
+ AnyValidatorAdapter,
+ AnyValidatorFn,
+ AnyValidatorObj,
+ Assign,
+ BaseRouteOptions,
+ BeforeLoadContextOptions,
+ BeforeLoadContextParameter,
+ BuildLocationFn,
+ BuildNextOptions,
+ CommitLocationOptions,
+ Constrain,
+ ContextAsyncReturnType,
+ ContextOptions,
+ ContextReturnType,
+ ControllablePromise,
+ ControlledPromise,
+ DefaultValidator,
+ DeferredPromise,
+ DeferredPromiseState,
+ ErrorComponentProps,
+ ErrorRouteProps,
+ Expand,
+ FileBaseRouteOptions,
+ FileRouteTypes,
+ FileRoutesByPath,
+ FullSearchSchema,
+ FullSearchSchemaInput,
+ FullSearchSchemaOption,
+ InferAllContext,
+ InferAllParams,
+ InferDescendantToPaths,
+ InferFullSearchSchema,
+ InferFullSearchSchemaInput,
+ InjectedHtmlEntry,
+ IntersectAssign,
+ LazyRouteOptions,
+ LinkOptions,
+ ListenerFn,
+ LoaderFnContext,
+ LooseAsyncReturnType,
+ LooseReturnType,
+ MakeOptionalPathParams,
+ MakeRemountDepsOptionsUnion,
+ MakeRouteMatch,
+ MakeRouteMatchUnion,
+ Manifest,
+ MatchLocation,
+ MergeAll,
+ MetaDescriptor,
+ NavigateFn,
+ NavigateOptions,
+ NotFoundRouteProps,
+ ParamsOptions,
+ ParseParamsFn,
+ ParseRoute,
+ ParsedLocation,
+ PathParamOptions,
+ PreloadableObj,
+ Redirect,
+ Register,
+ RegisteredRouter,
+ RelativeToCurrentPath,
+ RelativeToParentPath,
+ RelativeToPath,
+ RelativeToPathAutoComplete,
+ RemountDepsOptions,
+ RemoveLeadingSlashes,
+ RemoveTrailingSlashes,
+ ResolveAllContext,
+ ResolveAllParamsFromParent,
+ ResolveFullPath,
+ ResolveFullSearchSchema,
+ ResolveFullSearchSchemaInput,
+ ResolveId,
+ ResolveLoaderData,
+ ResolveParams,
+ ResolveRelativePath,
+ ResolveRoute,
+ ResolveRouteContext,
+ ResolveSearchValidatorInput,
+ ResolveSearchValidatorInputFn,
+ ResolveValidatorInput,
+ ResolveValidatorInputFn,
+ ResolveValidatorOutput,
+ ResolveValidatorOutputFn,
+ ResolvedRedirect,
+ RootRouteId,
+ RootRouteOptions,
+ RouteById,
+ RouteByPath,
+ RouteConstraints,
+ RouteContext,
+ RouteContextFn,
+ RouteContextOptions,
+ RouteContextParameter,
+ RouteIds,
+ RouteLinkEntry,
+ RouteLoaderFn,
+ RouteMask,
+ RouteOptions,
+ RoutePathOptions,
+ RoutePathOptionsIntersection,
+ RoutePaths,
+ RouterConstructorOptions,
+ RouterContextOptions,
+ RouterEvent,
+ RouterEvents,
+ RouterListener,
+ RouterManagedTag,
+ RouterOptions,
+ RouterState,
+ RoutesById,
+ RoutesByPath,
+ SearchFilter,
+ SearchParamOptions,
+ SearchParser,
+ SearchSchemaInput,
+ SearchSerializer,
+ Segment,
+ StaticDataRouteOption,
+ StringifyParamsFn,
+ MatchRouteOptions as TanstackMatchRouteOptions,
+ RouteMatch as TanstackRouteMatch,
+ ToMaskOptions,
+ ToOptions,
+ ToPathOption,
+ ToSubOptions,
+ TrailingSlashOption,
+ TrimPath,
+ TrimPathLeft,
+ TrimPathRight,
+ UpdatableRouteOptions,
+ UpdatableStaticRouteOption,
+ UseNavigateResult,
+ Validator,
+ ValidatorAdapter,
+ ValidatorFn,
+ ValidatorObj,
+} from '@tanstack/router-core'
+
+export {
+ createBrowserHistory,
+ createHashHistory,
+ createHistory,
+ createMemoryHistory,
+} from '@tanstack/history'
+
+export type {
+ BlockerFn,
+ HistoryLocation,
+ HistoryState,
+ ParsedPath,
+ RouterHistory,
+} from '@tanstack/history'
+
+export { Link, linkOptions } from './link'
+export { MatchRoute, matchRoute, matchRoute$ } from './match-route'
+export type { MakeMatchRouteOptions, MatchRouteOptions } from './match-route'
+export {
+ Matches,
+ childMatches,
+ childMatches$,
+ matches,
+ matches$,
+ parentMatches,
+ parentMatches$,
+} from './matches'
+
+export { OnRendered, Outlet, RouteMatch } from './outlet'
+
+export { loaderData, loaderData$ } from './loader-data'
+export { loaderDeps, loaderDeps$ } from './loader-deps'
+export { match, match$ } from './match'
+
+export { isRedirect, redirect } from '@tanstack/router-core'
+
+export {
+ LazyRoute,
+ createFileRoute,
+ createLazyFileRoute,
+ createLazyRoute,
+} from './file-route'
+export {
+ ERROR_COMPONENT_CONTEXT,
+ NOT_FOUND_COMPONENT_CONTEXT,
+ NotFoundRoute,
+ RootRoute,
+ Route,
+ RouteApi,
+ createRootRoute,
+ createRootRouteWithContext,
+ createRoute,
+ routeApi,
+} from './route'
+
+export type { AnyRootRoute, RouteComponent } from './route'
+
+export {
+ NgRouter,
+ ROUTER,
+ ROUTER_STATE,
+ createRouter,
+ injectRouter,
+ injectRouterState,
+ provideRouter,
+} from './router'
+export * from './router-root'
+
+export {
+ PathParamError,
+ SearchParamError,
+ componentTypes,
+ getInitialRouterState,
+ lazyFn,
+} from '@tanstack/router-core'
+
+export { params, params$ } from './params'
+export { search, search$ } from './search'
+
+export { canGoBack, canGoBack$ } from './can-go-back'
+export { location, location$ } from './location'
+export { routeContext, routeContext$ } from './route-context'
+export { routerState, routerState$ } from './router-state'
+
+export { isNotFound, notFound } from '@tanstack/router-core'
+export type { NotFoundError } from '@tanstack/router-core'
+export { DefaultError } from './default-error'
+export { DefaultNotFound } from './default-not-found'
+
+export type { ValidateLinkOptions, ValidateLinkOptionsArray } from './link'
+
+export type {
+ InferFrom,
+ InferMaskFrom,
+ InferMaskTo,
+ InferSelected,
+ InferShouldThrow,
+ InferStrict,
+ InferTo,
+ ValidateFromPath,
+ ValidateId,
+ ValidateNavigateOptions,
+ ValidateNavigateOptionsArray,
+ ValidateParams,
+ ValidateRedirectOptions,
+ ValidateRedirectOptionsArray,
+ ValidateSearch,
+ ValidateToPath,
+ ValidateUseParamsResult,
+ ValidateUseSearchResult,
+} from '@tanstack/router-core'
+
+export * from './transitioner'
+export * from './is-dev-mode'
diff --git a/packages/angular-router/src/is-dev-mode.ts b/packages/angular-router/src/is-dev-mode.ts
new file mode 100644
index 0000000000..3af98e5c4c
--- /dev/null
+++ b/packages/angular-router/src/is-dev-mode.ts
@@ -0,0 +1,21 @@
+import { DOCUMENT } from '@angular/common'
+import {
+ Injector,
+ assertInInjectionContext,
+ inject,
+ runInInjectionContext,
+} from '@angular/core'
+
+export function isDevMode({ injector }: { injector?: Injector } = {}) {
+ !injector && assertInInjectionContext(isDevMode)
+
+ if (!injector) {
+ injector = inject(Injector)
+ }
+
+ return runInInjectionContext(injector, () => {
+ const document = inject(DOCUMENT)
+ const window = document.defaultView
+ return !!window && 'ng' in window
+ })
+}
diff --git a/packages/angular-router/src/link.ts b/packages/angular-router/src/link.ts
new file mode 100644
index 0000000000..edc987a055
--- /dev/null
+++ b/packages/angular-router/src/link.ts
@@ -0,0 +1,377 @@
+import {
+ Directive,
+ ElementRef,
+ afterRenderEffect,
+ computed,
+ inject,
+ input,
+ signal,
+ untracked,
+} from '@angular/core'
+import { toObservable, toSignal } from '@angular/core/rxjs-interop'
+import {
+ deepEqual,
+ exactPathTest,
+ preloadWarning,
+ removeTrailingSlash,
+} from '@tanstack/router-core'
+import { combineLatest, distinctUntilChanged, map } from 'rxjs'
+import { matches$ } from './matches'
+import { injectRouter } from './router'
+import { routerState, routerState$ } from './router-state'
+import { shallow } from './utils'
+
+import type {
+ AnyRouter,
+ Constrain,
+ InferFrom,
+ InferMaskFrom,
+ InferMaskTo,
+ InferTo,
+ LinkOptions,
+ RegisteredRouter,
+} from '@tanstack/router-core'
+
+@Directive({
+ selector: 'a[link]',
+ exportAs: 'link',
+ host: {
+ '(click)': 'handleClick($event)',
+ '(focus)': 'handleFocus()',
+ '(touchstart)': 'handleClick($event)',
+ '(mouseenter)': 'handleMouseEnter($event)',
+ '(mouseleave)': 'handleMouseLeave()',
+ '[class]': 'activeClass()',
+ '[attr.data-active]': 'isActive()',
+ '[attr.data-type]': 'type()',
+ '[attr.data-transitioning]':
+ 'transitioning() ? "transitioning" : undefined',
+ '[attr.href]': 'hostHref()',
+ '[attr.role]': 'disabled() ? "link" : undefined',
+ '[attr.aria-disabled]': 'disabled()',
+ '[attr.aria-current]': 'isActive() ? "page" : undefined',
+ '[attr.data-from]': 'from()',
+ },
+})
+export class Link {
+ linkOptions = input.required({
+ alias: 'link',
+ transform: (
+ value:
+ | (Omit & {
+ activeOptions?: LinkOptions['activeOptions'] & { class?: string }
+ })
+ | NonNullable,
+ ) => {
+ return (typeof value === 'object' ? value : { to: value }) as Omit<
+ LinkOptions,
+ 'activeOptions'
+ > & { activeOptions?: LinkOptions['activeOptions'] & { class?: string } }
+ },
+ })
+ linkActiveOptions = input(
+ { class: 'active' },
+ {
+ alias: 'linkActive',
+ transform: (
+ value: (LinkOptions['activeOptions'] & { class?: string }) | string,
+ ) => {
+ if (typeof value === 'string') return { class: value }
+
+ if (!value.class) value.class = 'active'
+ return value
+ },
+ },
+ )
+
+ private router = injectRouter()
+ hostElement = inject>(ElementRef)
+
+ private currentSearch = routerState({ select: (s) => s.location.searchStr })
+
+ protected disabled = computed(() => this.linkOptions()['disabled'])
+ private to = computed(() => this.linkOptions()['to'])
+ private userFrom = computed(() => this.linkOptions()['from'])
+ private userReloadDocument = computed(
+ () => this.linkOptions()['reloadDocument'],
+ )
+ private userPreload = computed(() => this.linkOptions()['preload'])
+ private userPreloadDelay = computed(() => this.linkOptions()['preloadDelay'])
+
+ private activeOptions = computed(
+ () => this.linkOptions().activeOptions || this.linkActiveOptions(),
+ )
+ private exactActiveOptions = computed(() => this.activeOptions().exact)
+ private includeHashActiveOptions = computed(
+ () => this.activeOptions().includeHash,
+ )
+ private includeSearchActiveOptions = computed(
+ () => this.activeOptions().includeSearch,
+ )
+
+ protected type = computed(() => {
+ const to = this.to()
+ try {
+ new URL(`${to}`)
+ return 'external'
+ } catch {
+ return 'internal'
+ }
+ })
+
+ // when `from` is not supplied, use the leaf route of the current matches as the `from` location
+ // so relative routing works as expected
+ protected from = toSignal(
+ combineLatest([
+ toObservable(this.userFrom),
+ matches$({ select: (matches) => matches[matches.length - 1]?.fullPath }),
+ ]).pipe(
+ map(([userFrom, from]) => userFrom ?? from),
+ distinctUntilChanged(shallow),
+ ),
+ )
+
+ private navigateOptions = computed(() => {
+ return { ...this.linkOptions(), from: this.from() }
+ })
+
+ private next = computed(() => {
+ const [options] = [this.navigateOptions(), this.currentSearch()]
+ try {
+ return this.router.buildLocation(options as any)
+ } catch {
+ return null
+ }
+ })
+
+ private preload = computed(() => {
+ const userReloadDocument = this.userReloadDocument()
+ if (userReloadDocument) return false
+ const userPreload = this.userPreload()
+ if (userPreload) return userPreload
+ return this.router.options.defaultPreload
+ })
+
+ private preloadDelay = computed(() => {
+ const userPreloadDelay = this.userPreloadDelay()
+ if (userPreloadDelay) return userPreloadDelay
+ return this.router.options.defaultPreloadDelay
+ })
+
+ protected hostHref = computed(() => {
+ const [type, to] = [this.type(), this.to()]
+ if (type === 'external') return to
+
+ const disabled = this.disabled()
+ if (disabled) return undefined
+
+ const next = this.next()
+ if (!next) return undefined
+
+ return next.maskedLocation
+ ? this.router.history.createHref(next.maskedLocation.href)
+ : this.router.history.createHref(next.href)
+ })
+
+ transitioning = signal(false)
+
+ isActive = toSignal(
+ combineLatest([
+ toObservable(this.next),
+ toObservable(this.exactActiveOptions),
+ toObservable(this.includeSearchActiveOptions),
+ toObservable(this.includeHashActiveOptions),
+ routerState$({ select: (s) => s.location }),
+ ]).pipe(
+ map(
+ ([next, exact, includeSearchOptions, includeHashOptions, location]) => {
+ if (!next) return false
+ if (exact) {
+ const testExact = exactPathTest(
+ location.pathname,
+ next.pathname,
+ this.router.basepath,
+ )
+ if (!testExact) return false
+ } else {
+ const currentPathSplit = removeTrailingSlash(
+ location.pathname,
+ this.router.basepath,
+ ).split('/')
+ const nextPathSplit = removeTrailingSlash(
+ next.pathname,
+ this.router.basepath,
+ ).split('/')
+ const pathIsFuzzyEqual = nextPathSplit.every(
+ (d, i) => d === currentPathSplit[i],
+ )
+ if (!pathIsFuzzyEqual) {
+ return false
+ }
+ }
+
+ const includeSearch = includeSearchOptions ?? true
+ if (includeSearch) {
+ const searchTest = deepEqual(location.search, next.search, {
+ partial: !exact,
+ ignoreUndefined: !(includeSearchOptions ?? true),
+ })
+ if (!searchTest) {
+ return false
+ }
+ }
+
+ const includeHash = includeHashOptions ?? true
+ if (includeHash) {
+ return location.hash === next.hash
+ }
+
+ return true
+ },
+ ),
+ ),
+ )
+ protected activeClass = computed(() =>
+ this.isActive() ? this.activeOptions().class || 'active' : '',
+ )
+
+ constructor() {
+ afterRenderEffect(() => {
+ const [disabled, preload] = [
+ untracked(this.disabled),
+ untracked(this.preload),
+ ]
+ if (!disabled && preload === 'render') {
+ this.doPreload()
+ }
+ })
+
+ afterRenderEffect((onCleanup) => {
+ const unsub = this.router.subscribe('onResolved', () => {
+ this.transitioning.set(false)
+ })
+ onCleanup(() => unsub())
+ })
+ }
+
+ protected handleClick(event: MouseEvent) {
+ if (this.type() === 'external') return
+
+ const [disabled, target] = [
+ this.disabled(),
+ this.hostElement.nativeElement.target,
+ ]
+
+ if (
+ disabled ||
+ this.isCtrlEvent(event) ||
+ event.defaultPrevented ||
+ (target && target !== '_self') ||
+ event.button !== 0
+ ) {
+ return
+ }
+
+ event.preventDefault()
+ this.transitioning.set(true)
+
+ this.router.navigate(this.navigateOptions() as any)
+ }
+
+ protected handleFocus() {
+ if (this.disabled() || this.type() === 'external') return
+ if (this.preload()) {
+ this.doPreload()
+ }
+ }
+
+ private preloadTimeout: ReturnType | null = null
+ protected handleMouseEnter() {
+ if (
+ this.disabled() ||
+ !this.preload() ||
+ this.isActive() ||
+ this.type() === 'external'
+ )
+ return
+
+ this.preloadTimeout = setTimeout(() => {
+ this.preloadTimeout = null
+ this.doPreload()
+ }, this.preloadDelay())
+ }
+
+ protected handleMouseLeave() {
+ if (this.disabled() || this.type() === 'external') return
+ if (this.preloadTimeout) {
+ clearTimeout(this.preloadTimeout)
+ this.preloadTimeout = null
+ }
+ }
+
+ private doPreload() {
+ this.router.preloadRoute(this.navigateOptions() as any).catch((err) => {
+ console.warn(err)
+ console.warn(preloadWarning)
+ })
+ }
+
+ private isCtrlEvent(e: MouseEvent) {
+ return e.metaKey || e.altKey || e.ctrlKey || e.shiftKey
+ }
+}
+
+export type ValidateLinkOptions<
+ TRouter extends AnyRouter = RegisteredRouter,
+ TOptions = unknown,
+ TDefaultFrom extends string = string,
+> = Constrain<
+ TOptions,
+ Omit<
+ LinkOptions<
+ TRouter,
+ InferFrom,
+ InferTo,
+ InferMaskFrom,
+ InferMaskTo
+ >,
+ 'activeOptions'
+ > &
+ Partial> & {
+ label?: string | (() => string)
+ activeOptions?: LinkOptions<
+ TRouter,
+ InferFrom,
+ InferTo,
+ InferMaskFrom,
+ InferMaskTo
+ >['activeOptions'] & { class?: string }
+ }
+>
+
+export type ValidateLinkOptionsArray<
+ TRouter extends AnyRouter = RegisteredRouter,
+ TOptions extends ReadonlyArray = ReadonlyArray,
+ TDefaultFrom extends string = string,
+> = {
+ [K in keyof TOptions]: ValidateLinkOptions
+}
+
+export type LinkOptionsFnOptions<
+ TOptions,
+ TRouter extends AnyRouter = RegisteredRouter,
+> =
+ TOptions extends ReadonlyArray
+ ? ValidateLinkOptionsArray
+ : ValidateLinkOptions
+
+export type LinkOptionsFn = <
+ const TOptions,
+ TRouter extends AnyRouter = RegisteredRouter,
+>(
+ options: LinkOptionsFnOptions,
+) => TOptions
+
+export const linkOptions: LinkOptionsFn = (options) => {
+ return options as any
+}
diff --git a/packages/angular-router/src/loader-data.ts b/packages/angular-router/src/loader-data.ts
new file mode 100644
index 0000000000..d7962f0b58
--- /dev/null
+++ b/packages/angular-router/src/loader-data.ts
@@ -0,0 +1,97 @@
+import {
+ Injector,
+ assertInInjectionContext,
+ inject,
+ runInInjectionContext,
+} from '@angular/core'
+import { toSignal } from '@angular/core/rxjs-interop'
+import { match$ } from './match'
+
+import type { Signal } from '@angular/core'
+import type {
+ AnyRouter,
+ RegisteredRouter,
+ ResolveUseLoaderData,
+ StrictOrFrom,
+ UseLoaderDataResult,
+} from '@tanstack/router-core'
+
+import type { Observable } from 'rxjs'
+
+export interface LoaderDataBaseOptions<
+ TRouter extends AnyRouter,
+ TFrom,
+ TStrict extends boolean,
+ TSelected,
+> {
+ select?: (match: ResolveUseLoaderData) => TSelected
+ injector?: Injector
+}
+
+export type LoaderDataOptions<
+ TRouter extends AnyRouter,
+ TFrom extends string | undefined,
+ TStrict extends boolean,
+ TSelected,
+> = StrictOrFrom &
+ LoaderDataBaseOptions
+
+export type LoaderDataRoute = <
+ TRouter extends AnyRouter = RegisteredRouter,
+ TSelected = unknown,
+>(
+ opts?: LoaderDataBaseOptions,
+) => TObservable extends true
+ ? Observable>
+ : Signal>
+
+export function loaderData$<
+ TRouter extends AnyRouter = RegisteredRouter,
+ const TFrom extends string | undefined = undefined,
+ TStrict extends boolean = true,
+ TSelected = unknown,
+>({
+ injector,
+ ...opts
+}: LoaderDataOptions): Observable<
+ UseLoaderDataResult
+> {
+ !injector && assertInInjectionContext(loaderData$)
+
+ if (!injector) {
+ injector = inject(Injector)
+ }
+
+ return runInInjectionContext(injector, () => {
+ return match$({
+ injector,
+ from: opts.from,
+ strict: opts.strict,
+ select: (s) => (opts.select ? opts.select(s.loaderData) : s.loaderData),
+ }) as any
+ })
+}
+
+export function loaderData<
+ TRouter extends AnyRouter = RegisteredRouter,
+ const TFrom extends string | undefined = undefined,
+ TStrict extends boolean = true,
+ TSelected = unknown,
+>({
+ injector,
+ ...opts
+}: LoaderDataOptions): Signal<
+ UseLoaderDataResult
+> {
+ !injector && assertInInjectionContext(loaderData)
+
+ if (!injector) {
+ injector = inject(Injector)
+ }
+
+ return runInInjectionContext(injector, () => {
+ return toSignal(loaderData$({ injector, ...opts } as unknown as any), {
+ injector,
+ })
+ }) as any
+}
diff --git a/packages/angular-router/src/loader-deps.ts b/packages/angular-router/src/loader-deps.ts
new file mode 100644
index 0000000000..d78ccc066e
--- /dev/null
+++ b/packages/angular-router/src/loader-deps.ts
@@ -0,0 +1,91 @@
+import {
+ Injector,
+ assertInInjectionContext,
+ inject,
+ runInInjectionContext,
+} from '@angular/core'
+import { toSignal } from '@angular/core/rxjs-interop'
+import { match$ } from './match'
+
+import type { Signal } from '@angular/core'
+import type {
+ AnyRouter,
+ RegisteredRouter,
+ ResolveUseLoaderDeps,
+ StrictOrFrom,
+ UseLoaderDepsResult,
+} from '@tanstack/router-core'
+import type { Observable } from 'rxjs'
+
+export interface LoaderDepsBaseOptions<
+ TRouter extends AnyRouter,
+ TFrom,
+ TSelected,
+> {
+ select?: (deps: ResolveUseLoaderDeps) => TSelected
+ injector?: Injector
+}
+
+export type LoaderDepsOptions<
+ TRouter extends AnyRouter,
+ TFrom extends string | undefined,
+ TSelected,
+> = StrictOrFrom &
+ LoaderDepsBaseOptions
+
+export type LoaderDepsRoute = <
+ TRouter extends AnyRouter = RegisteredRouter,
+ TSelected = unknown,
+>(
+ opts?: LoaderDepsBaseOptions,
+) => TObservable extends true
+ ? Observable>
+ : Signal>
+
+export function loaderDeps$<
+ TRouter extends AnyRouter = RegisteredRouter,
+ const TFrom extends string | undefined = undefined,
+ TSelected = unknown,
+>({
+ injector,
+ ...opts
+}: LoaderDepsOptions): Observable<
+ UseLoaderDepsResult
+> {
+ !injector && assertInInjectionContext(loaderDeps$)
+
+ if (!injector) {
+ injector = inject(Injector)
+ }
+
+ return runInInjectionContext(injector, () => {
+ const { select, ...rest } = opts
+ return match$({
+ ...rest,
+ select: (s) => {
+ return select ? select(s.loaderDeps) : s.loaderDeps
+ },
+ }) as Observable>
+ })
+}
+
+export function loaderDeps<
+ TRouter extends AnyRouter = RegisteredRouter,
+ const TFrom extends string | undefined = undefined,
+ TSelected = unknown,
+>({
+ injector,
+ ...opts
+}: LoaderDepsOptions): Signal<
+ UseLoaderDepsResult
+> {
+ !injector && assertInInjectionContext(loaderDeps)
+
+ if (!injector) {
+ injector = inject(Injector)
+ }
+
+ return runInInjectionContext(injector, () => {
+ return toSignal(loaderDeps$({ injector, ...opts }), { injector })
+ }) as any
+}
diff --git a/packages/angular-router/src/location.ts b/packages/angular-router/src/location.ts
new file mode 100644
index 0000000000..aff1fa9bdc
--- /dev/null
+++ b/packages/angular-router/src/location.ts
@@ -0,0 +1,70 @@
+import {
+ Injector,
+ assertInInjectionContext,
+ inject,
+ runInInjectionContext,
+} from '@angular/core'
+import { toSignal } from '@angular/core/rxjs-interop'
+import { routerState$ } from './router-state'
+
+import type { Signal } from '@angular/core'
+import type {
+ AnyRouter,
+ RegisteredRouter,
+ RouterState,
+} from '@tanstack/router-core'
+import type { Observable } from 'rxjs'
+
+export interface LocationBaseOptions {
+ select?: (state: RouterState['location']) => TSelected
+ injector?: Injector
+}
+
+export type LocationResult<
+ TRouter extends AnyRouter,
+ TSelected,
+> = unknown extends TSelected
+ ? RouterState['location']
+ : TSelected
+
+export function location$<
+ TRouter extends AnyRouter = RegisteredRouter,
+ TSelected = unknown,
+>({
+ injector,
+ select,
+}: LocationBaseOptions = {}): Observable<
+ LocationResult
+> {
+ !injector && assertInInjectionContext(location$)
+
+ if (!injector) {
+ injector = inject(Injector)
+ }
+
+ return runInInjectionContext(injector, () => {
+ return routerState$({
+ injector,
+ select: (state) => (select ? select(state.location) : state.location),
+ }) as Observable>
+ })
+}
+
+export function location<
+ TRouter extends AnyRouter = RegisteredRouter,
+ TSelected = unknown,
+>({ injector, select }: LocationBaseOptions = {}): Signal<
+ LocationResult
+> {
+ !injector && assertInInjectionContext(location)
+
+ if (!injector) {
+ injector = inject(Injector)
+ }
+
+ return runInInjectionContext(injector, () => {
+ return toSignal(location$({ injector, select })) as Signal<
+ LocationResult
+ >
+ })
+}
diff --git a/packages/angular-router/src/match-route.ts b/packages/angular-router/src/match-route.ts
new file mode 100644
index 0000000000..142932b7be
--- /dev/null
+++ b/packages/angular-router/src/match-route.ts
@@ -0,0 +1,133 @@
+import {
+ Directive,
+ Injector,
+ assertInInjectionContext,
+ computed,
+ inject,
+ input,
+ runInInjectionContext,
+} from '@angular/core'
+import { toObservable, toSignal } from '@angular/core/rxjs-interop'
+import { combineLatest, map, switchMap } from 'rxjs'
+import { Link } from './link'
+import { injectRouter } from './router'
+import { routerState$ } from './router-state'
+
+import type {
+ AnyRouter,
+ DeepPartial,
+ MakeOptionalPathParams,
+ MakeOptionalSearchParams,
+ MaskOptions,
+ RegisteredRouter,
+ MatchRouteOptions as TanstackMatchRouteOptions,
+ ToSubOptionsProps,
+} from '@tanstack/router-core'
+
+export type MatchRouteOptions<
+ TRouter extends AnyRouter = RegisteredRouter,
+ TFrom extends string = string,
+ TTo extends string | undefined = undefined,
+ TMaskFrom extends string = TFrom,
+ TMaskTo extends string = '',
+> = ToSubOptionsProps &
+ DeepPartial> &
+ DeepPartial> &
+ MaskOptions &
+ TanstackMatchRouteOptions & { injector?: Injector }
+
+export function matchRoute$({
+ injector,
+}: { injector?: Injector } = {}) {
+ !injector && assertInInjectionContext(matchRoute$)
+
+ if (!injector) {
+ injector = inject(Injector)
+ }
+
+ return runInInjectionContext(injector, () => {
+ const router = injectRouter()
+ const status$ = routerState$({ select: (s) => s.status })
+
+ return <
+ const TFrom extends string = string,
+ const TTo extends string | undefined = undefined,
+ const TMaskFrom extends string = TFrom,
+ const TMaskTo extends string = '',
+ >(
+ opts: MatchRouteOptions,
+ ) => {
+ const { pending, caseSensitive, fuzzy, includeSearch, ...rest } = opts
+ return status$.pipe(
+ map(() =>
+ router.matchRoute(rest as any, {
+ pending,
+ caseSensitive,
+ fuzzy,
+ includeSearch,
+ }),
+ ),
+ )
+ }
+ })
+}
+
+export function matchRoute({
+ injector,
+}: { injector?: Injector } = {}) {
+ !injector && assertInInjectionContext(matchRoute)
+
+ if (!injector) {
+ injector = inject(Injector)
+ }
+
+ return runInInjectionContext(injector, () => {
+ const matchRoute$Return = matchRoute$({ injector })
+ return <
+ const TFrom extends string = string,
+ const TTo extends string | undefined = undefined,
+ const TMaskFrom extends string = TFrom,
+ const TMaskTo extends string = '',
+ >(
+ opts: MatchRouteOptions,
+ ) => {
+ return toSignal(matchRoute$Return(opts as any), { injector })
+ }
+ })
+}
+
+export type MakeMatchRouteOptions<
+ TRouter extends AnyRouter = RegisteredRouter,
+ TFrom extends string = string,
+ TTo extends string | undefined = undefined,
+ TMaskFrom extends string = TFrom,
+ TMaskTo extends string = '',
+> = MatchRouteOptions
+
+@Directive({ selector: '[match]', exportAs: 'matchRoute' })
+export class MatchRoute<
+ TRouter extends AnyRouter = RegisteredRouter,
+ const TFrom extends string = string,
+ const TTo extends string | undefined = undefined,
+ const TMaskFrom extends string = TFrom,
+ const TMaskTo extends string = '',
+> {
+ matchRoute = input<
+ Partial>
+ >({}, { alias: 'match' })
+
+ private status$ = routerState$({ select: (s) => s.status })
+ private matchRouteFn = matchRoute$()
+
+ private parentLink = inject(Link, { optional: true })
+ private options = computed(() => {
+ const parentLinkOptions = this.parentLink?.linkOptions()
+ if (!parentLinkOptions) return this.matchRoute()
+ return { ...parentLinkOptions, ...this.matchRoute() }
+ })
+
+ match$ = combineLatest([toObservable(this.options), this.status$]).pipe(
+ switchMap(([matchRoute]) => this.matchRouteFn(matchRoute as any)),
+ )
+ match = toSignal(this.match$)
+}
diff --git a/packages/angular-router/src/match.ts b/packages/angular-router/src/match.ts
new file mode 100644
index 0000000000..b7868bcd1d
--- /dev/null
+++ b/packages/angular-router/src/match.ts
@@ -0,0 +1,153 @@
+import {
+ Injector,
+ assertInInjectionContext,
+ computed,
+ inject,
+ runInInjectionContext,
+} from '@angular/core'
+import { toObservable, toSignal } from '@angular/core/rxjs-interop'
+import { combineLatest, distinctUntilChanged, map } from 'rxjs'
+import invariant from 'tiny-invariant'
+import { shallow } from './utils'
+import { MATCH_ID } from './outlet'
+import { routerState$ } from './router-state'
+
+import type {
+ AnyRouter,
+ MakeRouteMatch,
+ MakeRouteMatchUnion,
+ RegisteredRouter,
+ StrictOrFrom,
+ ThrowConstraint,
+ ThrowOrOptional,
+} from '@tanstack/router-core'
+import type { Observable } from 'rxjs'
+import type { Signal } from '@angular/core'
+
+export interface MatchBaseOptions<
+ TRouter extends AnyRouter,
+ TFrom,
+ TStrict extends boolean,
+ TThrow extends boolean,
+ TSelected,
+> {
+ select?: (
+ match: MakeRouteMatch,
+ ) => TSelected
+ shouldThrow?: TThrow
+ injector?: Injector
+}
+
+export type MatchRoute = <
+ TRouter extends AnyRouter = RegisteredRouter,
+ TSelected = unknown,
+>(
+ opts?: MatchBaseOptions,
+) => TObservable extends true
+ ? Observable>
+ : Signal>
+
+export type MatchOptions<
+ TRouter extends AnyRouter,
+ TFrom extends string | undefined,
+ TStrict extends boolean,
+ TThrow extends boolean,
+ TSelected,
+> = StrictOrFrom &
+ MatchBaseOptions
+
+export type MatchResult<
+ TRouter extends AnyRouter,
+ TFrom,
+ TStrict extends boolean,
+ TSelected,
+> = unknown extends TSelected
+ ? TStrict extends true
+ ? MakeRouteMatch
+ : MakeRouteMatchUnion
+ : TSelected
+
+export function match$<
+ TRouter extends AnyRouter = RegisteredRouter,
+ const TFrom extends string | undefined = undefined,
+ TStrict extends boolean = true,
+ TThrow extends boolean = true,
+ TSelected = unknown,
+>({
+ injector,
+ ...opts
+}: MatchOptions<
+ TRouter,
+ TFrom,
+ TStrict,
+ ThrowConstraint,
+ TSelected
+>): Observable<
+ ThrowOrOptional, TThrow>
+> {
+ !injector && assertInInjectionContext(match$)
+
+ if (!injector) {
+ injector = inject(Injector)
+ }
+
+ return runInInjectionContext(injector, () => {
+ const closestMatchId = inject(MATCH_ID, { optional: true })
+ const nearestMatchId = computed(() => {
+ if (opts.from) return null
+ return closestMatchId
+ })
+
+ return combineLatest([
+ routerState$({ select: (s) => s.matches, injector }),
+ toObservable(nearestMatchId),
+ ]).pipe(
+ map(([matches, matchId]) => {
+ const match = matches.find((d) => {
+ return opts.from ? opts.from === d.routeId : d.id === matchId
+ })
+ invariant(
+ !((opts.shouldThrow ?? true) && !match),
+ `Could not find ${opts.from ? `an active match from "${opts.from}"` : 'a nearest match!'}`,
+ )
+ if (match === undefined) {
+ return undefined
+ }
+
+ return opts.select ? opts.select(match) : match
+ }),
+ distinctUntilChanged(shallow),
+ ) as any
+ })
+}
+
+export function match<
+ TRouter extends AnyRouter = RegisteredRouter,
+ const TFrom extends string | undefined = undefined,
+ TStrict extends boolean = true,
+ TThrow extends boolean = true,
+ TSelected = unknown,
+>({
+ injector,
+ ...opts
+}: MatchOptions<
+ TRouter,
+ TFrom,
+ TStrict,
+ ThrowConstraint,
+ TSelected
+>): Signal<
+ ThrowOrOptional, TThrow>
+> {
+ !injector && assertInInjectionContext(match)
+
+ if (!injector) {
+ injector = inject(Injector)
+ }
+
+ return runInInjectionContext(injector, () => {
+ return toSignal(match$({ injector, ...opts } as unknown as any), {
+ injector,
+ })
+ }) as any
+}
diff --git a/packages/angular-router/src/matches.ts b/packages/angular-router/src/matches.ts
new file mode 100644
index 0000000000..3b67785f83
--- /dev/null
+++ b/packages/angular-router/src/matches.ts
@@ -0,0 +1,286 @@
+import {
+ DestroyRef,
+ Directive,
+ Injector,
+ ViewContainerRef,
+ afterNextRender,
+ assertInInjectionContext,
+ inject,
+ runInInjectionContext,
+} from '@angular/core'
+import { toSignal } from '@angular/core/rxjs-interop'
+import { combineLatest, distinctUntilChanged, map, of, switchMap } from 'rxjs'
+import { shallow } from './utils'
+import { DefaultError } from './default-error'
+import { MATCH_ID, RouteMatch } from './outlet'
+import { ERROR_COMPONENT_CONTEXT } from './route'
+import { injectRouter } from './router'
+import { routerState$ } from './router-state'
+import { Transitioner } from './transitioner'
+
+import type {
+ AnyRouter,
+ MakeRouteMatchUnion,
+ RegisteredRouter,
+ RouterState,
+} from '@tanstack/router-core'
+import type { Observable, Subscription } from 'rxjs'
+import type { ComponentRef, Signal } from '@angular/core'
+
+@Directive({ hostDirectives: [Transitioner] })
+export class Matches {
+ private router = injectRouter()
+ private injector = inject(Injector)
+ private vcr = inject(ViewContainerRef)
+
+ private defaultPendingComponent =
+ this.router.options.defaultPendingComponent?.()
+
+ private resetKey$ = routerState$({ select: (s) => s.loadedAt.toString() })
+ private rootMatchId$ = routerState$({ select: (s) => s.matches[0]?.id })
+
+ private matchLoad$ = this.rootMatchId$.pipe(
+ switchMap((rootMatchId) => {
+ if (!rootMatchId) return of({ pending: false })
+ const loadPromise = this.router.getMatch(rootMatchId)?._nonReactive.loadPromise;
+ if (!loadPromise) return of({ pending: false })
+ return of({ pending: true }).pipe(
+ switchMap(() => loadPromise.then(() => ({ pending: false }))),
+ )
+ }),
+ )
+
+ private cmpRef?: ComponentRef
+
+ private run$ = this.matchLoad$.pipe(
+ switchMap(({ pending }) => {
+ if (pending) {
+ if (this.defaultPendingComponent) {
+ return of({
+ component: this.defaultPendingComponent,
+ clearView: true,
+ matchId: null,
+ } as const)
+ }
+ return of(null)
+ }
+
+ return combineLatest([this.rootMatchId$, this.resetKey$]).pipe(
+ map(([matchId]) => {
+ if (!matchId) return null
+ if (this.cmpRef) return { clearView: false } as const
+ return {
+ component: RouteMatch,
+ matchId,
+ clearView: true,
+ } as const
+ }),
+ )
+ }),
+ )
+
+ constructor() {
+ let subscription: Subscription
+ afterNextRender(() => {
+ subscription = this.run$.subscribe({
+ next: (runData) => {
+ if (!runData) return
+ if (!runData.clearView) {
+ this.cmpRef?.changeDetectorRef.markForCheck()
+ return
+ }
+ const { component, matchId } = runData
+ this.vcr.clear()
+ this.cmpRef = this.vcr.createComponent(component)
+ if (matchId) {
+ this.cmpRef.setInput('matchId', matchId)
+ }
+ this.cmpRef.changeDetectorRef.markForCheck()
+ },
+ error: (error) => {
+ console.error(error)
+ const injector = Injector.create({
+ providers: [
+ {
+ provide: ERROR_COMPONENT_CONTEXT,
+ useValue: {
+ error: error,
+ info: { componentStack: '' },
+ reset: () => void this.router.invalidate(),
+ },
+ },
+ ],
+ parent: this.injector,
+ })
+ this.vcr.clear()
+ const ref = this.vcr.createComponent(DefaultError, { injector })
+ ref.changeDetectorRef.markForCheck()
+ this.cmpRef = undefined
+ },
+ })
+ })
+
+ inject(DestroyRef).onDestroy(() => {
+ subscription.unsubscribe()
+ this.vcr.clear()
+ this.cmpRef = undefined
+ })
+ }
+}
+
+export interface MatchesBaseOptions {
+ select?: (matches: Array>) => TSelected
+ injector?: Injector
+}
+
+export type MatchesResult<
+ TRouter extends AnyRouter,
+ TSelected,
+> = unknown extends TSelected ? Array> : TSelected
+
+export function matches$<
+ TRouter extends AnyRouter = RegisteredRouter,
+ TSelected = unknown,
+>({
+ injector,
+ ...opts
+}: MatchesBaseOptions = {}): Observable<
+ MatchesResult
+> {
+ !injector && assertInInjectionContext(matches$)
+
+ if (!injector) {
+ injector = inject(Injector)
+ }
+
+ return runInInjectionContext(injector, () => {
+ return routerState$({
+ injector,
+ select: (state: RouterState) => {
+ const matches = state.matches
+ return opts.select
+ ? opts.select(matches as Array>)
+ : matches
+ },
+ }) as Observable>
+ })
+}
+
+export function matches<
+ TRouter extends AnyRouter = RegisteredRouter,
+ TSelected = unknown,
+>({ injector, ...opts }: MatchesBaseOptions = {}): Signal<
+ MatchesResult
+> {
+ !injector && assertInInjectionContext(matches)
+
+ if (!injector) {
+ injector = inject(Injector)
+ }
+
+ return runInInjectionContext(injector, () => {
+ return toSignal(matches$({ injector, ...opts })) as Signal<
+ MatchesResult
+ >
+ })
+}
+
+export function parentMatches$<
+ TRouter extends AnyRouter = RegisteredRouter,
+ TSelected = unknown,
+>({
+ injector,
+ ...opts
+}: MatchesBaseOptions = {}): Observable<
+ MatchesResult
+> {
+ !injector && assertInInjectionContext(parentMatches$)
+
+ if (!injector) {
+ injector = inject(Injector)
+ }
+
+ return runInInjectionContext(injector, () => {
+ const closestMatch = inject(MATCH_ID)
+ return routerState$({ injector, select: (s) => s.matches }).pipe(
+ map((matches) => {
+ const sliced = matches.slice(
+ 0,
+ matches.findIndex((d) => d.id === closestMatch),
+ )
+ return opts.select
+ ? opts.select(sliced as Array>)
+ : sliced
+ }),
+ distinctUntilChanged(shallow) as any,
+ )
+ })
+}
+
+export function parentMatches<
+ TRouter extends AnyRouter = RegisteredRouter,
+ TSelected = unknown,
+>({ injector, ...opts }: MatchesBaseOptions = {}): Signal<
+ MatchesResult
+> {
+ !injector && assertInInjectionContext(parentMatches)
+
+ if (!injector) {
+ injector = inject(Injector)
+ }
+
+ return runInInjectionContext(injector, () => {
+ return toSignal(parentMatches$({ injector, ...opts })) as Signal<
+ MatchesResult
+ >
+ })
+}
+export function childMatches$<
+ TRouter extends AnyRouter = RegisteredRouter,
+ TSelected = unknown,
+>({
+ injector,
+ ...opts
+}: MatchesBaseOptions = {}): Observable<
+ MatchesResult
+> {
+ !injector && assertInInjectionContext(childMatches$)
+
+ if (!injector) {
+ injector = inject(Injector)
+ }
+
+ return runInInjectionContext(injector, () => {
+ const closestMatch = inject(MATCH_ID)
+ return routerState$({ injector, select: (s) => s.matches }).pipe(
+ map((matches) => {
+ const sliced = matches.slice(
+ matches.findIndex((d) => d.id === closestMatch) + 1,
+ )
+ return opts.select
+ ? opts.select(sliced as Array>)
+ : sliced
+ }),
+ distinctUntilChanged(shallow) as any,
+ )
+ })
+}
+
+export function childMatches<
+ TRouter extends AnyRouter = RegisteredRouter,
+ TSelected = unknown,
+>({ injector, ...opts }: MatchesBaseOptions = {}): Signal<
+ MatchesResult
+> {
+ !injector && assertInInjectionContext(childMatches)
+
+ if (!injector) {
+ injector = inject(Injector)
+ }
+
+ return runInInjectionContext(injector, () => {
+ return toSignal(childMatches$({ injector, ...opts })) as Signal<
+ MatchesResult
+ >
+ })
+}
diff --git a/packages/angular-router/src/outlet.ts b/packages/angular-router/src/outlet.ts
new file mode 100644
index 0000000000..876a32b190
--- /dev/null
+++ b/packages/angular-router/src/outlet.ts
@@ -0,0 +1,547 @@
+import {
+ ChangeDetectionStrategy,
+ Component,
+ DestroyRef,
+ Directive,
+ EnvironmentInjector,
+ InjectionToken,
+ Injector,
+ ViewContainerRef,
+ afterNextRender,
+ inject,
+ input,
+} from '@angular/core'
+import { toObservable } from '@angular/core/rxjs-interop'
+import {
+ createControlledPromise,
+ getLocationChangeInfo,
+ isNotFound,
+ isRedirect,
+ rootRouteId,
+} from '@tanstack/router-core'
+import {
+ catchError,
+ combineLatest,
+ distinctUntilChanged,
+ filter,
+ map,
+ of,
+ switchMap,
+ take,
+ throwError,
+ withLatestFrom,
+} from 'rxjs'
+import invariant from 'tiny-invariant'
+import warning from 'tiny-warning'
+import { DefaultError } from './default-error'
+import { DefaultNotFound } from './default-not-found'
+import { isDevMode } from './is-dev-mode'
+import { ERROR_COMPONENT_CONTEXT, NOT_FOUND_COMPONENT_CONTEXT } from './route'
+import { injectRouter } from './router'
+import { routerState$ } from './router-state'
+import { pick, shallow } from './utils'
+
+import type { ComponentRef, Type } from '@angular/core'
+import type { Subscription } from 'rxjs'
+
+@Directive()
+export class OnRendered {
+ private match = inject(RouteMatch)
+ private router = injectRouter()
+
+ private parentRouteId$ = combineLatest([
+ this.match.matchId$,
+ routerState$({ select: (s) => s.matches }),
+ ]).pipe(
+ map(
+ ([matchId, matches]) =>
+ matches.find((d) => d.id === matchId)?.routeId as string,
+ ),
+ distinctUntilChanged(shallow),
+ )
+ private location$ = routerState$({
+ select: (s) => s.resolvedLocation?.state.key,
+ })
+
+ constructor() {
+ let subscription: Subscription | undefined = undefined
+ afterNextRender(() => {
+ subscription = combineLatest([
+ this.parentRouteId$,
+ this.location$,
+ ]).subscribe(([parentRouteId]) => {
+ if (!parentRouteId || parentRouteId !== rootRouteId) return
+ this.router.emit({
+ type: 'onRendered',
+ ...getLocationChangeInfo(this.router.state),
+ })
+ })
+ })
+
+ inject(DestroyRef).onDestroy(() => {
+ subscription?.unsubscribe()
+ })
+ }
+}
+
+export const MATCH_ID = new InjectionToken('MATCH_ID')
+
+@Component({
+ selector: 'route-match,RouteMatch',
+ template: ``,
+ hostDirectives: [OnRendered],
+ changeDetection: ChangeDetectionStrategy.OnPush,
+ host: {
+ '[attr.data-matchId]': 'matchId()',
+ },
+})
+export class RouteMatch {
+ matchId = input.required()
+
+ private isDevMode = isDevMode()
+ private router = injectRouter()
+ private vcr = inject(ViewContainerRef)
+ private injector = inject(Injector)
+ private environmentInjector = inject(EnvironmentInjector)
+
+ matchId$ = toObservable(this.matchId)
+ private resetKey$ = routerState$({ select: (s) => s.loadedAt.toString() })
+ private matches$ = routerState$({ select: (s) => s.matches })
+ private routeId$ = combineLatest([this.matchId$, this.matches$]).pipe(
+ map(
+ ([matchId, matches]) =>
+ matches.find((d) => d.id === matchId)?.routeId as string,
+ ),
+ distinctUntilChanged(shallow),
+ )
+
+ private route$ = this.routeId$.pipe(
+ map((routeId) => this.router.routesById[routeId]),
+ distinctUntilChanged(shallow),
+ )
+ private pendingComponent$ = this.route$.pipe(
+ map(
+ (route) =>
+ route.options.pendingComponent ||
+ this.router.options.defaultPendingComponent,
+ ),
+ distinctUntilChanged(shallow),
+ )
+ private errorComponent$ = this.route$.pipe(
+ map(
+ (route) =>
+ route.options.errorComponent ||
+ this.router.options.defaultErrorComponent,
+ ),
+ distinctUntilChanged(shallow),
+ )
+ private onCatch$ = this.route$.pipe(
+ map((route) => route.options.onCatch || this.router.options.defaultOnCatch),
+ distinctUntilChanged(shallow),
+ )
+
+ private matchIndex$ = combineLatest([this.matchId$, this.matches$]).pipe(
+ map(([matchId, matches]) => matches.findIndex((d) => d.id === matchId)),
+ distinctUntilChanged(shallow),
+ )
+ private matchState$ = combineLatest([this.matchIndex$, this.matches$]).pipe(
+ map(([matchIndex, matches]) => matches[matchIndex]),
+ filter((match) => !!match),
+ map((match) => ({
+ routeId: match.routeId as string,
+ match: pick(match, ['id', 'status', 'error']),
+ })),
+ )
+
+ private matchRoute$ = this.matchState$.pipe(
+ map(({ routeId }) => this.router.routesById[routeId]),
+ distinctUntilChanged(shallow),
+ )
+ private match$ = this.matchState$.pipe(
+ map(({ match }) => match),
+ distinctUntilChanged((a, b) => a.id === b.id && a.status === b.status),
+ )
+ private matchLoad$ = this.match$.pipe(
+ withLatestFrom(this.matchRoute$),
+ switchMap(([match, matchRoute]) => {
+ const loadPromise = this.router.getMatch(match.id)?._nonReactive.loadPromise
+ if (!loadPromise) return Promise.resolve() as any
+
+ if (match.status === 'pending') {
+ const pendingMinMs =
+ matchRoute.options.pendingMinMs ??
+ this.router.options.defaultPendingMinMs
+ let minPendingPromise = this.router.getMatch(
+ match.id,
+ )?._nonReactive.minPendingPromise
+
+ if (pendingMinMs && !minPendingPromise) {
+ // Create a promise that will resolve after the minPendingMs
+ if (!this.router.isServer) {
+ minPendingPromise = createControlledPromise()
+ Promise.resolve().then(() => {
+ this.router.updateMatch(match.id, (prev) => ({
+ ...prev,
+ minPendingPromise,
+ }))
+ })
+
+ setTimeout(() => {
+ minPendingPromise?.resolve()
+ // We've handled the minPendingPromise, so we can delete it
+ this.router.updateMatch(match.id, (prev) => ({
+ ...prev,
+ minPendingPromise: undefined,
+ }))
+ }, pendingMinMs)
+ }
+ }
+
+ return minPendingPromise?.then(() => loadPromise) || loadPromise
+ }
+
+ return loadPromise
+ }),
+ distinctUntilChanged(shallow),
+ )
+
+ private run$ = this.routeId$.pipe(
+ switchMap((routeId) => {
+ invariant(
+ routeId,
+ `Could not find routeId for matchId "${this.matchId()}". Please file an issue!`,
+ )
+ return combineLatest([
+ this.match$,
+ this.matchRoute$,
+ this.resetKey$,
+ ]).pipe(
+ switchMap(([match, route]) => {
+ if (match.status === 'notFound') {
+ invariant(isNotFound(match.error), 'Expected a notFound error')
+ let notFoundCmp: Type | undefined
+ if (!route.options.notFoundComponent) {
+ notFoundCmp = this.router.options.defaultNotFoundComponent?.()
+ if (!notFoundCmp) {
+ if (this.isDevMode) {
+ warning(
+ route.options.notFoundComponent,
+ `A notFoundError was encountered on the route with ID "${route.id}", but a notFoundComponent option was not configured, nor was a router level defaultNotFoundComponent configured. Consider configuring at least one of these to avoid TanStack Router's overly generic defaultNotFoundComponent (Page not found
)`,
+ )
+ }
+ notFoundCmp = DefaultNotFound
+ }
+ } else {
+ notFoundCmp = route.options.notFoundComponent()
+ }
+
+ const injector = this.router.getRouteInjector(
+ route.id + '-not-found',
+ this.injector,
+ [{ provide: NOT_FOUND_COMPONENT_CONTEXT, useValue: {} }],
+ )
+ return of({
+ component: notFoundCmp,
+ injector,
+ environmentInjector: null,
+ clearView: true,
+ } as const)
+ }
+
+ if (match.status === 'redirected' || match.status === 'pending') {
+ if (match.status === 'redirected') {
+ invariant(isRedirect(match.error), 'Expected a redirect error')
+ }
+
+ return this.matchLoad$.pipe(
+ withLatestFrom(this.pendingComponent$),
+ switchMap(([, pendingComponent]) => {
+ const pendingCmp = pendingComponent?.()
+ if (!pendingCmp) return of(null)
+ return of({
+ component: pendingCmp,
+ injector: null,
+ environmentInjector: null,
+ clearView: true,
+ } as const)
+ }),
+ )
+ }
+
+ if (match.status === 'error') {
+ return this.errorComponent$.pipe(
+ take(1),
+ switchMap((errorComponent) => {
+ const errorCmp = errorComponent?.() || DefaultError
+ const injector = this.router.getRouteInjector(
+ route.id + '-error',
+ this.injector,
+ [
+ {
+ provide: ERROR_COMPONENT_CONTEXT,
+ useValue: {
+ error: match.error,
+ info: { componentStack: '' },
+ reset: () => void this.router.invalidate(),
+ },
+ },
+ ],
+ )
+ return of({
+ component: errorCmp,
+ injector,
+ environmentInjector: null,
+ clearView: true,
+ } as const)
+ }),
+ )
+ }
+
+ const successComponent = route.options.component?.() || Outlet
+
+ if (this.cmp === successComponent) {
+ return of({ clearView: false } as const)
+ }
+
+ this.cmpRef = undefined
+ this.cmp = successComponent
+ const injector = this.router.getRouteInjector(route.id, this.injector)
+ const environmentInjector = this.router.getRouteEnvInjector(
+ route.id,
+ this.environmentInjector,
+ route.options.providers || [],
+ this.router,
+ )
+
+ return of({
+ component: successComponent,
+ injector: Injector.create({
+ providers: [{ provide: MATCH_ID, useValue: match.id }],
+ parent: injector,
+ }),
+ environmentInjector,
+ clearView: true,
+ } as const)
+ }),
+ )
+ }),
+ catchError((error) =>
+ this.onCatch$.pipe(
+ take(1),
+ switchMap((onCatch) => throwError(() => [error, onCatch])),
+ ),
+ ),
+ )
+
+ private cmp?: Type
+ private cmpRef?: ComponentRef
+
+ constructor() {
+ let subscription: Subscription | undefined = undefined
+
+ afterNextRender(() => {
+ subscription = this.run$.subscribe({
+ next: (runData) => {
+ if (!runData) return
+ if (!runData.clearView) {
+ this.cmpRef?.changeDetectorRef.markForCheck()
+ return
+ }
+ const { component, injector, environmentInjector } = runData
+ this.vcr.clear()
+
+ this.cmpRef = this.vcr.createComponent(component, {
+ injector: injector || undefined,
+ environmentInjector: environmentInjector || undefined,
+ })
+ this.cmpRef.changeDetectorRef.markForCheck()
+ },
+ error: (error) => {
+ if (Array.isArray(error)) {
+ const [errorToThrow, onCatch] = error
+ if (onCatch) onCatch(errorToThrow)
+ console.error(errorToThrow)
+ return
+ }
+ console.error(error)
+ },
+ })
+ })
+
+ inject(DestroyRef).onDestroy(() => {
+ subscription?.unsubscribe()
+ this.vcr.clear()
+ this.cmp = undefined
+ this.cmpRef = undefined
+ })
+ }
+}
+
+@Component({
+ selector: 'outlet,Outlet',
+ template: ``,
+ changeDetection: ChangeDetectionStrategy.OnPush,
+})
+export class Outlet {
+ private matchId = inject(MATCH_ID)
+ private router = injectRouter()
+ private vcr = inject(ViewContainerRef)
+ private isDevMode = isDevMode()
+
+ protected readonly defaultPendingComponent =
+ this.router.options.defaultPendingComponent?.()
+
+ private matches$ = routerState$({ select: (s) => s.matches })
+ private routeId$ = this.matches$.pipe(
+ map(
+ (matches) =>
+ matches.find((d) => d.id === this.matchId)?.routeId as string,
+ ),
+ distinctUntilChanged(shallow),
+ )
+ private route$ = this.routeId$.pipe(
+ map((routeId) => this.router.routesById[routeId]),
+ distinctUntilChanged(shallow),
+ )
+ private parentGlobalNotFound$ = this.matches$.pipe(
+ map((matches) => {
+ const parentMatch = matches.find((d) => d.id === this.matchId)
+ if (!parentMatch) {
+ warning(
+ false,
+ `Could not find parent match for matchId "${this.matchId}". Please file an issue!`,
+ )
+ return false
+ }
+ return parentMatch.globalNotFound
+ }),
+ )
+
+ private childMatchId$ = this.matches$.pipe(
+ map((matches) => {
+ const index = matches.findIndex((d) => d.id === this.matchId)
+ if (index === -1) return null
+ return matches[index + 1]?.id
+ }),
+ distinctUntilChanged(shallow),
+ )
+ private matchLoad$ = this.childMatchId$.pipe(
+ switchMap((childMatchId) => {
+ if (!childMatchId) return Promise.resolve() as any
+ const loadPromise = this.router.getMatch(childMatchId)?._nonReactive.loadPromise
+ if (!loadPromise) return Promise.resolve() as any
+ return loadPromise
+ }),
+ )
+
+ private renderedId?: string
+ private cmpRef?: ComponentRef
+
+ private run$ = combineLatest([
+ this.parentGlobalNotFound$,
+ this.childMatchId$,
+ ]).pipe(
+ switchMap(([parentGlobalNotFound, childMatchId]) => {
+ if (parentGlobalNotFound) {
+ return this.route$.pipe(
+ map((route) => {
+ let notFoundCmp: Type | undefined = undefined
+
+ if (!route.options.notFoundComponent) {
+ notFoundCmp = this.router.options.defaultNotFoundComponent?.()
+ if (!notFoundCmp) {
+ if (this.isDevMode) {
+ warning(
+ route.options.notFoundComponent,
+ `A notFoundError was encountered on the route with ID "${route.id}", but a notFoundComponent option was not configured, nor was a router level defaultNotFoundComponent configured. Consider configuring at least one of these to avoid TanStack Router's overly generic defaultNotFoundComponent (Page not found
)`,
+ )
+ }
+ notFoundCmp = DefaultNotFound
+ }
+ } else {
+ notFoundCmp = route.options.notFoundComponent()
+ }
+
+ this.renderedId = route.id + '-not-found'
+ const injector = this.router.getRouteInjector(
+ route.id + '-not-found',
+ this.vcr.injector,
+ [{ provide: NOT_FOUND_COMPONENT_CONTEXT, useValue: {} }],
+ )
+ return {
+ component: notFoundCmp,
+ injector,
+ clearView: true,
+ childMatchId: null,
+ } as const
+ }),
+ )
+ }
+
+ if (!childMatchId) return of(null)
+
+ if (this.renderedId === childMatchId) {
+ return of({ clearView: false } as const)
+ }
+
+ this.cmpRef = undefined
+
+ if (childMatchId === rootRouteId) {
+ return this.matchLoad$.pipe(
+ map(() => {
+ return {
+ component: this.defaultPendingComponent,
+ injector: null,
+ clearView: true,
+ childMatchId: null,
+ } as const
+ }),
+ )
+ }
+
+ this.renderedId = childMatchId
+ return of({
+ component: RouteMatch,
+ injector: null,
+ clearView: true,
+ childMatchId,
+ } as const)
+ }),
+ catchError((error) => throwError(() => error)),
+ )
+
+ constructor() {
+ let subscription: Subscription | undefined = undefined
+ afterNextRender(() => {
+ subscription = this.run$.subscribe({
+ next: (runData) => {
+ if (!runData) return
+ if (!runData.clearView) {
+ this.cmpRef?.changeDetectorRef.markForCheck()
+ return
+ }
+ const { component, injector, childMatchId } = runData
+ this.vcr.clear()
+ if (!component) return
+ this.cmpRef = this.vcr.createComponent(component, {
+ injector: injector || undefined,
+ })
+ if (childMatchId) {
+ this.cmpRef.setInput('matchId', childMatchId)
+ }
+ this.cmpRef.changeDetectorRef.markForCheck()
+ },
+ error: (error) => {
+ console.error(error)
+ },
+ })
+ })
+
+ inject(DestroyRef).onDestroy(() => {
+ subscription?.unsubscribe()
+ this.vcr.clear()
+ this.cmpRef = undefined
+ this.renderedId = undefined
+ })
+ }
+}
diff --git a/packages/angular-router/src/params.ts b/packages/angular-router/src/params.ts
new file mode 100644
index 0000000000..54c737244f
--- /dev/null
+++ b/packages/angular-router/src/params.ts
@@ -0,0 +1,121 @@
+import {
+ Injector,
+ assertInInjectionContext,
+ inject,
+ runInInjectionContext,
+} from '@angular/core'
+import { toSignal } from '@angular/core/rxjs-interop'
+import { match$ } from './match'
+
+import type { Signal } from '@angular/core'
+import type {
+ AnyRouter,
+ RegisteredRouter,
+ ResolveUseParams,
+ StrictOrFrom,
+ ThrowConstraint,
+ ThrowOrOptional,
+ UseParamsResult,
+} from '@tanstack/router-core'
+import type { Observable } from 'rxjs'
+
+export interface ParamsBaseOptions<
+ TRouter extends AnyRouter,
+ TFrom,
+ TStrict extends boolean,
+ TThrow extends boolean,
+ TSelected,
+> {
+ select?: (params: ResolveUseParams) => TSelected
+ shouldThrow?: TThrow
+ injector?: Injector
+}
+
+export type ParamsOptions<
+ TRouter extends AnyRouter,
+ TFrom extends string | undefined,
+ TStrict extends boolean,
+ TThrow extends boolean,
+ TSelected,
+> = StrictOrFrom &
+ ParamsBaseOptions
+
+export type ParamsRoute = <
+ TRouter extends AnyRouter = RegisteredRouter,
+ TSelected = unknown,
+>(
+ opts?: ParamsBaseOptions<
+ TRouter,
+ TFrom,
+ /* TStrict */ true,
+ /* TThrow */ true,
+ TSelected
+ >,
+) => TObservable extends true
+ ? Observable>
+ : Signal>
+
+export function params$<
+ TRouter extends AnyRouter = RegisteredRouter,
+ const TFrom extends string | undefined = undefined,
+ TStrict extends boolean = true,
+ TThrow extends boolean = true,
+ TSelected = unknown,
+>({
+ injector,
+ ...opts
+}: ParamsOptions<
+ TRouter,
+ TFrom,
+ TStrict,
+ ThrowConstraint,
+ TSelected
+>): Observable<
+ ThrowOrOptional, TThrow>
+> {
+ !injector && assertInInjectionContext(params)
+
+ if (!injector) {
+ injector = inject(Injector)
+ }
+
+ return runInInjectionContext(injector, () => {
+ return match$({
+ from: opts.from!,
+ strict: opts.strict,
+ shouldThrow: opts.shouldThrow,
+ select: (match) => {
+ return opts.select ? opts.select(match.params) : match.params
+ },
+ }) as any
+ })
+}
+
+export function params<
+ TRouter extends AnyRouter = RegisteredRouter,
+ const TFrom extends string | undefined = undefined,
+ TStrict extends boolean = true,
+ TThrow extends boolean = true,
+ TSelected = unknown,
+>({
+ injector,
+ ...opts
+}: ParamsOptions<
+ TRouter,
+ TFrom,
+ TStrict,
+ ThrowConstraint,
+ TSelected
+>): Signal<
+ ThrowOrOptional, TThrow>
+> {
+ !injector && assertInInjectionContext(params)
+
+ if (!injector) {
+ injector = inject(Injector)
+ }
+
+ return runInInjectionContext(injector, () => {
+ return toSignal(params$({ injector, ...opts } as unknown as any)) as any
+ })
+}
diff --git a/packages/angular-router/src/route-context.ts b/packages/angular-router/src/route-context.ts
new file mode 100644
index 0000000000..685aa5560d
--- /dev/null
+++ b/packages/angular-router/src/route-context.ts
@@ -0,0 +1,80 @@
+import {
+ Injector,
+ assertInInjectionContext,
+ inject,
+ runInInjectionContext,
+} from '@angular/core'
+import { toSignal } from '@angular/core/rxjs-interop'
+import { match$ } from './match'
+
+import type { Signal } from '@angular/core'
+import type {
+ AnyRouter,
+ RegisteredRouter,
+ UseRouteContextBaseOptions,
+ UseRouteContextOptions,
+ UseRouteContextResult,
+} from '@tanstack/router-core'
+import type { Observable } from 'rxjs'
+
+export type RouteContextRoute = <
+ TRouter extends AnyRouter = RegisteredRouter,
+ TSelected = unknown,
+>(
+ opts?: UseRouteContextBaseOptions & {
+ injector?: Injector
+ },
+) => TObservable extends true
+ ? Observable>
+ : Signal>
+
+export function routeContext$<
+ TRouter extends AnyRouter = RegisteredRouter,
+ const TFrom extends string | undefined = undefined,
+ TStrict extends boolean = true,
+ TSelected = unknown,
+>({
+ injector,
+ ...opts
+}: UseRouteContextOptions & {
+ injector?: Injector
+}): Observable> {
+ !injector && assertInInjectionContext(routeContext)
+
+ if (!injector) {
+ injector = inject(Injector)
+ }
+
+ return runInInjectionContext(injector, () => {
+ return match$({
+ ...(opts as any),
+ select: (match) => {
+ return opts.select ? opts.select(match.context) : match.context
+ },
+ }) as any
+ })
+}
+
+export function routeContext<
+ TRouter extends AnyRouter = RegisteredRouter,
+ const TFrom extends string | undefined = undefined,
+ TStrict extends boolean = true,
+ TSelected = unknown,
+>({
+ injector,
+ ...opts
+}: UseRouteContextOptions & {
+ injector?: Injector
+}): Signal> {
+ !injector && assertInInjectionContext(routeContext)
+
+ if (!injector) {
+ injector = inject(Injector)
+ }
+
+ return runInInjectionContext(injector, () => {
+ return toSignal(
+ routeContext$({ injector, ...opts } as unknown as any),
+ ) as any
+ })
+}
diff --git a/packages/angular-router/src/route.ts b/packages/angular-router/src/route.ts
new file mode 100644
index 0000000000..e5ddb75119
--- /dev/null
+++ b/packages/angular-router/src/route.ts
@@ -0,0 +1,534 @@
+import { InjectionToken, runInInjectionContext } from '@angular/core'
+import { BaseRootRoute, BaseRoute, BaseRouteApi } from '@tanstack/router-core'
+import { loaderData, loaderData$ } from './loader-data'
+import { loaderDeps, loaderDeps$ } from './loader-deps'
+import { match, match$ } from './match'
+import { params, params$ } from './params'
+import { routeContext, routeContext$ } from './route-context'
+import { search, search$ } from './search'
+
+import type { Provider, Type } from '@angular/core'
+import type {
+ AnyContext,
+ AnyRoute,
+ AnyRouter,
+ ConstrainLiteral,
+ ErrorComponentProps,
+ NotFoundRouteProps,
+ Register,
+ RegisteredRouter,
+ ResolveFullPath,
+ ResolveId,
+ ResolveParams,
+ RootRouteId,
+ RootRouteOptions,
+ RouteConstraints,
+ RouteIds,
+ RouteOptions,
+} from '@tanstack/router-core'
+import type { LoaderDataRoute } from './loader-data'
+import type { LoaderDepsRoute } from './loader-deps'
+import type { MatchRoute } from './match'
+import type { ParamsRoute } from './params'
+import type { RouteContextRoute } from './route-context'
+import type { SearchRoute } from './search'
+
+declare module '@tanstack/router-core' {
+ export interface UpdatableRouteOptionsExtensions {
+ component?: () => RouteComponent
+ errorComponent?: false | null | (() => RouteComponent)
+ notFoundComponent?: () => RouteComponent
+ pendingComponent?: () => RouteComponent
+ providers?: Array
+ }
+
+ export interface RouteExtensions<
+ TId extends string,
+ TFullPath extends string,
+ > {
+ match$: MatchRoute
+ match: MatchRoute
+ routeContext$: RouteContextRoute
+ routeContext: RouteContextRoute
+ search$: SearchRoute
+ search: SearchRoute
+ params$: ParamsRoute
+ params: ParamsRoute
+ loaderDeps$: LoaderDepsRoute
+ loaderDeps: LoaderDepsRoute
+ loaderData$: LoaderDataRoute
+ loaderData: LoaderDataRoute
+ }
+}
+
+export const ERROR_COMPONENT_CONTEXT = new InjectionToken(
+ 'ERROR_COMPONENT_CONTEXT',
+)
+export const NOT_FOUND_COMPONENT_CONTEXT =
+ new InjectionToken('NOT_FOUND_COMPONENT_CONTEXT')
+
+export type RouteComponent =
+ Type
+
+export function routeApi<
+ const TId,
+ TRouter extends AnyRouter = RegisteredRouter,
+>(id: ConstrainLiteral>) {
+ return new RouteApi({ id })
+}
+
+export class RouteApi<
+ TId,
+ TRouter extends AnyRouter = RegisteredRouter,
+> extends BaseRouteApi {
+ /**
+ * @deprecated Use the `getRouteApi` function instead.
+ */
+ constructor({ id }: { id: TId }) {
+ super({ id })
+ }
+
+ match$: MatchRoute = (opts) =>
+ match$({ ...opts, from: this.id } as any) as any
+ match: MatchRoute = (opts) =>
+ match({ ...opts, from: this.id } as any) as any
+
+ routeContext$: RouteContextRoute = (opts) =>
+ routeContext$({ ...opts, from: this.id } as unknown as any)
+ routeContext: RouteContextRoute = (opts) =>
+ routeContext({ ...opts, from: this.id } as unknown as any)
+
+ search$: SearchRoute = (opts) =>
+ search$({ ...opts, from: this.id } as any) as any
+ search: SearchRoute = (opts) =>
+ search({ ...opts, from: this.id } as any) as any
+
+ params$: ParamsRoute = (opts) =>
+ params$({ ...opts, from: this.id } as any) as any
+ params: ParamsRoute = (opts) =>
+ params({ ...opts, from: this.id } as any) as any
+
+ loaderDeps$: LoaderDepsRoute = (opts) =>
+ loaderDeps$({ ...opts, from: this.id } as any)
+ loaderDeps: LoaderDepsRoute = (opts) =>
+ loaderDeps({ ...opts, from: this.id, strict: false } as any)
+
+ loaderData$: LoaderDataRoute = (opts) =>
+ loaderData$({ ...opts, from: this.id } as any)
+ loaderData: LoaderDataRoute = (opts) =>
+ loaderData({ ...opts, from: this.id, strict: false } as any)
+}
+
+export class Route<
+ in out TParentRoute extends RouteConstraints['TParentRoute'] = AnyRoute,
+ in out TPath extends RouteConstraints['TPath'] = '/',
+ in out TFullPath extends RouteConstraints['TFullPath'] = ResolveFullPath<
+ TParentRoute,
+ TPath
+ >,
+ in out TCustomId extends RouteConstraints['TCustomId'] = string,
+ in out TId extends RouteConstraints['TId'] = ResolveId<
+ TParentRoute,
+ TCustomId,
+ TPath
+ >,
+ in out TSearchValidator = undefined,
+ in out TParams = ResolveParams,
+ in out TRouterContext = AnyContext,
+ in out TRouteContextFn = AnyContext,
+ in out TBeforeLoadFn = AnyContext,
+ in out TLoaderDeps extends Record = {},
+ in out TLoaderFn = undefined,
+ in out TChildren = unknown,
+ in out TFileRouteTypes = unknown,
+> extends BaseRoute<
+ TParentRoute,
+ AnyRoute,
+ TPath,
+ TFullPath,
+ TCustomId,
+ TId,
+ TSearchValidator,
+ TParams,
+ TRouterContext,
+ TRouteContextFn,
+ TBeforeLoadFn,
+ TLoaderDeps,
+ TLoaderFn,
+ TChildren,
+ TFileRouteTypes
+> {
+ /**
+ * @deprecated Use the `createRoute` function instead.
+ */
+ constructor(
+ options?: RouteOptions<
+ TParentRoute,
+ AnyRoute,
+ TId,
+ TCustomId,
+ TFullPath,
+ TPath,
+ TSearchValidator,
+ TParams,
+ TLoaderDeps,
+ TLoaderFn,
+ TRouterContext,
+ TRouteContextFn,
+ TBeforeLoadFn
+ >,
+ ) {
+ super(options)
+ }
+
+ match$: MatchRoute = (opts) =>
+ match$({ ...opts, from: this.id } as any) as any
+ match: MatchRoute = (opts) =>
+ match({ ...opts, from: this.id } as any) as any
+
+ routeContext$: RouteContextRoute = (opts) =>
+ routeContext$({ ...opts, from: this.id } as unknown as any)
+ routeContext: RouteContextRoute = (opts) =>
+ routeContext({ ...opts, from: this.id } as unknown as any)
+
+ search$: SearchRoute = (opts) =>
+ search$({ ...opts, from: this.id } as any) as any
+ search: SearchRoute = (opts) =>
+ search({ ...opts, from: this.id } as any) as any
+
+ params$: ParamsRoute = (opts) =>
+ params$({ ...opts, from: this.id } as any) as any
+ params: ParamsRoute = (opts) =>
+ params({ ...opts, from: this.id } as any) as any
+
+ loaderDeps$: LoaderDepsRoute = (opts) =>
+ loaderDeps$({ ...opts, from: this.id } as any)
+ loaderDeps: LoaderDepsRoute = (opts) =>
+ loaderDeps({ ...opts, from: this.id } as any)
+
+ loaderData$: LoaderDataRoute = (opts) =>
+ loaderData$({ ...opts, from: this.id } as any)
+ loaderData: LoaderDataRoute = (opts) =>
+ loaderData({ ...opts, from: this.id } as any)
+}
+
+export function createRoute<
+ TParentRoute extends RouteConstraints['TParentRoute'] = AnyRoute,
+ TPath extends RouteConstraints['TPath'] = '/',
+ TFullPath extends RouteConstraints['TFullPath'] = ResolveFullPath<
+ TParentRoute,
+ TPath
+ >,
+ TCustomId extends RouteConstraints['TCustomId'] = string,
+ TId extends RouteConstraints['TId'] = ResolveId<
+ TParentRoute,
+ TCustomId,
+ TPath
+ >,
+ TSearchValidator = undefined,
+ TParams = ResolveParams,
+ TRouteContextFn = AnyContext,
+ TBeforeLoadFn = AnyContext,
+ TLoaderDeps extends Record = {},
+ TLoaderFn = undefined,
+ TChildren = unknown,
+>(
+ options: RouteOptions<
+ TParentRoute,
+ AnyRoute,
+ TId,
+ TCustomId,
+ TFullPath,
+ TPath,
+ TSearchValidator,
+ TParams,
+ TLoaderDeps,
+ TLoaderFn,
+ AnyContext,
+ TRouteContextFn,
+ TBeforeLoadFn
+ >,
+): Route<
+ TParentRoute,
+ TPath,
+ TFullPath,
+ TCustomId,
+ TId,
+ TSearchValidator,
+ TParams,
+ AnyContext,
+ TRouteContextFn,
+ TBeforeLoadFn,
+ TLoaderDeps,
+ TLoaderFn,
+ TChildren,
+ unknown
+> {
+ if (options.loader) {
+ options.loader = runFnInInjectionContext(options.loader)
+ }
+
+ if (options.shouldReload && typeof options.shouldReload === 'function') {
+ options.shouldReload = runFnInInjectionContext(options.shouldReload)
+ }
+
+ if (options.beforeLoad) {
+ options.beforeLoad = runFnInInjectionContext(options.beforeLoad)
+ }
+
+ return new Route<
+ TParentRoute,
+ TPath,
+ TFullPath,
+ TCustomId,
+ TId,
+ TSearchValidator,
+ TParams,
+ AnyContext,
+ TRouteContextFn,
+ TBeforeLoadFn,
+ TLoaderDeps,
+ TLoaderFn,
+ TChildren,
+ unknown
+ >(options)
+}
+
+export type AnyRootRoute = RootRoute
+
+export function createRootRouteWithContext() {
+ return <
+ TRegister = Register,
+ TSearchValidator = undefined,
+ TRouterContext = {},
+ TRouteContextFn = AnyContext,
+ TBeforeLoadFn = AnyContext,
+ TLoaderDeps extends Record = {},
+ TLoaderFn = undefined,
+ TSSR = unknown,
+ const TServerMiddlewares = unknown,
+ THandlers = undefined,
+ >(
+ options?: RootRouteOptions<
+ TRegister,
+ TSearchValidator,
+ TRouterContext,
+ TRouteContextFn,
+ TBeforeLoadFn,
+ TLoaderDeps,
+ TLoaderFn,
+ TSSR,
+ TServerMiddlewares,
+ THandlers
+ >,
+ ) => {
+ return createRootRoute<
+ TRegister,
+ TSearchValidator,
+ TRouterContext,
+ TRouteContextFn,
+ TBeforeLoadFn,
+ TLoaderDeps,
+ TLoaderFn,
+ TSSR,
+ TServerMiddlewares,
+ THandlers
+ >(options as any)
+ }
+}
+
+export class RootRoute<
+ in out TRegister = unknown,
+ in out TSearchValidator = undefined,
+ in out TRouterContext = {},
+ in out TRouteContextFn = AnyContext,
+ in out TBeforeLoadFn = AnyContext,
+ in out TLoaderDeps extends Record = {},
+ in out TLoaderFn = undefined,
+ in out TChildren = unknown,
+ in out TFileRouteTypes = unknown,
+ in out TSSR = unknown,
+ in out TServerMiddlewares = unknown,
+ in out THandlers = undefined,
+> extends BaseRootRoute<
+ TRegister,
+ TSearchValidator,
+ TRouterContext,
+ TRouteContextFn,
+ TBeforeLoadFn,
+ TLoaderDeps,
+ TLoaderFn,
+ TChildren,
+ TFileRouteTypes,
+ TSSR,
+ TServerMiddlewares,
+ THandlers
+> {
+ /**
+ * @deprecated `RootRoute` is now an internal implementation detail. Use `createRootRoute()` instead.
+ */
+ constructor(
+ options?: RootRouteOptions<
+ TRegister,
+ TSearchValidator,
+ TRouterContext,
+ TRouteContextFn,
+ TBeforeLoadFn,
+ TLoaderDeps,
+ TLoaderFn
+ >,
+ ) {
+ super(options as any)
+ }
+
+ match$: MatchRoute = (opts) =>
+ match$({ ...opts, from: this.id } as any) as any
+ match: MatchRoute = (opts) =>
+ match({ ...opts, from: this.id } as any) as any
+
+ routeContext$: RouteContextRoute = (opts) =>
+ routeContext$({ ...opts, from: this.id } as unknown as any)
+ routeContext: RouteContextRoute = (opts) =>
+ routeContext({ ...opts, from: this.id } as unknown as any)
+
+ search$: SearchRoute = (opts) =>
+ search$({ ...opts, from: this.id } as any) as any
+ search: SearchRoute = (opts) =>
+ search({ ...opts, from: this.id } as any) as any
+
+ params$: ParamsRoute = (opts) =>
+ params$({ ...opts, from: this.id } as any) as any
+ params: ParamsRoute = (opts) =>
+ params({ ...opts, from: this.id } as any) as any
+
+ loaderDeps$: LoaderDepsRoute = (opts) =>
+ loaderDeps$({ ...opts, from: this.id } as any)
+ loaderDeps: LoaderDepsRoute = (opts) =>
+ loaderDeps({ ...opts, from: this.id } as any)
+
+ loaderData$: LoaderDataRoute = (opts) =>
+ loaderData$({ ...opts, from: this.id } as any)
+ loaderData: LoaderDataRoute = (opts) =>
+ loaderData({ ...opts, from: this.id } as any)
+}
+
+export function createRootRoute<
+ TRegister = Register,
+ TSearchValidator = undefined,
+ TRouterContext = {},
+ TRouteContextFn = AnyContext,
+ TBeforeLoadFn = AnyContext,
+ TLoaderDeps extends Record = {},
+ TLoaderFn = undefined,
+ TSSR = unknown,
+ const TServerMiddlewares = unknown,
+ THandlers = undefined,
+>(
+ options?: RootRouteOptions<
+ TRegister,
+ TSearchValidator,
+ TRouterContext,
+ TRouteContextFn,
+ TBeforeLoadFn,
+ TLoaderDeps,
+ TLoaderFn,
+ TSSR,
+ TServerMiddlewares,
+ THandlers
+ >,
+): RootRoute<
+ TRegister,
+ TSearchValidator,
+ TRouterContext,
+ TRouteContextFn,
+ TBeforeLoadFn,
+ TLoaderDeps,
+ TLoaderFn,
+ unknown,
+ unknown,
+ TSSR,
+ TServerMiddlewares,
+ THandlers
+> {
+ return new RootRoute<
+ TRegister,
+ TSearchValidator,
+ TRouterContext,
+ TRouteContextFn,
+ TBeforeLoadFn,
+ TLoaderDeps,
+ TLoaderFn,
+ unknown,
+ unknown,
+ TSSR,
+ TServerMiddlewares,
+ THandlers
+ >(options as any)
+}
+
+export class NotFoundRoute<
+ TParentRoute extends AnyRootRoute,
+ TRouterContext = AnyContext,
+ TRouteContextFn = AnyContext,
+ TBeforeLoadFn = AnyContext,
+ TSearchValidator = undefined,
+ TLoaderDeps extends Record = {},
+ TLoaderFn = undefined,
+ TChildren = unknown,
+> extends Route<
+ TParentRoute,
+ '/404',
+ '/404',
+ '404',
+ '404',
+ TSearchValidator,
+ {},
+ TRouterContext,
+ TRouteContextFn,
+ TBeforeLoadFn,
+ TLoaderDeps,
+ TLoaderFn,
+ TChildren
+> {
+ constructor(
+ options: Omit<
+ RouteOptions<
+ TParentRoute,
+ AnyRoute,
+ string,
+ string,
+ string,
+ string,
+ TSearchValidator,
+ {},
+ TLoaderDeps,
+ TLoaderFn,
+ TRouterContext,
+ TRouteContextFn,
+ TBeforeLoadFn
+ >,
+ | 'caseSensitive'
+ | 'parseParams'
+ | 'stringifyParams'
+ | 'path'
+ | 'id'
+ | 'params'
+ >,
+ ) {
+ super({
+ ...(options as any),
+ id: '404',
+ })
+ }
+}
+
+function runFnInInjectionContext) => any>(
+ fn: TFn,
+) {
+ const originalFn = fn
+ return (...args: Parameters) => {
+ const { context, location, route } = args[0]
+ const routeInjector = context.getRouteInjector(route?.id || location.href)
+ return runInInjectionContext(routeInjector, originalFn.bind(null, ...args))
+ }
+}
diff --git a/packages/angular-router/src/router-root.ts b/packages/angular-router/src/router-root.ts
new file mode 100644
index 0000000000..a89fa0414b
--- /dev/null
+++ b/packages/angular-router/src/router-root.ts
@@ -0,0 +1,82 @@
+import {
+ Directive,
+ EnvironmentInjector,
+ effect,
+ inject,
+ input,
+} from '@angular/core'
+import { Matches } from './matches'
+import { injectRouter } from './router'
+
+import type { Provider } from '@angular/core'
+import type {
+ AnyRoute,
+ AnyRouter,
+ RegisteredRouter,
+ RouterOptions,
+} from '@tanstack/router-core'
+import type { NgRouter } from './router'
+
+export type RouterRootOptions<
+ TRouter extends AnyRouter = RegisteredRouter,
+ TDehydrated extends Record = Record,
+> = Omit<
+ RouterOptions<
+ TRouter['routeTree'],
+ NonNullable,
+ false,
+ TRouter['history'],
+ TDehydrated
+ >,
+ 'context'
+> & {
+ router: TRouter
+ context?: Partial<
+ RouterOptions<
+ TRouter['routeTree'],
+ NonNullable,
+ false,
+ TRouter['history'],
+ TDehydrated
+ >['context']
+ >
+}
+
+@Directive({
+ selector: 'router-root,RouterRoot',
+ hostDirectives: [Matches],
+})
+export class RouterRoot<
+ TRouter extends AnyRouter = RegisteredRouter,
+ TDehydrated extends Record = Record,
+> {
+ router = input['router']>(
+ injectRouter() as unknown as TRouter,
+ )
+ options = input, 'router'>>({})
+
+ constructor() {
+ const environmentInjector = inject(EnvironmentInjector)
+ effect(() => {
+ const [router, options] = [this.router(), this.options()]
+ router.update({
+ ...router.options,
+ ...options,
+ context: {
+ ...router.options.context,
+ ...options.context,
+ getRouteInjector(routeId: string, providers: Array = []) {
+ return (
+ router as unknown as NgRouter
+ ).getRouteEnvInjector(
+ routeId,
+ environmentInjector,
+ providers,
+ router,
+ )
+ },
+ },
+ })
+ })
+ }
+}
diff --git a/packages/angular-router/src/router-state.ts b/packages/angular-router/src/router-state.ts
new file mode 100644
index 0000000000..c4f7c22537
--- /dev/null
+++ b/packages/angular-router/src/router-state.ts
@@ -0,0 +1,79 @@
+import {
+ Injector,
+ assertInInjectionContext,
+ inject,
+ runInInjectionContext,
+} from '@angular/core'
+import { toSignal } from '@angular/core/rxjs-interop'
+import { distinctUntilChanged, map } from 'rxjs'
+import { injectRouterState } from './router'
+
+import type { Observable } from 'rxjs'
+
+import type { Signal, ValueEqualityFn } from '@angular/core'
+import type {
+ AnyRouter,
+ RegisteredRouter,
+ RouterState,
+} from '@tanstack/router-core'
+
+export type RouterStateResult<
+ TRouter extends AnyRouter,
+ TSelected,
+> = unknown extends TSelected ? RouterState : TSelected
+
+export type RouterStateOptions = {
+ select?: (state: RouterState) => TSelected
+ equal?: ValueEqualityFn<
+ RouterStateResult, NoInfer>
+ >
+ injector?: Injector
+}
+
+export function routerState$<
+ TRouter extends AnyRouter = RegisteredRouter,
+ TSelected = unknown,
+>({
+ select,
+ injector,
+ equal,
+}: RouterStateOptions): Observable<
+ RouterStateResult
+> {
+ !injector && assertInInjectionContext(routerState$)
+
+ if (!injector) {
+ injector = inject(Injector)
+ }
+
+ return runInInjectionContext(injector, () => {
+ const rootRouterState = injectRouterState()
+ if (select)
+ return rootRouterState.pipe(
+ map((s) => select(s) as any),
+ distinctUntilChanged(equal),
+ )
+ return rootRouterState.pipe(distinctUntilChanged(equal) as any)
+ })
+}
+
+export function routerState<
+ TRouter extends AnyRouter = RegisteredRouter,
+ TSelected = unknown,
+>({
+ select,
+ injector,
+ equal,
+}: RouterStateOptions = {}): Signal<
+ RouterStateResult
+> {
+ !injector && assertInInjectionContext(routerState)
+
+ if (!injector) {
+ injector = inject(Injector)
+ }
+
+ return runInInjectionContext(injector, () =>
+ toSignal(routerState$({ select, injector, equal }), { injector }),
+ ) as Signal>
+}
diff --git a/packages/angular-router/src/router.ts b/packages/angular-router/src/router.ts
new file mode 100644
index 0000000000..7f086e4af3
--- /dev/null
+++ b/packages/angular-router/src/router.ts
@@ -0,0 +1,206 @@
+import {
+ ApplicationRef,
+ InjectionToken,
+ Injector,
+ createEnvironmentInjector,
+ inject,
+} from '@angular/core'
+import { RouterCore, rootRouteId } from '@tanstack/router-core'
+import { BehaviorSubject } from 'rxjs'
+
+import type {
+ AnyRoute,
+ AnyRouter,
+ CreateRouterFn,
+ RouterConstructorOptions,
+ RouterState,
+ TrailingSlashOption,
+} from '@tanstack/router-core'
+import type { Observable } from 'rxjs'
+import type { EnvironmentInjector, Provider } from '@angular/core'
+import type { HistoryLocation, RouterHistory } from '@tanstack/history'
+import type { RouteComponent } from './route'
+
+declare module '@tanstack/history' {
+ interface HistoryState {
+ __tempLocation?: HistoryLocation
+ __tempKey?: string
+ __hashScrollIntoViewOptions?: boolean | ScrollIntoViewOptions
+ }
+}
+
+declare module '@tanstack/router-core' {
+ export interface RouterOptionsExtensions {
+ /**
+ * The default `component` a route should use if no component is provided.
+ *
+ * @default Outlet
+ * @link [API Docs](https://tanstack.com/router/latest/docs/framework/solid/api/router/RouterOptionsType#defaultcomponent-property)
+ */
+ defaultComponent?: () => RouteComponent
+ /**
+ * The default `errorComponent` a route should use if no error component is provided.
+ *
+ * @default ErrorComponent
+ * @link [API Docs](https://tanstack.com/router/latest/docs/framework/solid/api/router/RouterOptionsType#defaulterrorcomponent-property)
+ * @link [Guide](https://tanstack.com/router/latest/docs/framework/solid/guide/data-loading#handling-errors-with-routeoptionserrorcomponent)
+ */
+ defaultErrorComponent?: () => RouteComponent
+ /**
+ * The default `pendingComponent` a route should use if no pending component is provided.
+ *
+ * @link [API Docs](https://tanstack.com/router/latest/docs/framework/solid/api/router/RouterOptionsType#defaultpendingcomponent-property)
+ * @link [Guide](https://tanstack.com/router/latest/docs/framework/solid/guide/data-loading#showing-a-pending-component)
+ */
+ defaultPendingComponent?: () => RouteComponent
+ /**
+ * The default `notFoundComponent` a route should use if no notFound component is provided.
+ *
+ * @default NotFound
+ * @link [API Docs](https://tanstack.com/router/latest/docs/framework/solid/api/router/RouterOptionsType#defaultnotfoundcomponent-property)
+ * @link [Guide](https://tanstack.com/router/latest/docs/framework/solid/guide/not-found-errors#default-router-wide-not-found-handling)
+ */
+ defaultNotFoundComponent?: () => RouteComponent
+ /**
+ * The default `onCatch` handler for errors caught by the Router ErrorBoundary
+ *
+ * @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultoncatch-property)
+ * @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/data-loading#handling-errors-with-routeoptionsoncatch)
+ */
+ defaultOnCatch?: (error: Error) => void
+ }
+}
+
+export const ROUTER = new InjectionToken>('ROUTER')
+export const ROUTER_STATE = new InjectionToken<
+ Observable>
+>('ROUTER_STATE')
+
+export function injectRouter() {
+ return inject(ROUTER)
+}
+
+export function injectRouterState() {
+ return inject(ROUTER_STATE)
+}
+
+export function provideRouter(router: AnyRouter) {
+ return [
+ { provide: ROUTER, useValue: router },
+ {
+ provide: ROUTER_STATE,
+ useFactory: () => {
+ const state = new BehaviorSubject(router.state)
+ const appRef = inject(ApplicationRef)
+
+ const unsub = router.__store.subscribe(({ currentVal }) => {
+ state.next(currentVal)
+ })
+
+ appRef.onDestroy(() => {
+ state.complete()
+ unsub()
+ })
+
+ return state.asObservable()
+ },
+ },
+ ]
+}
+
+export const createRouter: CreateRouterFn = (options) => {
+ return new NgRouter(options)
+}
+
+export class NgRouter<
+ in out TRouteTree extends AnyRoute,
+ in out TTrailingSlashOption extends TrailingSlashOption = 'never',
+ in out TDefaultStructuralSharingOption extends boolean = false,
+ in out TRouterHistory extends RouterHistory = RouterHistory,
+ in out TDehydrated extends Record = Record,
+> extends RouterCore<
+ TRouteTree,
+ TTrailingSlashOption,
+ TDefaultStructuralSharingOption,
+ TRouterHistory,
+ TDehydrated
+> {
+ private injectors = new Map()
+ private envInjectors = new Map()
+
+ constructor(
+ options: RouterConstructorOptions<
+ TRouteTree,
+ TTrailingSlashOption,
+ TDefaultStructuralSharingOption,
+ TRouterHistory,
+ TDehydrated
+ >,
+ ) {
+ super(options)
+ }
+
+ getRouteInjector(
+ routeId: string,
+ parent: Injector,
+ providers: Array = [],
+ ) {
+ const existingInjector = this.injectors.get(routeId)
+ if (existingInjector) return existingInjector
+
+ const injector = Injector.create({
+ providers,
+ parent,
+ name: routeId,
+ })
+
+ // cache
+ this.injectors.set(routeId, injector)
+ return injector
+ }
+
+ getRouteEnvInjector(
+ routeId: string,
+ parent: EnvironmentInjector,
+ providers: Array = [],
+ router: AnyRouter,
+ ) {
+ const existingInjector = this.envInjectors.get(routeId)
+ if (existingInjector) return existingInjector
+
+ let route = router.routesById[routeId] || router.routesByPath[routeId]
+
+ // walk up the route hierarchy to build the providers
+ while (route) {
+ if (route.options?.providers) {
+ providers.push(...route.options.providers)
+ }
+
+ const parentInjector = route.parentRoute
+ ? this.envInjectors.get(route.parentRoute.id)
+ : null
+
+ if (parentInjector) {
+ parent = parentInjector
+ break
+ }
+
+ route = route.parentRoute
+ }
+
+ const envInjector = createEnvironmentInjector(providers, parent, routeId)
+
+ // if routeId is rootRouteId, we'll switch existing injectors' parent to the __root__ injector
+ if (routeId === rootRouteId) {
+ this.envInjectors.forEach((ele) => {
+ if ('parent' in ele && ele.parent === parent) {
+ ele.parent = envInjector
+ }
+ })
+ }
+
+ // cache
+ this.envInjectors.set(routeId, envInjector)
+ return envInjector
+ }
+}
diff --git a/packages/angular-router/src/search.ts b/packages/angular-router/src/search.ts
new file mode 100644
index 0000000000..e7c5b03767
--- /dev/null
+++ b/packages/angular-router/src/search.ts
@@ -0,0 +1,121 @@
+import {
+ Injector,
+ assertInInjectionContext,
+ inject,
+ runInInjectionContext,
+} from '@angular/core'
+import { toSignal } from '@angular/core/rxjs-interop'
+import { match$ } from './match'
+
+import type { Signal } from '@angular/core'
+import type {
+ AnyRouter,
+ RegisteredRouter,
+ ResolveUseSearch,
+ StrictOrFrom,
+ ThrowConstraint,
+ ThrowOrOptional,
+ UseSearchResult,
+} from '@tanstack/router-core'
+import type { Observable } from 'rxjs'
+
+export interface SearchBaseOptions<
+ TRouter extends AnyRouter,
+ TFrom,
+ TStrict extends boolean,
+ TThrow extends boolean,
+ TSelected,
+> {
+ select?: (state: ResolveUseSearch