Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 17 additions & 17 deletions adev-es/src/app/routing/sub-navigation-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -326,89 +326,89 @@ const DOCS_SUB_NAVIGATION_DATA: NavigationItem[] = [
],
},
{
label: 'Routing',
label: 'Enrutamiento',
status: 'updated',
children: [
{
label: 'Overview',
label: 'Visión general',
path: 'guide/routing',
contentPath: 'guide/routing/overview',
},
{
label: 'Define routes',
label: 'Definir rutas',
path: 'guide/routing/define-routes',
contentPath: 'guide/routing/define-routes',
},
{
label: 'Show routes with Outlets',
label: 'Mostrar rutas con outlets',
path: 'guide/routing/show-routes-with-outlets',
contentPath: 'guide/routing/show-routes-with-outlets',
},
{
label: 'Navigate to routes',
label: 'Navegar a rutas',
path: 'guide/routing/navigate-to-routes',
contentPath: 'guide/routing/navigate-to-routes',
},
{
label: 'Read route state',
label: 'Leer estado de ruta',
path: 'guide/routing/read-route-state',
contentPath: 'guide/routing/read-route-state',
},
{
label: 'Redirecting routes',
label: 'Redirigir rutas',
path: 'guide/routing/redirecting-routes',
contentPath: 'guide/routing/redirecting-routes',
},
{
label: 'Control route access with guards',
label: 'Controlar acceso a rutas con guards',
path: 'guide/routing/route-guards',
contentPath: 'guide/routing/route-guards',
},
{
label: 'Route data resolvers',
label: 'Resolvers de datos de ruta',
path: 'guide/routing/data-resolvers',
contentPath: 'guide/routing/data-resolvers',
},
{
label: 'Lifecycle and events',
label: 'Ciclo de vida y eventos',
path: 'guide/routing/lifecycle-and-events',
contentPath: 'guide/routing/lifecycle-and-events',
},
{
label: 'Testing routing and navigation',
label: 'Pruebas de routing y navegación',
path: 'guide/routing/testing',
contentPath: 'guide/routing/testing',
status: 'new',
},
{
label: 'Other routing tasks',
label: 'Otras tareas de routing',
path: 'guide/routing/common-router-tasks',
contentPath: 'guide/routing/common-router-tasks',
},
{
label: 'Creating custom route matches',
label: 'Creando coincidencias de ruta personalizadas',
path: 'guide/routing/routing-with-urlmatcher',
contentPath: 'guide/routing/routing-with-urlmatcher',
},
{
label: 'Rendering strategies',
label: 'Estrategias de renderizado',
path: 'guide/routing/rendering-strategies',
contentPath: 'guide/routing/rendering-strategies',
status: 'new',
},
{
label: 'Customizing route behavior',
label: 'Personalizar comportamiento de ruta',
path: 'guide/routing/customizing-route-behavior',
contentPath: 'guide/routing/customizing-route-behavior',
status: 'new',
},
{
label: 'Router reference',
label: 'Referencia del Router',
path: 'guide/routing/router-reference',
contentPath: 'guide/routing/router-reference',
},
{
label: 'Route transition animations',
label: 'Animaciones de transición de ruta',
path: 'guide/routing/route-transition-animations',
contentPath: 'guide/routing/route-transition-animations',
},
Expand Down
187 changes: 187 additions & 0 deletions adev-es/src/content/guide/routing/common-router-tasks.en.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
# Other common Routing Tasks

This guide covers some other common tasks associated with using Angular router in your application.

## Getting route information

Often, as a user navigates your application, you want to pass information from one component to another.
For example, consider an application that displays a shopping list of grocery items.
Each item in the list has a unique `id`.
To edit an item, users click an Edit button, which opens an `EditGroceryItem` component.
You want that component to retrieve the `id` for the grocery item so it can display the right information to the user.

Use a route to pass this type of information to your application components.
To do so, you use the [`withComponentInputBinding`](api/router/withComponentInputBinding) feature with `provideRouter` or the `bindToComponentInputs` option of `RouterModule.forRoot`.

To get information from a route:

<docs-workflow>

<docs-step title="Add `withComponentInputBinding`">

Add the `withComponentInputBinding` feature to the `provideRouter` method.

```ts
providers: [
provideRouter(appRoutes, withComponentInputBinding()),
]
```

</docs-step>

<docs-step title="Add an `input` to the component">

Update the component to have an `input()` property matching the name of the parameter.

```ts
id = input.required<string>()
hero = computed(() => this.service.getHero(id));
```

</docs-step>
<docs-step title="Optional: Use a default value">
The router assigns values to all inputs based on the current route when `withComponentInputBinding` is enabled.
The router assigns `undefined` if no route data matches the input key, such as when an optional query parameter is missing.
You should include `undefined` in the `input`'s type when there's a possibility that an input might not be matched by the route.

Provide a default value by either using the `transform` option on the input or managing a local state with a `linkedSignal`.

```ts
id = input.required({
transform: (maybeUndefined: string | undefined) => maybeUndefined ?? '0',
});
// or
id = input<string|undefined>();
internalId = linkedSignal(() => this.id() ?? getDefaultId());
```

</docs-step>
</docs-workflow>

NOTE: You can bind all route data with key, value pairs to component inputs: static or resolved route data, path parameters, matrix parameters, and query parameters.
If you want to use the parent components route info you will need to set the router `paramsInheritanceStrategy` option:
`withRouterConfig({paramsInheritanceStrategy: 'always'})`

## Displaying a 404 page

To display a 404 page, set up a [wildcard route](guide/routing/common-router-tasks#setting-up-wildcard-routes) with the `component` property set to the component you'd like to use for your 404 page as follows:

```ts
const routes: Routes = [
{ path: 'first-component', component: FirstComponent },
{ path: 'second-component', component: SecondComponent },
{ path: '**', component: PageNotFoundComponent }, // Wildcard route for a 404 page
];
```

The last route with the `path` of `**` is a wildcard route.
The router selects this route if the requested URL doesn't match any of the paths earlier in the list and sends the user to the `PageNotFoundComponent`.

## Link parameters array

A link parameters array holds the following ingredients for router navigation:

- The path of the route to the destination component
- Required and optional route parameters that go into the route URL

Bind the `RouterLink` directive to such an array like this:

```angular-html
<a [routerLink]="['/heroes']">Heroes</a>
```

The following is a two-element array when specifying a route parameter:

```angular-html
<a [routerLink]="['/hero', hero.id]">
<span class="badge">{{ hero.id }}</span>{{ hero.name }}
</a>
```

Provide optional route parameters in an object, as in `{ foo: 'foo' }`:

```angular-html
<a [routerLink]="['/crisis-center', { foo: 'foo' }]">Crisis Center</a>
```

These three examples cover the needs of an application with one level of routing.
However, with a child router, such as in the crisis center, you create new link array possibilities.

The following minimal `RouterLink` example builds upon a specified default child route for the crisis center.

```angular-html
<a [routerLink]="['/crisis-center']">Crisis Center</a>
```

Review the following:

- The first item in the array identifies the parent route \(`/crisis-center`\)
- There are no parameters for this parent route
- There is no default for the child route so you need to pick one
- You're navigating to the `CrisisListComponent`, whose route path is `/`, but you don't need to explicitly add the slash

Consider the following router link that navigates from the root of the application down to the Dragon Crisis:

```angular-html
<a [routerLink]="['/crisis-center', 1]">Dragon Crisis</a>
```

- The first item in the array identifies the parent route \(`/crisis-center`\)
- There are no parameters for this parent route
- The second item identifies the child route details about a particular crisis \(`/:id`\)
- The details child route requires an `id` route parameter
- You added the `id` of the Dragon Crisis as the second item in the array \(`1`\)
- The resulting path is `/crisis-center/1`

You could also redefine the `AppComponent` template with Crisis Center routes exclusively:

```angular-ts
@Component({
template: `
<h1 class="title">Angular Router</h1>
<nav>
<a [routerLink]="['/crisis-center']">Crisis Center</a>
<a [routerLink]="['/crisis-center/1', { foo: 'foo' }]">Dragon Crisis</a>
<a [routerLink]="['/crisis-center/2']">Shark Crisis</a>
</nav>
<router-outlet />
`
})
export class AppComponent {}
```

In summary, you can write applications with one, two or more levels of routing.
The link parameters array affords the flexibility to represent any routing depth and any legal sequence of route paths, \(required\) router parameters, and \(optional\) route parameter objects.

## `LocationStrategy` and browser URL styles

When the router navigates to a new component view, it updates the browser's location and history with a URL for that view.

Modern HTML5 browsers support [history.pushState](https://developer.mozilla.org/docs/Web/API/History_API/Working_with_the_History_API#adding_and_modifying_history_entries 'HTML5 browser history push-state'), a technique that changes a browser's location and history without triggering a server page request.
The router can compose a "natural" URL that is indistinguishable from one that would otherwise require a page load.

Here's the Crisis Center URL in this "HTML5 pushState" style:

```text
localhost:3002/crisis-center
```

Older browsers send page requests to the server when the location URL changes unless the change occurs after a "#" \(called the "hash"\).
Routers can take advantage of this exception by composing in-application route URLs with hashes.
Here's a "hash URL" that routes to the Crisis Center.

```text
localhost:3002/src/#/crisis-center
```

The router supports both styles with two `LocationStrategy` providers:

| Providers | Details |
| :--------------------- | :----------------------------------- |
| `PathLocationStrategy` | The default "HTML5 pushState" style. |
| `HashLocationStrategy` | The "hash URL" style. |

The `RouterModule.forRoot()` function sets the `LocationStrategy` to the `PathLocationStrategy`, which makes it the default strategy.
You also have the option of switching to the `HashLocationStrategy` with an override during the bootstrapping process.

HELPFUL: For more information on providers and the bootstrap process, see [Dependency Injection](guide/di/dependency-injection-providers).
Loading