From b68ba6e77e62add1e37ff4e88da0dc2c4e0820d7 Mon Sep 17 00:00:00 2001 From: Arcadio Quintero Date: Wed, 2 Sep 2026 15:43:29 -0400 Subject: [PATCH] translate: miscellaneous Angular 22.1 guides and the v21 event page Translate into Spanish, each with its .en.md backup: - guide/routing/loading-strategies.md - best-practices/performance/overview.md - tools/devtools/router.md - events/v21.md Fixes #190 --- .../best-practices/performance/overview.en.md | 44 +++++++++ .../best-practices/performance/overview.md | 60 ++++++------ adev-es/src/content/events/v21.en.md | 25 +++++ adev-es/src/content/events/v21.md | 26 ++--- .../guide/routing/loading-strategies.en.md | 96 +++++++++++++++++++ .../guide/routing/loading-strategies.md | 50 +++++----- .../src/content/tools/devtools/router.en.md | 30 ++++++ adev-es/src/content/tools/devtools/router.md | 42 ++++---- 8 files changed, 284 insertions(+), 89 deletions(-) create mode 100644 adev-es/src/content/best-practices/performance/overview.en.md create mode 100644 adev-es/src/content/events/v21.en.md create mode 100644 adev-es/src/content/guide/routing/loading-strategies.en.md create mode 100644 adev-es/src/content/tools/devtools/router.en.md diff --git a/adev-es/src/content/best-practices/performance/overview.en.md b/adev-es/src/content/best-practices/performance/overview.en.md new file mode 100644 index 00000000..0754c74c --- /dev/null +++ b/adev-es/src/content/best-practices/performance/overview.en.md @@ -0,0 +1,44 @@ +# Performance + +Angular includes many optimizations out of the box, but as applications grow, you may need to fine-tune both how quickly your app loads and how responsive it feels during use. These guides cover the tools and techniques Angular provides to help you build fast applications. + +## Loading performance + +Loading performance determines how quickly your application becomes visible and interactive. Slow loading directly impacts [Core Web Vitals](https://web.dev/vitals/) like Largest Contentful Paint (LCP) and Time to First Byte (TTFB). + +| Technique | What it does | When to use it | +| :------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :-------------------------------------------------------------------------------------------- | +| [Lazy-loaded routes](best-practices/performance/lazy-loaded-routes#lazily-loaded-components-and-routes) | Defers loading route components until navigation, reducing the initial bundle size | Applications with multiple routes where not all are needed on initial load | +| [Deferred loading with `@defer`](best-practices/performance/defer) | Splits components into separate bundles that load on demand | Components not visible on initial render, heavy third-party libraries, below-the-fold content | +| [Lazy loading services with `injectAsync`](guide/di/lazy-loading-services) | Splits rarely used services into separate chunks and loads them on demand | Services backed by large libraries or infrequently used features | +| [Image optimization](best-practices/performance/image-optimization) | Prioritizes LCP images, lazy loads others, generates responsive `srcset` attributes | Any application that displays images | +| [Server-side rendering](best-practices/performance/ssr) | Renders pages on the server for faster first paint and better SEO, with [hydration](guide/hydration) to restore interactivity and [incremental hydration](guide/incremental-hydration) to defer hydrating sections until needed | Content-heavy applications, pages that need search engine indexing | + +## Runtime performance + +Runtime performance determines how responsive your application feels after it loads. Angular's change detection system keeps the DOM in sync with your data, and optimizing how and when it runs is the primary lever for improving runtime performance. + +| Technique | What it does | When to use it | +| :-------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------ | +| [Zoneless change detection](guide/zoneless) | Removes ZoneJS overhead and triggers change detection only when signals or events indicate a change | New applications (default in Angular v21+), or existing applications ready to migrate | +| [Slow computations](best-practices/slow-computations) | Identifies and optimizes expensive template expressions and lifecycle hooks | Profiling reveals specific components causing slow change detection cycles | +| [Skipping component subtrees](best-practices/skipping-subtrees) | Uses `OnPush` change detection to skip unchanged component trees | Applications that need finer control over change detection | +| [Zone pollution](best-practices/zone-pollution) | Prevents unnecessary change detection caused by third-party libraries or timers | Zone-based applications where profiling reveals excessive change detection cycles | + +## Measuring performance + +Identifying what to optimize is just as important as knowing how to optimize it. Angular integrates with browser developer tools to help you find bottlenecks. + +| Tool | What it does | +| :------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [Chrome DevTools profiling](best-practices/profiling-with-chrome-devtools) | Records Angular-specific performance data alongside browser profiling, with color-coded flame charts that show component rendering, change detection cycles, and lifecycle hooks | +| [Angular DevTools](tools/devtools) | A browser extension that provides a component tree inspector and a profiler for visualizing change detection cycles | + +## What to optimize first + +If you are unsure where to start, profile your application first using the [Chrome DevTools Angular track](best-practices/profiling-with-chrome-devtools) to identify specific bottlenecks. + +As a general starting point: + +- **Slow initial load** — Use [`@defer`](best-practices/performance/defer) to split large components out of the main bundle, [`NgOptimizedImage`](best-practices/performance/image-optimization) to prioritize above-the-fold images, and [server-side rendering](best-practices/performance/ssr) to deliver content faster. +- **Slow interactions after load** — Check whether [zoneless change detection](guide/zoneless) is enabled, look for [slow computations](best-practices/slow-computations) in templates or lifecycle hooks, and consider [`OnPush`](best-practices/skipping-subtrees) to reduce unnecessary change detection. diff --git a/adev-es/src/content/best-practices/performance/overview.md b/adev-es/src/content/best-practices/performance/overview.md index 0754c74c..5019a52f 100644 --- a/adev-es/src/content/best-practices/performance/overview.md +++ b/adev-es/src/content/best-practices/performance/overview.md @@ -1,44 +1,44 @@ -# Performance +# Rendimiento -Angular includes many optimizations out of the box, but as applications grow, you may need to fine-tune both how quickly your app loads and how responsive it feels during use. These guides cover the tools and techniques Angular provides to help you build fast applications. +Angular incluye muchas optimizaciones listas para usar, pero a medida que las aplicaciones crecen, puede que necesites ajustar tanto la rapidez con la que carga tu aplicación como la capacidad de respuesta que ofrece durante su uso. Estas guías cubren las herramientas y técnicas que Angular proporciona para ayudarte a construir aplicaciones rápidas. -## Loading performance +## Rendimiento de carga {#loading-performance} -Loading performance determines how quickly your application becomes visible and interactive. Slow loading directly impacts [Core Web Vitals](https://web.dev/vitals/) like Largest Contentful Paint (LCP) and Time to First Byte (TTFB). +El rendimiento de carga determina qué tan rápido tu aplicación se vuelve visible e interactiva. Una carga lenta afecta directamente a las [Core Web Vitals](https://web.dev/vitals/) como Largest Contentful Paint (LCP) y Time to First Byte (TTFB). -| Technique | What it does | When to use it | -| :------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :-------------------------------------------------------------------------------------------- | -| [Lazy-loaded routes](best-practices/performance/lazy-loaded-routes#lazily-loaded-components-and-routes) | Defers loading route components until navigation, reducing the initial bundle size | Applications with multiple routes where not all are needed on initial load | -| [Deferred loading with `@defer`](best-practices/performance/defer) | Splits components into separate bundles that load on demand | Components not visible on initial render, heavy third-party libraries, below-the-fold content | -| [Lazy loading services with `injectAsync`](guide/di/lazy-loading-services) | Splits rarely used services into separate chunks and loads them on demand | Services backed by large libraries or infrequently used features | -| [Image optimization](best-practices/performance/image-optimization) | Prioritizes LCP images, lazy loads others, generates responsive `srcset` attributes | Any application that displays images | -| [Server-side rendering](best-practices/performance/ssr) | Renders pages on the server for faster first paint and better SEO, with [hydration](guide/hydration) to restore interactivity and [incremental hydration](guide/incremental-hydration) to defer hydrating sections until needed | Content-heavy applications, pages that need search engine indexing | +| Técnica | Qué hace | Cuándo usarla | +| :------------------------------------------------------------------------------------------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------- | +| [Rutas con carga diferida](best-practices/performance/lazy-loaded-routes#lazily-loaded-components-and-routes) | Pospone la carga de los componentes de ruta hasta la navegación, reduciendo el tamaño del bundle inicial | Aplicaciones con múltiples rutas donde no todas se necesitan en la carga inicial | +| [Carga diferida con `@defer`](best-practices/performance/defer) | Divide los componentes en bundles separados que se cargan bajo demanda | Componentes no visibles en el renderizado inicial, bibliotecas de terceros pesadas, contenido bajo el pliegue | +| [Lazy loading de servicios con `injectAsync`](guide/di/lazy-loading-services) | Divide los servicios poco usados en chunks separados y los carga bajo demanda | Servicios respaldados por bibliotecas grandes o funcionalidades de uso poco frecuente | +| [Optimización de imágenes](best-practices/performance/image-optimization) | Prioriza las imágenes LCP, carga las demás de forma diferida y genera atributos `srcset` responsivos | Cualquier aplicación que muestre imágenes | +| [Renderizado del lado del servidor](best-practices/performance/ssr) | Renderiza las páginas en el servidor para un primer pintado más rápido y mejor SEO, con [hidratación](guide/hydration) para restaurar la interactividad e [hidratación incremental](guide/incremental-hydration) para posponer la hidratación de secciones hasta que se necesiten | Aplicaciones con mucho contenido, páginas que necesitan indexación en motores de búsqueda | -## Runtime performance +## Rendimiento en tiempo de ejecución {#runtime-performance} -Runtime performance determines how responsive your application feels after it loads. Angular's change detection system keeps the DOM in sync with your data, and optimizing how and when it runs is the primary lever for improving runtime performance. +El rendimiento en tiempo de ejecución determina qué tan fluida se siente tu aplicación después de cargar. El sistema de detección de cambios de Angular mantiene el DOM sincronizado con tus datos, y optimizar cómo y cuándo se ejecuta es la principal palanca para mejorar el rendimiento en tiempo de ejecución. -| Technique | What it does | When to use it | -| :-------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------ | -| [Zoneless change detection](guide/zoneless) | Removes ZoneJS overhead and triggers change detection only when signals or events indicate a change | New applications (default in Angular v21+), or existing applications ready to migrate | -| [Slow computations](best-practices/slow-computations) | Identifies and optimizes expensive template expressions and lifecycle hooks | Profiling reveals specific components causing slow change detection cycles | -| [Skipping component subtrees](best-practices/skipping-subtrees) | Uses `OnPush` change detection to skip unchanged component trees | Applications that need finer control over change detection | -| [Zone pollution](best-practices/zone-pollution) | Prevents unnecessary change detection caused by third-party libraries or timers | Zone-based applications where profiling reveals excessive change detection cycles | +| Técnica | Qué hace | Cuándo usarla | +| :--------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------- | +| [Detección de cambios zoneless](guide/zoneless) | Elimina la sobrecarga de ZoneJS y activa la detección de cambios solo cuando las signals o los eventos indican un cambio | Aplicaciones nuevas (predeterminado en Angular v21+), o aplicaciones existentes listas para migrar | +| [Cálculos lentos](best-practices/slow-computations) | Identifica y optimiza expresiones de plantilla y hooks de ciclo de vida costosos | El perfilado revela componentes específicos que causan ciclos de detección de cambios lentos | +| [Omitir subárboles de componentes](best-practices/skipping-subtrees) | Usa la detección de cambios `OnPush` para omitir árboles de componentes sin cambios | Aplicaciones que necesitan un control más fino sobre la detección de cambios | +| [Contaminación de zona](best-practices/zone-pollution) | Evita la detección de cambios innecesaria causada por bibliotecas de terceros o temporizadores | Aplicaciones basadas en zonas donde el perfilado revela ciclos de detección de cambios excesivos | -## Measuring performance +## Medir el rendimiento {#measuring-performance} -Identifying what to optimize is just as important as knowing how to optimize it. Angular integrates with browser developer tools to help you find bottlenecks. +Identificar qué optimizar es tan importante como saber cómo optimizarlo. Angular se integra con las herramientas de desarrollo del navegador para ayudarte a encontrar cuellos de botella. -| Tool | What it does | -| :------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [Chrome DevTools profiling](best-practices/profiling-with-chrome-devtools) | Records Angular-specific performance data alongside browser profiling, with color-coded flame charts that show component rendering, change detection cycles, and lifecycle hooks | -| [Angular DevTools](tools/devtools) | A browser extension that provides a component tree inspector and a profiler for visualizing change detection cycles | +| Herramienta | Qué hace | +| :------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [Perfilado con Chrome DevTools](best-practices/profiling-with-chrome-devtools) | Registra datos de rendimiento específicos de Angular junto con el perfilado del navegador, con gráficos de llamas codificados por colores que muestran el renderizado de componentes, los ciclos de detección de cambios y los hooks de ciclo de vida | +| [Angular DevTools](tools/devtools) | Una extensión del navegador que proporciona un inspector del árbol de componentes y un profiler para visualizar los ciclos de detección de cambios | -## What to optimize first +## Qué optimizar primero {#what-to-optimize-first} -If you are unsure where to start, profile your application first using the [Chrome DevTools Angular track](best-practices/profiling-with-chrome-devtools) to identify specific bottlenecks. +Si no sabes por dónde empezar, primero perfila tu aplicación usando la [pista de Angular en Chrome DevTools](best-practices/profiling-with-chrome-devtools) para identificar cuellos de botella específicos. -As a general starting point: +Como punto de partida general: -- **Slow initial load** — Use [`@defer`](best-practices/performance/defer) to split large components out of the main bundle, [`NgOptimizedImage`](best-practices/performance/image-optimization) to prioritize above-the-fold images, and [server-side rendering](best-practices/performance/ssr) to deliver content faster. -- **Slow interactions after load** — Check whether [zoneless change detection](guide/zoneless) is enabled, look for [slow computations](best-practices/slow-computations) in templates or lifecycle hooks, and consider [`OnPush`](best-practices/skipping-subtrees) to reduce unnecessary change detection. +- **Carga inicial lenta** — Usa [`@defer`](best-practices/performance/defer) para separar los componentes grandes del bundle principal, [`NgOptimizedImage`](best-practices/performance/image-optimization) para priorizar las imágenes sobre el pliegue, y el [renderizado del lado del servidor](best-practices/performance/ssr) para entregar el contenido más rápido. +- **Interacciones lentas después de la carga** — Comprueba si la [detección de cambios zoneless](guide/zoneless) está habilitada, busca [cálculos lentos](best-practices/slow-computations) en plantillas o hooks de ciclo de vida, y considera [`OnPush`](best-practices/skipping-subtrees) para reducir la detección de cambios innecesaria. diff --git a/adev-es/src/content/events/v21.en.md b/adev-es/src/content/events/v21.en.md new file mode 100644 index 00000000..675e931a --- /dev/null +++ b/adev-es/src/content/events/v21.en.md @@ -0,0 +1,25 @@ +![A retro 8-bit, pixel art style graphic announcing the upcoming release of Angular v21. The large, gradient 'v21' text dominates the frame. Next to it, in smaller text, are the words 'The Adventure Begins' and the release date '11-20-2025' inside a pink pixelated box. The Angular logo is in the bottom right corner.](assets/images/v21-event/angular-v21-hero.jpg {loading: 'eager', fetchpriority: 'high'} 'Angular v21 Hero Image') + +# Angular v21: The Adventure Begins + +## Release Blog + +**Angular v21 is live**: check out the [v21 release blog](https://goo.gle/angular-v21-blog) to learn about all of the amazing new features coming your way. + +## Experience the v21 Release + +Explore the Angular v21 release with this interactive game world. Curious how we made it? Click the `Show Code` button below to view the source code for this Angular app. + + + +## Angular v21 Developer Event [Full Version] + +Angular v21 is being delivered to you as a brand new release adventure. With modern AI tooling, performance updates and more, Angular v21 delivers fantastic new features to improve your developer experience. Whether you’re creating AI-powered apps or scalable enterprise applications, there has never been a better time to build with Angular. + +🔥 What's coming in v21 + +- New Angular MCP Server tools to improve AI-powered workflows and code generation +- Your first look at Signal Forms, our new streamlined, signal-based approach to forms in Angular +- Exciting new details about the Angular Aria package + + diff --git a/adev-es/src/content/events/v21.md b/adev-es/src/content/events/v21.md index 675e931a..56179521 100644 --- a/adev-es/src/content/events/v21.md +++ b/adev-es/src/content/events/v21.md @@ -1,25 +1,25 @@ -![A retro 8-bit, pixel art style graphic announcing the upcoming release of Angular v21. The large, gradient 'v21' text dominates the frame. Next to it, in smaller text, are the words 'The Adventure Begins' and the release date '11-20-2025' inside a pink pixelated box. The Angular logo is in the bottom right corner.](assets/images/v21-event/angular-v21-hero.jpg {loading: 'eager', fetchpriority: 'high'} 'Angular v21 Hero Image') +![Un gráfico retro al estilo pixel art de 8 bits que anuncia el próximo lanzamiento de Angular v21. El gran texto 'v21' con degradado domina la imagen. Junto a él, en texto más pequeño, aparecen las palabras 'The Adventure Begins' y la fecha de lanzamiento '11-20-2025' dentro de una caja pixelada rosa. El logo de Angular está en la esquina inferior derecha.](assets/images/v21-event/angular-v21-hero.jpg {loading: 'eager', fetchpriority: 'high'} 'Angular v21 Hero Image') -# Angular v21: The Adventure Begins +# Angular v21: La aventura comienza -## Release Blog +## Blog de lanzamiento {#release-blog} -**Angular v21 is live**: check out the [v21 release blog](https://goo.gle/angular-v21-blog) to learn about all of the amazing new features coming your way. +**Angular v21 ya está disponible**: consulta el [blog de lanzamiento de v21](https://goo.gle/angular-v21-blog) para conocer todas las increíbles nuevas características que llegan. -## Experience the v21 Release +## Experimenta el lanzamiento de v21 {#experience-the-v21-release} -Explore the Angular v21 release with this interactive game world. Curious how we made it? Click the `Show Code` button below to view the source code for this Angular app. +Explora el lanzamiento de Angular v21 con este mundo de juego interactivo. ¿Tienes curiosidad por saber cómo lo hicimos? Haz clic en el botón `Show Code` de abajo para ver el código fuente de esta aplicación Angular. - + -## Angular v21 Developer Event [Full Version] +## Evento para desarrolladores de Angular v21 [Versión completa] {#angular-v21-developer-event-full-version} -Angular v21 is being delivered to you as a brand new release adventure. With modern AI tooling, performance updates and more, Angular v21 delivers fantastic new features to improve your developer experience. Whether you’re creating AI-powered apps or scalable enterprise applications, there has never been a better time to build with Angular. +Angular v21 llega a ti como una aventura de lanzamiento completamente nueva. Con herramientas modernas de IA, mejoras de rendimiento y más, Angular v21 ofrece fantásticas nuevas características para mejorar tu experiencia de desarrollo. Ya sea que estés creando aplicaciones impulsadas por IA o aplicaciones empresariales escalables, nunca ha habido un mejor momento para construir con Angular. -🔥 What's coming in v21 +🔥 Qué llega en v21 -- New Angular MCP Server tools to improve AI-powered workflows and code generation -- Your first look at Signal Forms, our new streamlined, signal-based approach to forms in Angular -- Exciting new details about the Angular Aria package +- Nuevas herramientas del Angular MCP Server para mejorar los flujos de trabajo impulsados por IA y la generación de código +- Tu primer vistazo a Signal Forms, nuestro nuevo enfoque simplificado basado en signals para los formularios en Angular +- Nuevos y emocionantes detalles sobre el paquete Angular Aria diff --git a/adev-es/src/content/guide/routing/loading-strategies.en.md b/adev-es/src/content/guide/routing/loading-strategies.en.md new file mode 100644 index 00000000..dfdd13c7 --- /dev/null +++ b/adev-es/src/content/guide/routing/loading-strategies.en.md @@ -0,0 +1,96 @@ +# Route Loading Strategies + +Understanding how and when routes and components load in Angular routing is crucial for building responsive web applications. Angular offers two primary strategies to control loading behavior: + +1. **Eagerly loaded**: Routes and components that are loaded immediately +2. **Lazily loaded**: Routes and components loaded only when needed + +Each approach offers distinct advantages for different scenarios. + +## Eagerly loaded components + +When you define a route with the [`component`](api/router/Route#component) property, the referenced component is eagerly loaded as part of the same JavaScript bundle as the route configuration. + +```ts +import {Routes} from '@angular/router'; +import {HomePage} from './components/home/home-page'; +import {LoginPage} from './components/auth/login-page'; + +export const routes: Routes = [ + // HomePage and LoginPage are both directly referenced in this config, + // so their code is eagerly included in the same JavaScript bundle as this file. + { + path: '', + component: HomePage, + }, + { + path: 'login', + component: LoginPage, + }, +]; +``` + +Eagerly loading route components like this means that the browser has to download and parse all of the JavaScript for these components as part of your initial page load, but the components are available to Angular immediately. + +While including more JavaScript in your initial page load leads to slower initial load times, this can lead to more seamless transitions as the user navigates through an application. + +## Lazily loaded components and routes + +You can use the [`loadComponent`](api/router/Route#loadComponent) property to lazily load the JavaScript for a component at the point at which that route would become active. The [`loadChildren`](api/router/Route#loadChildren) property lazily loads child routes during route matching. + +```ts +import {Routes} from '@angular/router'; + +export const routes: Routes = [ + { + path: 'login', + loadComponent: () => import('./components/auth/login-page'), + }, + { + path: 'admin', + loadComponent: () => import('./admin/admin.component'), + loadChildren: () => import('./admin/admin.routes'), + }, +]; +``` + +The [`loadComponent`](/api/router/Route#loadComponent) and [`loadChildren`](/api/router/Route#loadChildren) properties accept a loader function that returns a Promise that resolves to an Angular component or a set of routes respectively. In most cases, this function uses the standard [JavaScript dynamic import API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import). You can, however, use any arbitrary async loader function. + +If the lazily loaded file uses a `default` export, you can return the `import()` promise directly without an additional `.then` call to select the exported class. + +Lazily loading routes can significantly improve the load speed of your Angular application by removing large portions of JavaScript from the initial bundle. These portions of your code compile into separate JavaScript "chunks" that the router requests only when the user visits the corresponding route. + +## Injection context lazy loading + +The Router executes [`loadComponent`](/api/router/Route#loadComponent) and [`loadChildren`](/api/router/Route#loadChildren) within the **injection context of the current route**, allowing you to call [`inject`](/api/core/inject)inside these loader functions to access providers declared on that route, inherited from parent routes through hierarchical dependency injection, or available globally. This enables context-aware lazy loading. + +```ts +import {Routes} from '@angular/router'; +import {inject} from '@angular/core'; +import {FeatureFlags} from './feature-flags'; + +export const routes: Routes = [ + { + path: 'dashboard', + // Runs inside the route's injection context + loadComponent: () => { + const flags = inject(FeatureFlags); + return flags.isPremium + ? import('./dashboard/premium-dashboard') + : import('./dashboard/basic-dashboard'); + }, + }, +]; +``` + +## Should I use an eager or a lazy route? + +There are many factors to consider when deciding on whether a route should be eager or lazy. + +In general, eager loading is recommended for primary landing page(s) while other pages would be lazy-loaded. + +NOTE: While lazy routes have the upfront performance benefit of reducing the amount of initial data requested by the user, it adds future data requests that could be undesirable. This is particularly true when dealing with nested lazy loading at multiple levels, which can significantly impact performance. + +## Next steps + +Learn how to [display the contents of your routes with Outlets](/guide/routing/show-routes-with-outlets). diff --git a/adev-es/src/content/guide/routing/loading-strategies.md b/adev-es/src/content/guide/routing/loading-strategies.md index dfdd13c7..5a80a7a5 100644 --- a/adev-es/src/content/guide/routing/loading-strategies.md +++ b/adev-es/src/content/guide/routing/loading-strategies.md @@ -1,15 +1,15 @@ -# Route Loading Strategies +# Estrategias de carga de rutas -Understanding how and when routes and components load in Angular routing is crucial for building responsive web applications. Angular offers two primary strategies to control loading behavior: +Entender cómo y cuándo se cargan las rutas y los componentes en el routing en Angular es crucial para construir aplicaciones web con buena capacidad de respuesta. Angular ofrece dos estrategias principales para controlar el comportamiento de carga: -1. **Eagerly loaded**: Routes and components that are loaded immediately -2. **Lazily loaded**: Routes and components loaded only when needed +1. **Carga anticipada (eager)**: Rutas y componentes que se cargan de inmediato +2. **Carga diferida (lazy)**: Rutas y componentes que se cargan solo cuando se necesitan -Each approach offers distinct advantages for different scenarios. +Cada enfoque ofrece ventajas distintas según el escenario. -## Eagerly loaded components +## Componentes con carga anticipada {#eagerly-loaded-components} -When you define a route with the [`component`](api/router/Route#component) property, the referenced component is eagerly loaded as part of the same JavaScript bundle as the route configuration. +Cuando defines una ruta con la propiedad [`component`](api/router/Route#component), el componente referenciado se carga de forma anticipada como parte del mismo bundle de JavaScript que la configuración de rutas. ```ts import {Routes} from '@angular/router'; @@ -17,8 +17,8 @@ import {HomePage} from './components/home/home-page'; import {LoginPage} from './components/auth/login-page'; export const routes: Routes = [ - // HomePage and LoginPage are both directly referenced in this config, - // so their code is eagerly included in the same JavaScript bundle as this file. + // HomePage y LoginPage se referencian directamente en esta configuración, + // así que su código se incluye de forma anticipada en el mismo bundle de JavaScript que este archivo. { path: '', component: HomePage, @@ -30,13 +30,13 @@ export const routes: Routes = [ ]; ``` -Eagerly loading route components like this means that the browser has to download and parse all of the JavaScript for these components as part of your initial page load, but the components are available to Angular immediately. +Cargar los componentes de ruta de forma anticipada como en este ejemplo significa que el navegador tiene que descargar y analizar todo el JavaScript de estos componentes como parte de la carga inicial de la página, pero los componentes están disponibles para Angular de inmediato. -While including more JavaScript in your initial page load leads to slower initial load times, this can lead to more seamless transitions as the user navigates through an application. +Aunque incluir más JavaScript en la carga inicial de la página provoca tiempos de carga inicial más lentos, esto puede dar lugar a transiciones más fluidas mientras el usuario navega por la aplicación. -## Lazily loaded components and routes +## Componentes y rutas con carga diferida {#lazily-loaded-components-and-routes} -You can use the [`loadComponent`](api/router/Route#loadComponent) property to lazily load the JavaScript for a component at the point at which that route would become active. The [`loadChildren`](api/router/Route#loadChildren) property lazily loads child routes during route matching. +Puedes usar la propiedad [`loadComponent`](api/router/Route#loadComponent) para cargar de forma diferida el JavaScript de un componente en el momento en que esa ruta se activaría. La propiedad [`loadChildren`](api/router/Route#loadChildren) carga de forma diferida las rutas hijas durante la coincidencia de rutas. ```ts import {Routes} from '@angular/router'; @@ -54,15 +54,15 @@ export const routes: Routes = [ ]; ``` -The [`loadComponent`](/api/router/Route#loadComponent) and [`loadChildren`](/api/router/Route#loadChildren) properties accept a loader function that returns a Promise that resolves to an Angular component or a set of routes respectively. In most cases, this function uses the standard [JavaScript dynamic import API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import). You can, however, use any arbitrary async loader function. +Las propiedades [`loadComponent`](/api/router/Route#loadComponent) y [`loadChildren`](/api/router/Route#loadChildren) aceptan una función de carga que devuelve una Promise que se resuelve en un componente de Angular o en un conjunto de rutas, respectivamente. En la mayoría de los casos, esta función usa la [API estándar de importación dinámica de JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import). Sin embargo, puedes usar cualquier función de carga asíncrona arbitraria. -If the lazily loaded file uses a `default` export, you can return the `import()` promise directly without an additional `.then` call to select the exported class. +Si el archivo cargado de forma diferida usa una exportación `default`, puedes devolver directamente la promesa de `import()` sin una llamada adicional a `.then` para seleccionar la clase exportada. -Lazily loading routes can significantly improve the load speed of your Angular application by removing large portions of JavaScript from the initial bundle. These portions of your code compile into separate JavaScript "chunks" that the router requests only when the user visits the corresponding route. +Cargar rutas de forma diferida puede mejorar significativamente la velocidad de carga de tu aplicación Angular al eliminar grandes porciones de JavaScript del bundle inicial. Estas porciones de tu código se compilan en "chunks" de JavaScript separados que el router solicita solo cuando el usuario visita la ruta correspondiente. -## Injection context lazy loading +## Lazy loading en el contexto de inyección {#injection-context-lazy-loading} -The Router executes [`loadComponent`](/api/router/Route#loadComponent) and [`loadChildren`](/api/router/Route#loadChildren) within the **injection context of the current route**, allowing you to call [`inject`](/api/core/inject)inside these loader functions to access providers declared on that route, inherited from parent routes through hierarchical dependency injection, or available globally. This enables context-aware lazy loading. +El Router ejecuta [`loadComponent`](/api/router/Route#loadComponent) y [`loadChildren`](/api/router/Route#loadChildren) dentro del **contexto de inyección de la ruta actual**, lo que te permite llamar a [`inject`](/api/core/inject) dentro de estas funciones de carga para acceder a proveedores declarados en esa ruta, heredados de rutas padre mediante la inyección de dependencias jerárquica, o disponibles globalmente. Esto habilita un lazy loading consciente del contexto. ```ts import {Routes} from '@angular/router'; @@ -72,7 +72,7 @@ import {FeatureFlags} from './feature-flags'; export const routes: Routes = [ { path: 'dashboard', - // Runs inside the route's injection context + // Se ejecuta dentro del contexto de inyección de la ruta loadComponent: () => { const flags = inject(FeatureFlags); return flags.isPremium @@ -83,14 +83,14 @@ export const routes: Routes = [ ]; ``` -## Should I use an eager or a lazy route? +## ¿Debo usar una ruta eager o lazy? {#should-i-use-an-eager-or-a-lazy-route} -There are many factors to consider when deciding on whether a route should be eager or lazy. +Hay muchos factores a considerar al decidir si una ruta debe ser eager o lazy. -In general, eager loading is recommended for primary landing page(s) while other pages would be lazy-loaded. +En general, se recomienda la carga anticipada para la(s) página(s) de aterrizaje principal(es), mientras que las demás páginas se cargarían de forma diferida. -NOTE: While lazy routes have the upfront performance benefit of reducing the amount of initial data requested by the user, it adds future data requests that could be undesirable. This is particularly true when dealing with nested lazy loading at multiple levels, which can significantly impact performance. +NOTE: Aunque las rutas lazy tienen la ventaja inicial de rendimiento de reducir la cantidad de datos que el usuario solicita al principio, añaden solicitudes de datos futuras que podrían ser indeseables. Esto es especialmente cierto cuando se trabaja con lazy loading anidado en varios niveles, lo que puede afectar significativamente al rendimiento. -## Next steps +## Próximos pasos {#next-steps} -Learn how to [display the contents of your routes with Outlets](/guide/routing/show-routes-with-outlets). +Aprende cómo [mostrar el contenido de tus rutas con Outlets](/guide/routing/show-routes-with-outlets). diff --git a/adev-es/src/content/tools/devtools/router.en.md b/adev-es/src/content/tools/devtools/router.en.md new file mode 100644 index 00000000..1f19f856 --- /dev/null +++ b/adev-es/src/content/tools/devtools/router.en.md @@ -0,0 +1,30 @@ +# Inspect the Router Tree + +The **Router Tree** tab lets you visualize the routing tree of your application. You can explore how routes are nested and view details about specific routes. + +A screenshot of the 'Router Tree' tab in Angular DevTools showing a tree of configured routes. The active routes are highlighted in green, while inactive ones are white. + +### View route details + +When you select a specific route in the tree, Angular DevTools displays its properties in the sidebar on the right. This information includes: + +- **Path**: The URL path for the route. If the route uses a custom URL matcher, DevTools displays the **Matcher** instead. +- **Component**: The component rendered for this route. If the route is a redirect, DevTools displays the **Redirect to** target instead. +- **Path Match**: The path matching strategy (`prefix` or `full`), if configured. +- **Data**: Static data associated with the route, displayed as a JSON tree. +- **Resolvers**: Route resolvers, displayed as key-value pairs. +- **Guards**: Any guards configured on the route, grouped by type — `canActivate`, `canActivateChild`, `canDeactivate`, and `canMatch`. +- **Providers**: Route-level providers, if configured. +- **Title**: The route title, if configured. +- **RunGuardsAndResolvers**: The re-run strategy for guards and resolvers, if configured. +- **Active**: Whether this route is currently active. +- **Auxiliary**: Indicates if the route is an auxiliary route (e.g., in a named outlet). +- **Lazy**: Indicates if the route is lazily loaded. + +Note: Properties like Path Match, Data, Resolvers, Guards, Providers, Title, and RunGuardsAndResolvers only appear in the sidebar when they are configured on the selected route. + +### Navigate to a specific route + +You can easily trigger navigation directly from the DevTools. While inspecting a route's details in the right sidebar, click on the **Navigate** icon next to the path string. This triggers the Angular router to navigate to that URL in your application. + +A screenshot showing the 'Navigate to' tooltip on the route path in the 'Routes Details' sidebar. diff --git a/adev-es/src/content/tools/devtools/router.md b/adev-es/src/content/tools/devtools/router.md index 1f19f856..33454fa8 100644 --- a/adev-es/src/content/tools/devtools/router.md +++ b/adev-es/src/content/tools/devtools/router.md @@ -1,30 +1,30 @@ -# Inspect the Router Tree +# Inspeccionar el árbol del Router -The **Router Tree** tab lets you visualize the routing tree of your application. You can explore how routes are nested and view details about specific routes. +La pestaña **Router Tree** te permite visualizar el árbol de routing de tu aplicación. Puedes explorar cómo se anidan las rutas y ver los detalles de rutas específicas. -A screenshot of the 'Router Tree' tab in Angular DevTools showing a tree of configured routes. The active routes are highlighted in green, while inactive ones are white. +Una captura de pantalla de la pestaña 'Router Tree' en Angular DevTools mostrando un árbol de rutas configuradas. Las rutas activas se resaltan en verde, mientras que las inactivas están en blanco. -### View route details +### Ver los detalles de una ruta {#view-route-details} -When you select a specific route in the tree, Angular DevTools displays its properties in the sidebar on the right. This information includes: +Cuando seleccionas una ruta específica en el árbol, Angular DevTools muestra sus propiedades en la barra lateral derecha. Esta información incluye: -- **Path**: The URL path for the route. If the route uses a custom URL matcher, DevTools displays the **Matcher** instead. -- **Component**: The component rendered for this route. If the route is a redirect, DevTools displays the **Redirect to** target instead. -- **Path Match**: The path matching strategy (`prefix` or `full`), if configured. -- **Data**: Static data associated with the route, displayed as a JSON tree. -- **Resolvers**: Route resolvers, displayed as key-value pairs. -- **Guards**: Any guards configured on the route, grouped by type — `canActivate`, `canActivateChild`, `canDeactivate`, and `canMatch`. -- **Providers**: Route-level providers, if configured. -- **Title**: The route title, if configured. -- **RunGuardsAndResolvers**: The re-run strategy for guards and resolvers, if configured. -- **Active**: Whether this route is currently active. -- **Auxiliary**: Indicates if the route is an auxiliary route (e.g., in a named outlet). -- **Lazy**: Indicates if the route is lazily loaded. +- **Path**: La ruta URL de la ruta. Si la ruta usa un matcher de URL personalizado, DevTools muestra **Matcher** en su lugar. +- **Component**: El componente renderizado para esta ruta. Si la ruta es una redirección, DevTools muestra el destino de **Redirect to** en su lugar. +- **Path Match**: La estrategia de coincidencia de ruta (`prefix` o `full`), si está configurada. +- **Data**: Datos estáticos asociados a la ruta, mostrados como un árbol JSON. +- **Resolvers**: Los resolvers de la ruta, mostrados como pares clave-valor. +- **Guards**: Cualquier guard configurado en la ruta, agrupado por tipo — `canActivate`, `canActivateChild`, `canDeactivate` y `canMatch`. +- **Providers**: Proveedores a nivel de ruta, si están configurados. +- **Title**: El título de la ruta, si está configurado. +- **RunGuardsAndResolvers**: La estrategia de re-ejecución de guards y resolvers, si está configurada. +- **Active**: Si esta ruta está activa actualmente. +- **Auxiliary**: Indica si la ruta es una ruta auxiliar (por ejemplo, en un outlet con nombre). +- **Lazy**: Indica si la ruta se carga de forma diferida. -Note: Properties like Path Match, Data, Resolvers, Guards, Providers, Title, and RunGuardsAndResolvers only appear in the sidebar when they are configured on the selected route. +Note: Propiedades como Path Match, Data, Resolvers, Guards, Providers, Title y RunGuardsAndResolvers solo aparecen en la barra lateral cuando están configuradas en la ruta seleccionada. -### Navigate to a specific route +### Navegar a una ruta específica {#navigate-to-a-specific-route} -You can easily trigger navigation directly from the DevTools. While inspecting a route's details in the right sidebar, click on the **Navigate** icon next to the path string. This triggers the Angular router to navigate to that URL in your application. +Puedes activar fácilmente una navegación directamente desde DevTools. Mientras inspeccionas los detalles de una ruta en la barra lateral derecha, haz clic en el icono **Navigate** junto a la cadena de la ruta. Esto hace que el router de Angular navegue a esa URL en tu aplicación. -A screenshot showing the 'Navigate to' tooltip on the route path in the 'Routes Details' sidebar. +Una captura de pantalla mostrando el tooltip 'Navigate to' sobre la ruta en la barra lateral 'Routes Details'.