diff --git a/adev-es/src/app/routing/sub-navigation-data.ts b/adev-es/src/app/routing/sub-navigation-data.ts
index 02ca72c..9355bb0 100644
--- a/adev-es/src/app/routing/sub-navigation-data.ts
+++ b/adev-es/src/app/routing/sub-navigation-data.ts
@@ -131,57 +131,57 @@ const DOCS_SUB_NAVIGATION_DATA: NavigationItem[] = [
contentPath: 'guide/components/styling',
},
{
- label: 'Accepting data with input properties',
+ label: 'Aceptando datos con propiedades de input',
path: 'guide/components/inputs',
contentPath: 'guide/components/inputs',
},
{
- label: 'Custom events with outputs',
+ label: 'Eventos personalizados con outputs',
path: 'guide/components/outputs',
contentPath: 'guide/components/outputs',
},
{
- label: 'Content projection with ng-content',
+ label: 'Proyección de contenido con ng-content',
path: 'guide/components/content-projection',
contentPath: 'guide/components/content-projection',
},
{
- label: 'Host elements',
+ label: 'Elementos host de componentes',
path: 'guide/components/host-elements',
contentPath: 'guide/components/host-elements',
},
{
- label: 'Lifecycle',
+ label: 'Ciclo de vida del componente',
path: 'guide/components/lifecycle',
contentPath: 'guide/components/lifecycle',
},
{
- label: 'Referencing component children with queries',
+ label: 'Referenciando hijos de componentes con consultas',
path: 'guide/components/queries',
contentPath: 'guide/components/queries',
},
{
- label: 'Using DOM APIs',
+ label: 'Usando APIs del DOM',
path: 'guide/components/dom-apis',
contentPath: 'guide/components/dom-apis',
},
{
- label: 'Inheritance',
+ label: 'Herencia',
path: 'guide/components/inheritance',
contentPath: 'guide/components/inheritance',
},
{
- label: 'Programmatically rendering components',
+ label: 'Renderizado programático de componentes',
path: 'guide/components/programmatic-rendering',
contentPath: 'guide/components/programmatic-rendering',
},
{
- label: 'Advanced configuration',
+ label: 'Configuración avanzada',
path: 'guide/components/advanced-configuration',
contentPath: 'guide/components/advanced-configuration',
},
{
- label: 'Custom Elements',
+ label: 'Elementos personalizados',
path: 'guide/elements',
contentPath: 'guide/elements',
},
diff --git a/adev-es/src/content/guide/components/advanced-configuration.en.md b/adev-es/src/content/guide/components/advanced-configuration.en.md
new file mode 100644
index 0000000..4e71034
--- /dev/null
+++ b/adev-es/src/content/guide/components/advanced-configuration.en.md
@@ -0,0 +1,48 @@
+# Advanced component configuration
+
+TIP: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular.
+
+## ChangeDetectionStrategy
+
+The `@Component` decorator accepts a `changeDetection` option that controls the component's **change
+detection mode**. There are two change detection mode options.
+
+**`ChangeDetectionStrategy.Default`** is, unsurprisingly, the default strategy. In this mode,
+Angular checks whether the component's DOM needs an update whenever any activity may have occurred
+application-wide. Activities that trigger this checking include user interaction, network response,
+timers, and more.
+
+**`ChangeDetectionStrategy.OnPush`** is an optional mode that reduces the amount of checking Angular
+needs to perform. In this mode, the framework only checks if a component's DOM needs an update when:
+
+- A component input has changes as a result of a binding in a template, or
+- An event listener in this component runs
+- The component is explicitly marked for check, via `ChangeDetectorRef.markForCheck` or something which wraps it, like `AsyncPipe`.
+
+Additionally, when an OnPush component is checked, Angular _also_ checks all of its ancestor
+components, traversing upwards through the application tree.
+
+## PreserveWhitespaces
+
+By default, Angular removes and collapses superfluous whitespace in templates, most commonly from
+newlines and indentation. You can change this setting by explicitly setting `preserveWhitespaces` to
+`true` in a component's metadata.
+
+## Custom element schemas
+
+By default, Angular throws an error when it encounters an unknown HTML element. You can
+disable this behavior for a component by including `CUSTOM_ELEMENTS_SCHEMA` in the `schemas`
+property in your component metadata.
+
+```angular-ts
+import {Component, CUSTOM_ELEMENTS_SCHEMA} from '@angular/core';
+
+@Component({
+ ...,
+ schemas: [CUSTOM_ELEMENTS_SCHEMA],
+ template: ''
+})
+export class ComponentWithCustomElements { }
+```
+
+Angular does not support any other schemas at this time.
diff --git a/adev-es/src/content/guide/components/advanced-configuration.md b/adev-es/src/content/guide/components/advanced-configuration.md
index 4e71034..a683915 100644
--- a/adev-es/src/content/guide/components/advanced-configuration.md
+++ b/adev-es/src/content/guide/components/advanced-configuration.md
@@ -1,38 +1,38 @@
-# Advanced component configuration
+# Configuración avanzada de componentes
-TIP: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular.
+CONSEJO: Esta guía asume que ya has leído la [Guía de Esenciales](essentials). Lee eso primero si eres nuevo en Angular.
## ChangeDetectionStrategy
-The `@Component` decorator accepts a `changeDetection` option that controls the component's **change
-detection mode**. There are two change detection mode options.
+El decorador `@Component` acepta una opción `changeDetection` que controla el **modo de
+detección de cambios** del componente. Hay dos opciones de modo de detección de cambios.
-**`ChangeDetectionStrategy.Default`** is, unsurprisingly, the default strategy. In this mode,
-Angular checks whether the component's DOM needs an update whenever any activity may have occurred
-application-wide. Activities that trigger this checking include user interaction, network response,
-timers, and more.
+**`ChangeDetectionStrategy.Default`** es, como era de esperar, la estrategia por defecto. En este modo,
+Angular verifica si el DOM del componente necesita una actualización cada vez que cualquier actividad puede haber ocurrido
+en toda la aplicación. Las actividades que desencadenan esta verificación incluyen interacción del usuario, respuesta de red,
+temporizadores, y más.
-**`ChangeDetectionStrategy.OnPush`** is an optional mode that reduces the amount of checking Angular
-needs to perform. In this mode, the framework only checks if a component's DOM needs an update when:
+**`ChangeDetectionStrategy.OnPush`** es un modo opcional que reduce la cantidad de verificación que Angular
+necesita realizar. En este modo, el framework solo verifica si el DOM de un componente necesita una actualización cuando:
-- A component input has changes as a result of a binding in a template, or
-- An event listener in this component runs
-- The component is explicitly marked for check, via `ChangeDetectorRef.markForCheck` or something which wraps it, like `AsyncPipe`.
+- Un input del componente ha cambiado como resultado de un enlace en una plantilla, o
+- Un event listener en este componente se ejecuta
+- El componente es explícitamente marcado para verificación, a través de `ChangeDetectorRef.markForCheck` o algo que lo envuelve, como `AsyncPipe`.
-Additionally, when an OnPush component is checked, Angular _also_ checks all of its ancestor
-components, traversing upwards through the application tree.
+Además, cuando un componente OnPush es verificado, Angular _también_ verifica todos sus componentes
+ancestros, atravesando hacia arriba a través del árbol de la aplicación.
## PreserveWhitespaces
-By default, Angular removes and collapses superfluous whitespace in templates, most commonly from
-newlines and indentation. You can change this setting by explicitly setting `preserveWhitespaces` to
-`true` in a component's metadata.
+Por defecto, Angular elimina y colapsa los espacios en blanco superfluos en las plantillas, más comúnmente de
+saltos de línea e indentación. Puedes cambiar esta configuración estableciendo explícitamente `preserveWhitespaces` a
+`true` en los metadatos del componente.
-## Custom element schemas
+## Esquemas de elementos personalizados
-By default, Angular throws an error when it encounters an unknown HTML element. You can
-disable this behavior for a component by including `CUSTOM_ELEMENTS_SCHEMA` in the `schemas`
-property in your component metadata.
+Por defecto, Angular lanza un error cuando encuentra un elemento HTML desconocido. Puedes
+deshabilitar este comportamiento para un componente incluyendo `CUSTOM_ELEMENTS_SCHEMA` en la propiedad `schemas`
+en los metadatos de tu componente.
```angular-ts
import {Component, CUSTOM_ELEMENTS_SCHEMA} from '@angular/core';
@@ -45,4 +45,4 @@ import {Component, CUSTOM_ELEMENTS_SCHEMA} from '@angular/core';
export class ComponentWithCustomElements { }
```
-Angular does not support any other schemas at this time.
+Angular no soporta ningún otro esquema en este momento.
diff --git a/adev-es/src/content/guide/components/content-projection.en.md b/adev-es/src/content/guide/components/content-projection.en.md
new file mode 100644
index 0000000..efa351c
--- /dev/null
+++ b/adev-es/src/content/guide/components/content-projection.en.md
@@ -0,0 +1,245 @@
+# Content projection with ng-content
+
+TIP: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular.
+
+You often need to create components that act as containers for different types of content. For
+example, you may want to create a custom card component:
+
+```angular-ts
+@Component({
+ selector: 'custom-card',
+ template: '
',
+})
+export class CustomCard {/* ... */}
+```
+
+**You can use the `` element as a placeholder to mark where content should go**:
+
+```angular-ts
+@Component({
+ selector: 'custom-card',
+ template: '
',
+})
+export class CustomCard {/* ... */}
+```
+
+TIP: `` works similarly
+to [the native `` element](https://developer.mozilla.org/docs/Web/HTML/Element/slot),
+but with some Angular-specific functionality.
+
+When you use a component with ``, any children of the component host element are
+rendered, or **projected**, at the location of that ``:
+
+```angular-ts
+// Component source
+@Component({
+ selector: 'custom-card',
+ template: `
+
+
+```
+
+Angular refers to any children of a component passed this way as that component's **content**. This
+is distinct from the component's **view**, which refers to the elements defined in the component's
+template.
+
+**The `` element is neither a component nor DOM element**. Instead, it is a special
+placeholder that tells Angular where to render content. Angular's compiler processes
+all `` elements at build-time. You cannot insert, remove, or modify `` at
+run time. You cannot add directives, styles, or arbitrary attributes to ``.
+
+IMPORTANT: You should not conditionally include `` with `@if`, `@for`, or `@switch`. Angular always
+instantiates and creates DOM nodes for content rendered to a `` placeholder, even if
+that `` placeholder is hidden. For conditional rendering of component content,
+see [Template fragments](api/core/ng-template).
+
+## Multiple content placeholders
+
+Angular supports projecting multiple different elements into different `` placeholders
+based on CSS selector. Expanding the card example from above, you could create two placeholders for
+a card title and a card body by using the `select` attribute:
+
+```angular-ts
+@Component({
+ selector: 'card-title',
+ template: `card-title`,
+})
+export class CardTitle {}
+
+@Component({
+ selector: 'card-body',
+ template: `card-body`,
+})
+export class CardBody {}
+```
+
+```angular-ts
+
+Component({
+ selector: 'custom-card',
+ template: `
+
+
+
+
+
+ `,
+})
+export class CustomCard {}
+```
+
+```angular-ts
+
+@Component({
+ selector: 'app-root',
+ imports: [CustomCard, CardTitle, CardBody],
+ template: `
+
+ Hello
+ Welcome to the example
+
+`,
+})
+export class App {}
+```
+
+```angular-html
+
+
+
+ Hello
+
+ Welcome to the example
+
+
+```
+
+The `` placeholder supports the same CSS selectors
+as [component selectors](guide/components/selectors).
+
+If you include one or more `` placeholders with a `select` attribute and
+one `` placeholder without a `select` attribute, the latter captures all elements that
+did not match a `select` attribute:
+
+```angular-html
+
+
+
+
+
+
+
+```
+
+```angular-html
+
+
+ Hello
+
+
Welcome to the example
+
+```
+
+```angular-html
+
+
+
+ Hello
+
+
+
Welcome to the example
+
+
+```
+
+If a component does not include an `` placeholder without a `select` attribute, any
+elements that don't match one of the component's placeholders do not render into the DOM.
+
+## Fallback content
+
+Angular can show _fallback content_ for a component's `` placeholder if that component doesn't have any matching child content. You can specify fallback content by adding child content to the `` element itself.
+
+```angular-html
+
+
+
+```
+
+## Aliasing content for projection
+
+Angular supports a special attribute, `ngProjectAs`, that allows you to specify a CSS selector on
+any element. Whenever an element with `ngProjectAs` is checked against an ``
+placeholder, Angular compares against the `ngProjectAs` value instead of the element's identity:
+
+```angular-html
+
+
+
+
+
+
+```
+
+```angular-html
+
+
+
Hello
+
+
Welcome to the example
+
+```
+
+```angular-html
+
+
+
+
Hello
+
+
Welcome to the example
+
+
+```
+
+`ngProjectAs` supports only static values and cannot be bound to dynamic expressions.
diff --git a/adev-es/src/content/guide/components/content-projection.md b/adev-es/src/content/guide/components/content-projection.md
index efa351c..5d6ccd9 100644
--- a/adev-es/src/content/guide/components/content-projection.md
+++ b/adev-es/src/content/guide/components/content-projection.md
@@ -1,19 +1,19 @@
-# Content projection with ng-content
+# Proyección de contenido con ng-content
-TIP: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular.
+CONSEJO: Esta guía asume que ya has leído la [Guía de Esenciales](essentials). Lee esa primero si eres nuevo en Angular.
-You often need to create components that act as containers for different types of content. For
-example, you may want to create a custom card component:
+Frecuentemente necesitas crear componentes que actúen como contenedores para diferentes tipos de contenido. Por
+ejemplo, puedes querer crear un componente de tarjeta personalizado:
```angular-ts
@Component({
selector: 'custom-card',
- template: '
',
+ template: '
',
})
export class CustomCard {/* ... */}
```
-**You can use the `` element as a placeholder to mark where content should go**:
+**Puedes usar el elemento `` como marcador de posición para indicar dónde debe ir el contenido**:
```angular-ts
@Component({
@@ -23,15 +23,15 @@ export class CustomCard {/* ... */}
export class CustomCard {/* ... */}
```
-TIP: `` works similarly
-to [the native `` element](https://developer.mozilla.org/docs/Web/HTML/Element/slot),
-but with some Angular-specific functionality.
+CONSEJO: `` funciona de manera similar
+al [elemento nativo ``](https://developer.mozilla.org/es/docs/Web/HTML/Reference/Elements/slot),
+pero con alguna funcionalidad específica de Angular.
-When you use a component with ``, any children of the component host element are
-rendered, or **projected**, at the location of that ``:
+Cuando usas un componente con ``, cualquier hijo del elemento host del componente se
+renderiza, o **proyecta**, en la ubicación de ese ``:
```angular-ts
-// Component source
+// Código fuente del componente
@Component({
selector: 'custom-card',
template: `
@@ -44,40 +44,39 @@ export class CustomCard {/* ... */}
```
```angular-html
-
+
-
This is the projected content
+
Este es el contenido proyectado
```
```angular-html
-
+
-
This is the projected content
+
Este es el contenido proyectado
```
-Angular refers to any children of a component passed this way as that component's **content**. This
-is distinct from the component's **view**, which refers to the elements defined in the component's
-template.
+Angular se refiere a cualquier hijo de un componente pasado de esta manera como el **contenido** de ese componente. Esto
+es distinto de la **vista** del componente, que se refiere a los elementos definidos en la plantilla del componente.
-**The `` element is neither a component nor DOM element**. Instead, it is a special
-placeholder that tells Angular where to render content. Angular's compiler processes
-all `` elements at build-time. You cannot insert, remove, or modify `` at
-run time. You cannot add directives, styles, or arbitrary attributes to ``.
+**El elemento `` no es ni un componente ni un elemento DOM**. En su lugar, es un marcador de posición
+especial que le dice a Angular dónde renderizar el contenido. El compilador de Angular procesa
+todos los elementos `` en tiempo de compilación. No puedes insertar, eliminar o modificar `` en
+tiempo de ejecución. No puedes agregar directivas, estilos o atributos arbitrarios a ``.
-IMPORTANT: You should not conditionally include `` with `@if`, `@for`, or `@switch`. Angular always
-instantiates and creates DOM nodes for content rendered to a `` placeholder, even if
-that `` placeholder is hidden. For conditional rendering of component content,
-see [Template fragments](api/core/ng-template).
+IMPORTANTE: No debes incluir condicionalmente `` con `@if`, `@for` o `@switch`. Angular siempre
+instancia y crea nodos DOM para el contenido renderizado en un marcador de posición ``, incluso si
+ese marcador de posición `` está oculto. Para renderizado condicional del contenido del componente,
+consulta [Fragmentos de plantilla](api/core/ng-template).
-## Multiple content placeholders
+## Múltiples marcadores de posición de contenido
-Angular supports projecting multiple different elements into different `` placeholders
-based on CSS selector. Expanding the card example from above, you could create two placeholders for
-a card title and a card body by using the `select` attribute:
+Angular admite proyectar múltiples elementos diferentes en diferentes marcadores de posición ``
+basándose en selectores CSS. Expandiendo el ejemplo de la tarjeta de arriba, podrías crear dos marcadores de posición para
+un título de tarjeta y un cuerpo de tarjeta usando el atributo `select`:
```angular-ts
@Component({
@@ -94,7 +93,7 @@ export class CardBody {}
```
```angular-ts
-
+
Component({
selector: 'custom-card',
template: `
@@ -109,14 +108,14 @@ export class CustomCard {}
```
```angular-ts
-
+
@Component({
selector: 'app-root',
imports: [CustomCard, CardTitle, CardBody],
template: `
- Hello
- Welcome to the example
+ Hola
+ Bienvenido al ejemplo
`,
})
@@ -124,97 +123,97 @@ export class App {}
```
```angular-html
-
+
- Hello
+ Hola
- Welcome to the example
+ Bienvenido al ejemplo
```
-The `` placeholder supports the same CSS selectors
-as [component selectors](guide/components/selectors).
+El marcador de posición `` admite los mismos selectores CSS
+que los [selectores de componentes](guide/components/selectors).
-If you include one or more `` placeholders with a `select` attribute and
-one `` placeholder without a `select` attribute, the latter captures all elements that
-did not match a `select` attribute:
+Si incluyes uno o más marcadores de posición `` con un atributo `select` y
+un marcador de posición `` sin un atributo `select`, el último captura todos los elementos que
+no coincidieron con un atributo `select`:
```angular-html
-
+
-
+
```
```angular-html
-
+
- Hello
+ Hola
-
Welcome to the example
+
Bienvenido al ejemplo
```
```angular-html
-
+
- Hello
+ Hola
-
Welcome to the example
+
Bienvenido al ejemplo
```
-If a component does not include an `` placeholder without a `select` attribute, any
-elements that don't match one of the component's placeholders do not render into the DOM.
+Si un componente no incluye un marcador de posición `` sin un atributo `select`, cualquier
+elemento que no coincida con uno de los marcadores de posición del componente no se renderiza en el DOM.
-## Fallback content
+## Contenido de respaldo
-Angular can show _fallback content_ for a component's `` placeholder if that component doesn't have any matching child content. You can specify fallback content by adding child content to the `` element itself.
+Angular puede mostrar _contenido de respaldo_ para el marcador de posición `` de un componente si ese componente no tiene ningún contenido hijo coincidente. Puedes especificar contenido de respaldo agregando contenido hijo al propio elemento ``.
```angular-html
-
+
- Default Title
+ Título predeterminado
- Default Body
+ Cuerpo predeterminado
- Hello
+ Hola
- Default Body
+ Cuerpo predeterminado
```
-## Aliasing content for projection
+## Alias de contenido para proyección
-Angular supports a special attribute, `ngProjectAs`, that allows you to specify a CSS selector on
-any element. Whenever an element with `ngProjectAs` is checked against an ``
-placeholder, Angular compares against the `ngProjectAs` value instead of the element's identity:
+Angular admite un atributo especial, `ngProjectAs`, que te permite especificar un selector CSS en
+cualquier elemento. Siempre que un elemento con `ngProjectAs` se compara contra un marcador de posición ``,
+Angular compara contra el valor de `ngProjectAs` en lugar de la identidad del elemento:
```angular-html
-
+
@@ -223,23 +222,23 @@ placeholder, Angular compares against the `ngProjectAs` value instead of the ele
```
```angular-html
-
+
-
Hello
+
Hola
-
Welcome to the example
+
Bienvenido al ejemplo
```
```angular-html
-
+
-
Hello
+
Hola
-
Welcome to the example
+
Bienvenido al ejemplo
```
-`ngProjectAs` supports only static values and cannot be bound to dynamic expressions.
+`ngProjectAs` solo admite valores estáticos y no se puede enlazar a expresiones dinámicas.
diff --git a/adev-es/src/content/guide/components/dom-apis.en.md b/adev-es/src/content/guide/components/dom-apis.en.md
new file mode 100644
index 0000000..68ac11a
--- /dev/null
+++ b/adev-es/src/content/guide/components/dom-apis.en.md
@@ -0,0 +1,85 @@
+# Using DOM APIs
+
+TIP: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular.
+
+Angular handles most DOM creation, updates, and removals for you. However, you might rarely need to
+directly interact with a component's DOM. Components can inject ElementRef to get a reference to the
+component's host element:
+
+```ts
+@Component({...})
+export class ProfilePhoto {
+ constructor() {
+ const elementRef = inject(ElementRef);
+ console.log(elementRef.nativeElement);
+ }
+}
+```
+
+The `nativeElement` property references the
+host [Element](https://developer.mozilla.org/docs/Web/API/Element) instance.
+
+You can use Angular's `afterEveryRender` and `afterNextRender` functions to register a **render
+callback** that runs when Angular has finished rendering the page.
+
+```ts
+@Component({...})
+export class ProfilePhoto {
+ constructor() {
+ const elementRef = inject(ElementRef);
+ afterEveryRender(() => {
+ // Focus the first input element in this component.
+ elementRef.nativeElement.querySelector('input')?.focus();
+ });
+ }
+}
+```
+
+`afterEveryRender` and `afterNextRender` must be called in an _injection context_, typically a
+component's constructor.
+
+**Avoid direct DOM manipulation whenever possible.** Always prefer expressing your DOM's structure
+in component templates and updating that DOM with bindings.
+
+**Render callbacks never run during server-side rendering or build-time pre-rendering.**
+
+**Never directly manipulate the DOM inside of other Angular lifecycle hooks**. Angular does not
+guarantee that a component's DOM is fully rendered at any point other than in render callbacks.
+Further, reading or modifying the DOM during other lifecycle hooks can negatively impact page
+performance by
+causing [layout thrashing](https://web.dev/avoid-large-complex-layouts-and-layout-thrashing).
+
+## Using a component's renderer
+
+Components can inject an instance of `Renderer2` to perform certain DOM manipulations that are tied
+to other Angular features.
+
+Any DOM elements created by a component's `Renderer2` participate in that
+component's [style encapsulation](guide/components/styling#style-scoping).
+
+Certain `Renderer2` APIs also tie into Angular's animation system. You can use the `setProperty`
+method to update synthetic animation properties and the `listen` method to add event listeners for
+synthetic animation events. See the [Animations](guide/animations) guide for details.
+
+Aside from these two narrow use-cases, there is no difference between using `Renderer2` and native
+DOM APIs. `Renderer2` APIs do not support DOM manipulation in server-side rendering or build-time
+pre-rendering contexts.
+
+## When to use DOM APIs
+
+While Angular handles most rendering concerns, some behaviors may still require using DOM APIs. Some
+common use cases include:
+
+- Managing element focus
+- Measuring element geometry, such as with `getBoundingClientRect`
+- Reading an element's text content
+- Setting up native observers such
+ as [`MutationObserver`](https://developer.mozilla.org/docs/Web/API/MutationObserver),
+ [`ResizeObserver`](https://developer.mozilla.org/docs/Web/API/ResizeObserver), or
+ [`IntersectionObserver`](https://developer.mozilla.org/docs/Web/API/Intersection_Observer_API).
+
+Avoid inserting, removing, and modifying DOM elements. In particular, **never directly set an
+element's `innerHTML` property**, which can make your application vulnerable
+to [cross-site scripting (XSS) exploits](https://developer.mozilla.org/docs/Glossary/Cross-site_scripting).
+Angular's template bindings, including bindings for `innerHTML`, include safeguards that help
+protect against XSS attacks. See the [Security guide](best-practices/security) for details.
diff --git a/adev-es/src/content/guide/components/dom-apis.md b/adev-es/src/content/guide/components/dom-apis.md
index 68ac11a..318a369 100644
--- a/adev-es/src/content/guide/components/dom-apis.md
+++ b/adev-es/src/content/guide/components/dom-apis.md
@@ -1,10 +1,10 @@
-# Using DOM APIs
+# Usando APIs del DOM
-TIP: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular.
+CONSEJO: Esta guía asume que ya has leído la [Guía de Esenciales](essentials). Lee esa primero si eres nuevo en Angular.
-Angular handles most DOM creation, updates, and removals for you. However, you might rarely need to
-directly interact with a component's DOM. Components can inject ElementRef to get a reference to the
-component's host element:
+Angular maneja la mayoría de la creación, actualización y eliminación del DOM por ti. Sin embargo, raramente podrías necesitar
+interactuar directamente con el DOM de un componente. Los componentes pueden inyectar ElementRef para obtener una referencia al
+elemento host del componente:
```ts
@Component({...})
@@ -16,11 +16,11 @@ export class ProfilePhoto {
}
```
-The `nativeElement` property references the
-host [Element](https://developer.mozilla.org/docs/Web/API/Element) instance.
+La propiedad `nativeElement` hace referencia a la instancia del
+[Element](https://developer.mozilla.org/es/docs/Web/API/Element) host.
-You can use Angular's `afterEveryRender` and `afterNextRender` functions to register a **render
-callback** that runs when Angular has finished rendering the page.
+Puedes usar las funciones `afterEveryRender` y `afterNextRender` de Angular para registrar un **callback de renderizado**
+que se ejecuta cuando Angular ha terminado de renderizar la página.
```ts
@Component({...})
@@ -28,58 +28,57 @@ export class ProfilePhoto {
constructor() {
const elementRef = inject(ElementRef);
afterEveryRender(() => {
- // Focus the first input element in this component.
+ // Enfoca el primer elemento input en este componente.
elementRef.nativeElement.querySelector('input')?.focus();
});
}
}
```
-`afterEveryRender` and `afterNextRender` must be called in an _injection context_, typically a
-component's constructor.
+`afterEveryRender` y `afterNextRender` deben ser llamados en un _contexto de inyección_, típicamente el
+constructor de un componente.
-**Avoid direct DOM manipulation whenever possible.** Always prefer expressing your DOM's structure
-in component templates and updating that DOM with bindings.
+**Evita la manipulación directa del DOM siempre que sea posible.** Siempre prefiere expresar la estructura de tu DOM
+en plantillas de componentes y actualizar ese DOM con enlaces.
-**Render callbacks never run during server-side rendering or build-time pre-rendering.**
+**Los callbacks de renderizado nunca se ejecutan durante el renderizado del lado del servidor o el pre-renderizado en tiempo de compilación.**
-**Never directly manipulate the DOM inside of other Angular lifecycle hooks**. Angular does not
-guarantee that a component's DOM is fully rendered at any point other than in render callbacks.
-Further, reading or modifying the DOM during other lifecycle hooks can negatively impact page
-performance by
-causing [layout thrashing](https://web.dev/avoid-large-complex-layouts-and-layout-thrashing).
+**Nunca manipules directamente el DOM dentro de otros hooks de ciclo de vida de Angular**. Angular no
+garantiza que el DOM de un componente esté completamente renderizado en ningún punto que no sea en los callbacks de renderizado.
+Además, leer o modificar el DOM durante otros hooks de ciclo de vida puede impactar negativamente el rendimiento de la página
+causando [layout thrashing](https://web.dev/avoid-large-complex-layouts-and-layout-thrashing).
-## Using a component's renderer
+## Usar el renderer de un componente
-Components can inject an instance of `Renderer2` to perform certain DOM manipulations that are tied
-to other Angular features.
+Los componentes pueden inyectar una instancia de `Renderer2` para realizar ciertas manipulaciones del DOM que están vinculadas
+a otras características de Angular.
-Any DOM elements created by a component's `Renderer2` participate in that
-component's [style encapsulation](guide/components/styling#style-scoping).
+Cualquier elemento DOM creado por el `Renderer2` de un componente participa en la
+[encapsulación de estilos](guide/components/styling#style-scoping) de ese componente.
-Certain `Renderer2` APIs also tie into Angular's animation system. You can use the `setProperty`
-method to update synthetic animation properties and the `listen` method to add event listeners for
-synthetic animation events. See the [Animations](guide/animations) guide for details.
+Ciertas APIs de `Renderer2` también se vinculan al sistema de animaciones de Angular. Puedes usar el método `setProperty`
+para actualizar propiedades de animación sintéticas y el método `listen` para agregar event listeners para
+eventos de animación sintéticos. Consulta la guía de [Animaciones](guide/animations) para más detalles.
-Aside from these two narrow use-cases, there is no difference between using `Renderer2` and native
-DOM APIs. `Renderer2` APIs do not support DOM manipulation in server-side rendering or build-time
-pre-rendering contexts.
+Aparte de estos dos casos de uso específicos, no hay diferencia entre usar `Renderer2` y las APIs nativas del DOM.
+Las APIs de `Renderer2` no admiten manipulación del DOM en contextos de renderizado del lado del servidor o
+pre-renderizado en tiempo de compilación.
-## When to use DOM APIs
+## Cuándo usar APIs del DOM
-While Angular handles most rendering concerns, some behaviors may still require using DOM APIs. Some
-common use cases include:
+Aunque Angular maneja la mayoría de las preocupaciones de renderizado, algunos comportamientos pueden requerir el uso de APIs del DOM. Algunos
+casos de uso comunes incluyen:
-- Managing element focus
-- Measuring element geometry, such as with `getBoundingClientRect`
-- Reading an element's text content
-- Setting up native observers such
- as [`MutationObserver`](https://developer.mozilla.org/docs/Web/API/MutationObserver),
- [`ResizeObserver`](https://developer.mozilla.org/docs/Web/API/ResizeObserver), or
- [`IntersectionObserver`](https://developer.mozilla.org/docs/Web/API/Intersection_Observer_API).
+- Gestionar el foco de elementos
+- Medir la geometría de elementos, como con `getBoundingClientRect`
+- Leer el contenido de texto de un elemento
+- Configurar observadores nativos como
+ [`MutationObserver`](https://developer.mozilla.org/es/docs/Web/API/MutationObserver),
+ [`ResizeObserver`](https://developer.mozilla.org/docs/Web/API/ResizeObserver) o
+ [`IntersectionObserver`](https://developer.mozilla.org/es/docs/Web/API/Intersection_Observer_API).
-Avoid inserting, removing, and modifying DOM elements. In particular, **never directly set an
-element's `innerHTML` property**, which can make your application vulnerable
-to [cross-site scripting (XSS) exploits](https://developer.mozilla.org/docs/Glossary/Cross-site_scripting).
-Angular's template bindings, including bindings for `innerHTML`, include safeguards that help
-protect against XSS attacks. See the [Security guide](best-practices/security) for details.
+Evita insertar, eliminar y modificar elementos del DOM. En particular, **nunca establezcas directamente la
+propiedad `innerHTML` de un elemento**, lo cual puede hacer que tu aplicación sea vulnerable
+a [ataques de cross-site scripting (XSS)](https://developer.mozilla.org/es/docs/Glossary/Cross-site_scripting).
+Los enlaces de plantilla de Angular, incluyendo los enlaces para `innerHTML`, incluyen salvaguardas que ayudan
+a proteger contra ataques XSS. Consulta la [guía de Seguridad](best-practices/security) para más detalles.
diff --git a/adev-es/src/content/guide/components/host-elements.en.md b/adev-es/src/content/guide/components/host-elements.en.md
new file mode 100644
index 0000000..38f5080
--- /dev/null
+++ b/adev-es/src/content/guide/components/host-elements.en.md
@@ -0,0 +1,187 @@
+# Component host elements
+
+TIP: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular.
+
+Angular creates an instance of a component for every HTML element that matches the component's
+selector. The DOM element that matches a component's selector is that component's **host element**.
+The contents of a component's template are rendered inside its host element.
+
+```angular-ts
+// Component source
+@Component({
+ selector: 'profile-photo',
+ template: `
+
+ `,
+})
+export class ProfilePhoto {}
+```
+
+```angular-html
+
+
Your profile photo
+
+
+```
+
+```angular-html
+
+
Your profile photo
+
+
+
+
+```
+
+In the above example, `` is the host element of the `ProfilePhoto` component.
+
+## Binding to the host element
+
+A component can bind properties, attributes, styles and events to its host element. This behaves
+identically to bindings on elements inside the component's template, but instead defined with
+the `host` property in the `@Component` decorator:
+
+```angular-ts
+@Component({
+ ...,
+ host: {
+ 'role': 'slider',
+ '[attr.aria-valuenow]': 'value',
+ '[class.active]': 'isActive()',
+ '[style.background]' : `hasError() ? 'red' : 'green'`,
+ '[tabIndex]': 'disabled ? -1 : 0',
+ '(keydown)': 'updateValue($event)',
+ },
+})
+export class CustomSlider {
+ value: number = 0;
+ disabled: boolean = false;
+ isActive = signal(false);
+ hasError = signal(false);
+ updateValue(event: KeyboardEvent) { /* ... */ }
+
+ /* ... */
+}
+```
+
+## The `@HostBinding` and `@HostListener` decorators
+
+You can alternatively bind to the host element by applying the `@HostBinding` and `@HostListener`
+decorator to class members.
+
+`@HostBinding` lets you bind host properties and attributes to properties and getters:
+
+```ts
+@Component({
+ /* ... */
+})
+export class CustomSlider {
+ @HostBinding('attr.aria-valuenow')
+ value: number = 0;
+
+ @HostBinding('tabIndex')
+ get tabIndex() {
+ return this.disabled ? -1 : 0;
+ }
+
+ /* ... */
+}
+```
+
+`@HostListener` lets you bind event listeners to the host element. The decorator accepts an event
+name and an optional array of arguments:
+
+```ts
+export class CustomSlider {
+ @HostListener('keydown', ['$event'])
+ updateValue(event: KeyboardEvent) {
+ /* ... */
+ }
+}
+```
+
+
+ **Always prefer using the `host` property over `@HostBinding` and `@HostListener`.** These
+decorators exist exclusively for backwards compatibility.
+
+
+## Binding collisions
+
+When you use a component in a template, you can add bindings to that component instance's element.
+The component may _also_ define host bindings for the same properties or attributes.
+
+```angular-ts
+@Component({
+ ...,
+ host: {
+ 'role': 'presentation',
+ '[id]': 'id',
+ }
+})
+export class ProfilePhoto { /* ... */ }
+```
+
+```angular-html
+
+```
+
+In cases like this, the following rules determine which value wins:
+
+- If both values are static, the instance binding wins.
+- If one value is static and the other dynamic, the dynamic value wins.
+- If both values are dynamic, the component's host binding wins.
+
+## Styling with CSS custom properties
+
+Developers often rely on [CSS Custom Properties](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_cascading_variables/Using_CSS_custom_properties) to enable a flexible configuration of their component's styles.
+You can set such custom properties on a host element with a [style binding][style binding](guide/templates/binding#css-style-properties).
+
+```angular-ts
+@Component({
+ /* ... */
+ host: {
+ '[style.--my-background]': 'color()',
+ }
+})
+export class MyComponent {
+ color = signal('lightgreen');
+}
+```
+
+In this example, the `--my-background` CSS custom property is bound to the `color` signal. The value of the custom property will automatically update whenever the `color` signal changes. This will affect the current component and all its children that rely on this custom property.
+
+### Setting custom properties on children compoents
+
+Alternatively, it is also possible to set css custom properties on the host element of children components with a [style binding](guide/templates/binding#css-style-properties).
+
+```angular-ts
+@Component({
+ selector: 'my-component',
+ template: ``,
+})
+export class MyComponent {
+ color = signal('lightgreen');
+}
+```
+
+## Injecting host element attributes
+
+Components and directives can read static attributes from their host element by using `HostAttributeToken` together with the [`inject`](api/core/inject) function.
+
+```ts
+import { Component, HostAttributeToken, inject } from '@angular/core';
+
+@Component({
+ selector: 'app-button',
+ ...,
+})
+export class Button {
+ variation = inject(new HostAttributeToken('variation'));
+}
+```
+
+```angular-html
+Click me
+```
+
+HELPFUL: `HostAttributeToken` throws an error if the attribute is missing, unless the injection is marked as optional.
diff --git a/adev-es/src/content/guide/components/host-elements.md b/adev-es/src/content/guide/components/host-elements.md
index 38f5080..920412b 100644
--- a/adev-es/src/content/guide/components/host-elements.md
+++ b/adev-es/src/content/guide/components/host-elements.md
@@ -1,45 +1,45 @@
-# Component host elements
+# Elementos host de componentes
-TIP: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular.
+CONSEJO: Esta guía asume que ya has leído la [Guía de Esenciales](essentials). Lee esa primero si eres nuevo en Angular.
-Angular creates an instance of a component for every HTML element that matches the component's
-selector. The DOM element that matches a component's selector is that component's **host element**.
-The contents of a component's template are rendered inside its host element.
+Angular crea una instancia de un componente para cada elemento HTML que coincide con el
+selector del componente. El elemento DOM que coincide con el selector de un componente es el **elemento host** de ese componente.
+El contenido de la plantilla de un componente se renderiza dentro de su elemento host.
```angular-ts
-// Component source
+// Código fuente del componente
@Component({
selector: 'profile-photo',
template: `
-
+
`,
})
export class ProfilePhoto {}
```
```angular-html
-
-
Your profile photo
+
+
Tu foto de perfil
-
+
```
```angular-html
-
-
Your profile photo
+
+
Tu foto de perfil
-
+
-
+
```
-In the above example, `` is the host element of the `ProfilePhoto` component.
+En el ejemplo anterior, `` es el elemento host del componente `ProfilePhoto`.
-## Binding to the host element
+## Enlazar al elemento host
-A component can bind properties, attributes, styles and events to its host element. This behaves
-identically to bindings on elements inside the component's template, but instead defined with
-the `host` property in the `@Component` decorator:
+Un componente puede enlazar propiedades, atributos, estilos y eventos a su elemento host. Esto se comporta
+de manera idéntica a los enlaces en elementos dentro de la plantilla del componente, pero en su lugar se define con
+la propiedad `host` en el decorador `@Component`:
```angular-ts
@Component({
@@ -64,12 +64,12 @@ export class CustomSlider {
}
```
-## The `@HostBinding` and `@HostListener` decorators
+## Los decoradores `@HostBinding` y `@HostListener`
-You can alternatively bind to the host element by applying the `@HostBinding` and `@HostListener`
-decorator to class members.
+Alternativamente puedes enlazar al elemento host aplicando los decoradores `@HostBinding` y `@HostListener`
+a los miembros de la clase.
-`@HostBinding` lets you bind host properties and attributes to properties and getters:
+`@HostBinding` te permite enlazar propiedades y atributos del host a propiedades y getters:
```ts
@Component({
@@ -88,8 +88,8 @@ export class CustomSlider {
}
```
-`@HostListener` lets you bind event listeners to the host element. The decorator accepts an event
-name and an optional array of arguments:
+`@HostListener` te permite enlazar event listeners al elemento host. El decorador acepta un nombre de evento
+y un array opcional de argumentos:
```ts
export class CustomSlider {
@@ -100,15 +100,15 @@ export class CustomSlider {
}
```
-
- **Always prefer using the `host` property over `@HostBinding` and `@HostListener`.** These
-decorators exist exclusively for backwards compatibility.
+
+ **Siempre prefiere usar la propiedad `host` sobre `@HostBinding` y `@HostListener`.** Estos
+decoradores existen exclusivamente por compatibilidad hacia atrás.
-## Binding collisions
+## Colisiones de enlaces
-When you use a component in a template, you can add bindings to that component instance's element.
-The component may _also_ define host bindings for the same properties or attributes.
+Cuando usas un componente en una plantilla, puedes agregar enlaces al elemento de esa instancia del componente.
+El componente _también_ puede definir enlaces host para las mismas propiedades o atributos.
```angular-ts
@Component({
@@ -125,16 +125,16 @@ export class ProfilePhoto { /* ... */ }
```
-In cases like this, the following rules determine which value wins:
+En casos como este, las siguientes reglas determinan qué valor gana:
-- If both values are static, the instance binding wins.
-- If one value is static and the other dynamic, the dynamic value wins.
-- If both values are dynamic, the component's host binding wins.
+- Si ambos valores son estáticos, el enlace de la instancia gana.
+- Si un valor es estático y el otro dinámico, el valor dinámico gana.
+- Si ambos valores son dinámicos, el enlace host del componente gana.
-## Styling with CSS custom properties
+## Estilizar con propiedades personalizadas CSS
-Developers often rely on [CSS Custom Properties](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_cascading_variables/Using_CSS_custom_properties) to enable a flexible configuration of their component's styles.
-You can set such custom properties on a host element with a [style binding][style binding](guide/templates/binding#css-style-properties).
+Los desarrolladores frecuentemente dependen de [Propiedades Personalizadas CSS](https://developer.mozilla.org/es/docs/Web/CSS/Guides/Cascading_variables/Using_custom_properties) para habilitar una configuración flexible de los estilos de sus componentes.
+Puedes establecer tales propiedades personalizadas en un elemento host con un [enlace de estilo](guide/templates/binding#css-style-properties).
```angular-ts
@Component({
@@ -148,11 +148,11 @@ export class MyComponent {
}
```
-In this example, the `--my-background` CSS custom property is bound to the `color` signal. The value of the custom property will automatically update whenever the `color` signal changes. This will affect the current component and all its children that rely on this custom property.
+En este ejemplo, la propiedad personalizada CSS `--my-background` está enlazada a la signal `color`. El valor de la propiedad personalizada se actualizará automáticamente cada vez que la signal `color` cambie. Esto afectará al componente actual y a todos sus hijos que dependan de esta propiedad personalizada.
-### Setting custom properties on children compoents
+### Establecer propiedades personalizadas en componentes hijos
-Alternatively, it is also possible to set css custom properties on the host element of children components with a [style binding](guide/templates/binding#css-style-properties).
+Alternativamente, también es posible establecer propiedades personalizadas CSS en el elemento host de componentes hijos con un [enlace de estilo](guide/templates/binding#css-style-properties).
```angular-ts
@Component({
@@ -164,9 +164,9 @@ export class MyComponent {
}
```
-## Injecting host element attributes
+## Inyectar atributos del elemento host
-Components and directives can read static attributes from their host element by using `HostAttributeToken` together with the [`inject`](api/core/inject) function.
+Los componentes y directivas pueden leer atributos estáticos de su elemento host usando `HostAttributeToken` junto con la función [`inject`](api/core/inject).
```ts
import { Component, HostAttributeToken, inject } from '@angular/core';
@@ -181,7 +181,7 @@ export class Button {
```
```angular-html
-Click me
+Haz clic aquí
```
-HELPFUL: `HostAttributeToken` throws an error if the attribute is missing, unless the injection is marked as optional.
+ÚTIL: `HostAttributeToken` lanza un error si el atributo falta, a menos que la inyección esté marcada como opcional.
diff --git a/adev-es/src/content/guide/components/importing.en.md b/adev-es/src/content/guide/components/importing.en.md
new file mode 100644
index 0000000..a3bbf85
--- /dev/null
+++ b/adev-es/src/content/guide/components/importing.en.md
@@ -0,0 +1,35 @@
+# Importing and using components
+
+Tip: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular.
+
+Angular supports two ways of making a component available to other components: as a standalone component or in an `NgModule`.
+
+## Standalone components
+
+A **standalone component** is a component that sets `standalone: true` in its component metadata.
+Standalone components directly import other components, directives, and pipes used in their
+templates:
+
+
+@Component({
+ standalone: true,
+ selector: 'profile-photo',
+})
+export class ProfilePhoto { }
+
+@Component({
+ standalone: true,
+ imports: [ProfilePhoto],
+ template: ``
+})
+export class UserProfile { }
+
+
+Standalone components are directly importable into other standalone components.
+
+The Angular team recommends using standalone components for all new development.
+
+## NgModules
+
+Angular code that predates standalone components uses `NgModule` as a mechanism for importing and
+using other components. See the full [`NgModule` guide](guide/ngmodules) for details.
diff --git a/adev-es/src/content/guide/components/importing.md b/adev-es/src/content/guide/components/importing.md
index a3bbf85..9665bcf 100644
--- a/adev-es/src/content/guide/components/importing.md
+++ b/adev-es/src/content/guide/components/importing.md
@@ -1,14 +1,14 @@
-# Importing and using components
+# Importar y usar componentes
-Tip: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular.
+CONSEJO: Esta guía asume que ya has leído la [Guía de Esenciales](essentials). Lee esa primero si eres nuevo en Angular.
-Angular supports two ways of making a component available to other components: as a standalone component or in an `NgModule`.
+Angular admite dos formas de hacer que un componente esté disponible para otros componentes: como componente standalone o en un `NgModule`.
-## Standalone components
+## Componentes standalone
-A **standalone component** is a component that sets `standalone: true` in its component metadata.
-Standalone components directly import other components, directives, and pipes used in their
-templates:
+Un **componente standalone** es un componente que establece `standalone: true` en los metadatos de su componente.
+Los componentes standalone importan directamente otros componentes, directivas y pipes usados en sus
+plantillas:
@Component({
@@ -25,11 +25,11 @@ export class ProfilePhoto { }
export class UserProfile { }
-Standalone components are directly importable into other standalone components.
+Los componentes standalone son directamente importables en otros componentes standalone.
-The Angular team recommends using standalone components for all new development.
+El equipo de Angular recomienda usar componentes standalone para todo desarrollo nuevo.
## NgModules
-Angular code that predates standalone components uses `NgModule` as a mechanism for importing and
-using other components. See the full [`NgModule` guide](guide/ngmodules) for details.
+El código de Angular anterior a los componentes standalone usa `NgModule` como mecanismo para importar y
+usar otros componentes. Consulta la [guía completa de `NgModule`](guide/ngmodules) para más detalles.
diff --git a/adev-es/src/content/guide/components/inheritance.en.md b/adev-es/src/content/guide/components/inheritance.en.md
new file mode 100644
index 0000000..b11af7e
--- /dev/null
+++ b/adev-es/src/content/guide/components/inheritance.en.md
@@ -0,0 +1,108 @@
+# Inheritance
+
+TIP: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular.
+
+Angular components are TypeScript classes and participate in standard JavaScript inheritance
+semantics.
+
+A component can extend any base class:
+
+```ts
+export class ListboxBase {
+ value: string;
+}
+
+@Component({ ... })
+export class CustomListbox extends ListboxBase {
+ // CustomListbox inherits the `value` property.
+}
+```
+
+## Extending other components and directives
+
+When a component extends another component or a directive, it inherits some of the metadata defined in
+the base class's decorator and the base class's decorated members. This includes
+host bindings, inputs, outputs, lifecycle methods.
+
+```angular-ts
+@Component({
+ selector: 'base-listbox',
+ template: `
+ ...
+ `,
+ host: {
+ '(keydown)': 'handleKey($event)',
+ },
+})
+export class ListboxBase {
+ value = input.required();
+ handleKey(event: KeyboardEvent) {
+ /* ... */
+ }
+}
+
+@Component({
+ selector: 'custom-listbox',
+ template: `
+ ...
+ `,
+ host: {
+ '(click)': 'focusActiveOption()',
+ },
+})
+export class CustomListbox extends ListboxBase {
+ disabled = input(false);
+ focusActiveOption() {
+ /* ... */
+ }
+}
+```
+
+In the example above, `CustomListbox` inherits all the information associated with `ListboxBase`,
+overriding the selector and template with its own values. `CustomListbox` has two inputs (`value`
+and `disabled`) and two event listeners (`keydown` and `click`).
+
+Child classes end up with the _union_ of all of their ancestors' inputs, outputs, and host bindings
+and their own.
+
+### Forwarding injected dependencies
+
+If a base class injects dependencies as constructor parameters, the child class must explicitly class these dependencies to `super`.
+
+```ts
+@Component({ ... })
+export class ListboxBase {
+ constructor(private element: ElementRef) { }
+}
+
+@Component({ ... })
+export class CustomListbox extends ListboxBase {
+ constructor(element: ElementRef) {
+ super(element);
+ }
+}
+```
+
+### Overriding lifecycle methods
+
+If a base class defines a lifecycle method, such as `ngOnInit`, a child class that also
+implements `ngOnInit` _overrides_ the base class's implementation. If you want to preserve the base
+class's lifecycle method, explicitly call the method with `super`:
+
+```ts
+@Component({ ... })
+export class ListboxBase {
+ protected isInitialized = false;
+ ngOnInit() {
+ this.isInitialized = true;
+ }
+}
+
+@Component({ ... })
+export class CustomListbox extends ListboxBase {
+ override ngOnInit() {
+ super.ngOnInit();
+ /* ... */
+ }
+}
+```
diff --git a/adev-es/src/content/guide/components/inheritance.md b/adev-es/src/content/guide/components/inheritance.md
index b11af7e..51fc165 100644
--- a/adev-es/src/content/guide/components/inheritance.md
+++ b/adev-es/src/content/guide/components/inheritance.md
@@ -1,11 +1,10 @@
-# Inheritance
+# Herencia
-TIP: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular.
+CONSEJO: Esta guía asume que ya has leído la [Guía de Esenciales](essentials). Lee esa primero si eres nuevo en Angular.
-Angular components are TypeScript classes and participate in standard JavaScript inheritance
-semantics.
+Los componentes de Angular son clases TypeScript y participan en la semántica de herencia estándar de JavaScript.
-A component can extend any base class:
+Un componente puede extender cualquier clase base:
```ts
export class ListboxBase {
@@ -14,15 +13,15 @@ export class ListboxBase {
@Component({ ... })
export class CustomListbox extends ListboxBase {
- // CustomListbox inherits the `value` property.
+ // CustomListbox hereda la propiedad `value`.
}
```
-## Extending other components and directives
+## Extender otros componentes y directivas
-When a component extends another component or a directive, it inherits some of the metadata defined in
-the base class's decorator and the base class's decorated members. This includes
-host bindings, inputs, outputs, lifecycle methods.
+Cuando un componente extiende otro componente o una directiva, hereda algunos de los metadatos definidos en
+el decorador de la clase base y los miembros decorados de la clase base. Esto incluye
+enlaces host, inputs, outputs, métodos de ciclo de vida.
```angular-ts
@Component({
@@ -58,16 +57,16 @@ export class CustomListbox extends ListboxBase {
}
```
-In the example above, `CustomListbox` inherits all the information associated with `ListboxBase`,
-overriding the selector and template with its own values. `CustomListbox` has two inputs (`value`
-and `disabled`) and two event listeners (`keydown` and `click`).
+En el ejemplo anterior, `CustomListbox` hereda toda la información asociada con `ListboxBase`,
+sobrescribiendo el selector y la plantilla con sus propios valores. `CustomListbox` tiene dos inputs (`value`
+y `disabled`) y dos event listeners (`keydown` y `click`).
-Child classes end up with the _union_ of all of their ancestors' inputs, outputs, and host bindings
-and their own.
+Las clases hijas terminan con la _unión_ de todos los inputs, outputs y enlaces host de sus ancestros
+y los suyos propios.
-### Forwarding injected dependencies
+### Reenviar dependencias inyectadas
-If a base class injects dependencies as constructor parameters, the child class must explicitly class these dependencies to `super`.
+Si una clase base inyecta dependencias como parámetros del constructor, la clase hija debe pasar explícitamente estas dependencias a `super`.
```ts
@Component({ ... })
@@ -83,11 +82,11 @@ export class CustomListbox extends ListboxBase {
}
```
-### Overriding lifecycle methods
+### Sobrescribir métodos de ciclo de vida
-If a base class defines a lifecycle method, such as `ngOnInit`, a child class that also
-implements `ngOnInit` _overrides_ the base class's implementation. If you want to preserve the base
-class's lifecycle method, explicitly call the method with `super`:
+Si una clase base define un método de ciclo de vida, como `ngOnInit`, una clase hija que también
+implementa `ngOnInit` _sobrescribe_ la implementación de la clase base. Si quieres preservar el
+método de ciclo de vida de la clase base, llama explícitamente al método con `super`:
```ts
@Component({ ... })
diff --git a/adev-es/src/content/guide/components/inputs.en.md b/adev-es/src/content/guide/components/inputs.en.md
new file mode 100644
index 0000000..73651d7
--- /dev/null
+++ b/adev-es/src/content/guide/components/inputs.en.md
@@ -0,0 +1,399 @@
+# Accepting data with input properties
+
+TIP: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular.
+
+TIP: If you're familiar with other web frameworks, input properties are similar to _props_.
+
+When you use a component, you commonly want to pass some data to it. A component specifies the data that it accepts by declaring
+**inputs**:
+
+```ts {highlight:[5]}
+import {Component, input} from '@angular/core';
+
+@Component({/*...*/})
+export class CustomSlider {
+ // Declare an input named 'value' with a default value of zero.
+ value = input(0);
+}
+```
+
+This lets you bind to the property in a template:
+
+```angular-html
+
+```
+
+If an input has a default value, TypeScript infers the type from the default value:
+
+```ts
+@Component({/*...*/})
+export class CustomSlider {
+ // TypeScript infers that this input is a number, returning InputSignal.
+ value = input(0);
+}
+```
+
+You can explicitly declare a type for the input by specifying a generic parameter to the function.
+
+If an input without a default value is not set, its value is `undefined`:
+
+```ts
+@Component({/*...*/})
+export class CustomSlider {
+ // Produces an InputSignal because `value` may not be set.
+ value = input();
+}
+```
+
+**Angular records inputs statically at compile-time**. Inputs cannot be added or removed at run-time.
+
+The `input` function has special meaning to the Angular compiler. **You can exclusively call `input` in component and directive property initializers.**
+
+When extending a component class, **inputs are inherited by the child class.**
+
+**Input names are case-sensitive.**
+
+## Reading inputs
+
+The `input` function returns an `InputSignal`. You can read the value by calling the signal:
+
+```ts {highlight:[5]}
+import {Component, input, computed} from '@angular/core';
+
+@Component({/*...*/})
+export class CustomSlider {
+ // Declare an input named 'value' with a default value of zero.
+ value = input(0);
+
+ // Create a computed expression that reads the value input
+ label = computed(() => `The slider's value is ${this.value()}`);
+}
+```
+
+Signals created by the `input` function are read-only.
+
+## Required inputs
+
+You can declare that an input is `required` by calling `input.required` instead of `input`:
+
+```ts {highlight:[3]}
+@Component({/*...*/})
+export class CustomSlider {
+ // Declare a required input named value. Returns an `InputSignal`.
+ value = input.required();
+}
+```
+
+Angular enforces that required inputs _must_ be set when the component is used in a template. If you try to use a component without specifying all of its required inputs, Angular reports an error at build-time.
+
+Required inputs do not automatically include `undefined` in the generic parameter of the returned `InputSignal`.
+
+## Configuring inputs
+
+The `input` function accepts a config object as a second parameter that lets you change the way that input works.
+
+### Input transforms
+
+You can specify a `transform` function to change the value of an input when it's set by Angular.
+
+```ts {highlight:[6]}
+@Component({
+ selector: 'custom-slider',
+ /*...*/
+})
+export class CustomSlider {
+ label = input('', {transform: trimString});
+}
+
+function trimString(value: string | undefined): string {
+ return value?.trim() ?? '';
+}
+```
+
+```angular-html
+
+```
+
+In the example above, whenever the value of `systemVolume` changes, Angular runs `trimString` and sets `label` to the result.
+
+The most common use-case for input transforms is to accept a wider range of value types in templates, often including `null` and `undefined`.
+
+**Input transform function must be statically analyzable at build-time.** You cannot set transform functions conditionally or as the result of an expression evaluation.
+
+**Input transform functions should always be [pure functions](https://en.wikipedia.org/wiki/Pure_function).** Relying on state outside the transform function can lead to unpredictable behavior.
+
+#### Type checking
+
+When you specify an input transform, the type of the transform function's parameter determines the types of values that can be set to the input in a template.
+
+```ts
+@Component({/*...*/})
+export class CustomSlider {
+ widthPx = input('', {transform: appendPx});
+}
+
+function appendPx(value: number): string {
+ return `${value}px`;
+}
+```
+
+In the example above, the `widthPx` input accepts a `number` while the `InputSignal` property returns a `string`.
+
+#### Built-in transformations
+
+Angular includes two built-in transform functions for the two most common scenarios: coercing values to boolean and numbers.
+
+```ts
+import {Component, input, booleanAttribute, numberAttribute} from '@angular/core';
+
+@Component({/*...*/})
+export class CustomSlider {
+ disabled = input(false, {transform: booleanAttribute});
+ value = input(0, {transform: numberAttribute});
+}
+```
+
+`booleanAttribute` imitates the behavior of standard HTML [boolean attributes](https://developer.mozilla.org/docs/Glossary/Boolean/HTML), where the
+_presence_ of the attribute indicates a "true" value. However, Angular's `booleanAttribute` treats the literal string `"false"` as the boolean `false`.
+
+`numberAttribute` attempts to parse the given value to a number, producing `NaN` if parsing fails.
+
+### Input aliases
+
+You can specify the `alias` option to change the name of an input in templates.
+
+```ts {highlight:[3]}
+@Component({/*...*/})
+export class CustomSlider {
+ value = input(0, {alias: 'sliderValue'});
+}
+```
+
+```angular-html
+
+```
+
+This alias does not affect usage of the property in TypeScript code.
+
+While you should generally avoid aliasing inputs for components, this feature can be useful for renaming properties while preserving an alias for the original name or for avoiding collisions with the name of native DOM element properties.
+
+## Model inputs
+
+**Model inputs** are a special type of input that enable a component to propagate new values back to its parent component.
+
+When creating a component, you can define a model input similarly to how you create a standard input.
+
+Both types of input allow someone to bind a value into the property. However, **model inputs allow the component author to write values into the property**. If the property is bound with a two-way binding, the new value propagates to that binding.
+
+```ts
+@Component({ /* ... */})
+export class CustomSlider {
+ // Define a model input named "value".
+ value = model(0);
+
+ increment() {
+ // Update the model input with a new value, propagating the value to any bindings.
+ this.value.update(oldValue => oldValue + 10);
+ }
+}
+
+@Component({
+ /* ... */
+ // Using the two-way binding syntax means that any changes to the slider's
+ // value automatically propagate back to the `volume` signal.
+ // Note that this binding uses the signal *instance*, not the signal value.
+ template: ``,
+})
+export class MediaControls {
+ // Create a writable signal for the `volume` local state.
+ volume = signal(0);
+}
+```
+
+In the above example, the `CustomSlider` can write values into its `value` model input, which then propagates those values back to the `volume` signal in `MediaControls`. This binding keeps the values of `value` and `volume` in sync. Notice that the binding passes the `volume` signal instance, not the _value_ of the signal.
+
+In other respects, model inputs work similarly to standard inputs. You can read the value by calling the signal function, including in reactive contexts like `computed` and `effect`.
+
+See [Two-way binding](guide/templates/two-way-binding) for more details on two-way binding in templates.
+
+### Two-way binding with plain properties
+
+You can bind a plain JavaScript property to a model input.
+
+```angular-ts
+@Component({
+ /* ... */
+ // `value` is a model input.
+ // The parenthesis-inside-square-brackets syntax (aka "banana-in-a-box") creates a two-way binding
+ template: '',
+})
+export class MediaControls {
+ protected volume = 0;
+}
+```
+
+In the example above, the `CustomSlider` can write values into its `value` model input, which then propagates those values back to the `volume` property in `MediaControls`. This binding keeps the values of `value` and `volume` in sync.
+
+### Implicit `change` events
+
+When you declare a model input in a component or directive, Angular automatically creates a corresponding [output](guide/components/outputs) for that model. The output's name is the model input's name suffixed with "Change".
+
+```ts
+@Directive({ /* ... */ })
+export class CustomCheckbox {
+ // This automatically creates an output named "checkedChange".
+ // Can be subscribed to using `(checkedChange)="handler()"` in the template.
+ checked = model(false);
+}
+```
+
+Angular emits this change event whenever you write a new value into the model input by calling its `set` or `update` methods.
+
+See [Custom events with outputs](guide/components/outputs) for more details on outputs.
+
+### Customizing model inputs
+
+You can mark a model input as required or provide an alias in the same way as a [standard input](guide/signals/inputs).
+
+Model inputs do not support input transforms.
+
+### When to use model inputs
+
+Use model inputs when you want a component to support two-way binding. This is typically appropriate when a component exists to modify a value based on user interaction. Most commonly, custom form controls, such as a date picker or combobox, should use model inputs for their primary value.
+
+## Choosing input names
+
+Avoid choosing input names that collide with properties on DOM elements like HTMLElement. Name collisions introduce confusion about whether the bound property belongs to the component or the DOM element.
+
+Avoid adding prefixes for component inputs like you would with component selectors. Since a given element can only host one component, any custom properties can be assumed to belong to the component.
+
+## Declaring inputs with the `@Input` decorator
+
+TIP: While the Angular team recommends using the signal-based `input` function for new projects, the original decorator-based `@Input` API remains fully supported.
+
+You can alternatively declare component inputs by adding the `@Input` decorator to a property:
+
+```ts {highlight:[3]}
+@Component({...})
+export class CustomSlider {
+ @Input() value = 0;
+}
+```
+
+Binding to an input is the same in both signal-based and decorator-based inputs:
+
+```angular-html
+
+```
+
+### Customizing decorator-based inputs
+
+The `@Input` decorator accepts a config object that lets you change the way that input works.
+
+#### Required inputs
+
+You can specify the `required` option to enforce that a given input must always have a value.
+
+```ts {highlight:[3]}
+@Component({...})
+export class CustomSlider {
+ @Input({required: true}) value = 0;
+}
+```
+
+If you try to use a component without specifying all of its required inputs, Angular reports an error at build-time.
+
+#### Input transforms
+
+You can specify a `transform` function to change the value of an input when it's set by Angular. This transform function works identically to transform functions for signal-based inputs described above.
+
+```ts {highlight:[6]}
+@Component({
+ selector: 'custom-slider',
+ ...
+})
+export class CustomSlider {
+ @Input({transform: trimString}) label = '';
+}
+
+function trimString(value: string | undefined) {
+ return value?.trim() ?? '';
+}
+```
+
+#### Input aliases
+
+You can specify the `alias` option to change the name of an input in templates.
+
+```ts {highlight:[3]}
+@Component({...})
+export class CustomSlider {
+ @Input({alias: 'sliderValue'}) value = 0;
+}
+```
+
+```angular-html
+
+```
+
+The `@Input` decorator also accepts the alias as its first parameter in place of the config object.
+
+Input aliases work the same way as for signal-based inputs described above.
+
+### Inputs with getters and setters
+
+When using decorator-based inputs, a property implemented with a getter and setter can be an input:
+
+```ts
+export class CustomSlider {
+ @Input()
+ get value(): number {
+ return this.internalValue;
+ }
+
+ set value(newValue: number) { this.internalValue = newValue; }
+
+ private internalValue = 0;
+}
+```
+
+You can even create a _write-only_ input by only defining a public setter:
+
+```ts
+export class CustomSlider {
+ @Input()
+ set value(newValue: number) {
+ this.internalValue = newValue;
+ }
+
+ private internalValue = 0;
+}
+```
+
+**Prefer using input transforms instead of getters and setters** if possible.
+
+Avoid complex or costly getters and setters. Angular may invoke an input's setter multiple times, which may negatively impact application performance if the setter performs any costly behaviors, such as DOM manipulation.
+
+## Specify inputs in the `@Component` decorator
+
+In addition to the `@Input` decorator, you can also specify a component's inputs with the `inputs` property in the `@Component` decorator. This can be useful when a component inherits a property from a base class:
+
+```ts {highlight:[4]}
+// `CustomSlider` inherits the `disabled` property from `BaseSlider`.
+@Component({
+ ...,
+ inputs: ['disabled'],
+})
+export class CustomSlider extends BaseSlider { }
+```
+
+You can additionally specify an input alias in the `inputs` list by putting the alias after a colon in the string:
+
+```ts {highlight:[4]}
+// `CustomSlider` inherits the `disabled` property from `BaseSlider`.
+@Component({
+ ...,
+ inputs: ['disabled: sliderDisabled'],
+})
+export class CustomSlider extends BaseSlider { }
+```
diff --git a/adev-es/src/content/guide/components/inputs.md b/adev-es/src/content/guide/components/inputs.md
index 73651d7..79c0aa3 100644
--- a/adev-es/src/content/guide/components/inputs.md
+++ b/adev-es/src/content/guide/components/inputs.md
@@ -1,10 +1,10 @@
-# Accepting data with input properties
+# Aceptando datos con propiedades de input
-TIP: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular.
+CONSEJO: Esta guía asume que ya has leído la [Guía de Esenciales](essentials). Lee esa primero si eres nuevo en Angular.
-TIP: If you're familiar with other web frameworks, input properties are similar to _props_.
+CONSEJO: Si estás familiarizado con otros frameworks web, las propiedades de input son similares a _props_.
-When you use a component, you commonly want to pass some data to it. A component specifies the data that it accepts by declaring
+Cuando usas un componente, comúnmente quieres pasarle algunos datos. Un componente especifica los datos que acepta declarando
**inputs**:
```ts {highlight:[5]}
@@ -12,89 +12,89 @@ import {Component, input} from '@angular/core';
@Component({/*...*/})
export class CustomSlider {
- // Declare an input named 'value' with a default value of zero.
+ // Declara un input llamado 'value' con un valor predeterminado de cero.
value = input(0);
}
```
-This lets you bind to the property in a template:
+Esto te permite enlazar a la propiedad en una plantilla:
```angular-html
```
-If an input has a default value, TypeScript infers the type from the default value:
+Si un input tiene un valor predeterminado, TypeScript infiere el tipo del valor predeterminado:
```ts
@Component({/*...*/})
export class CustomSlider {
- // TypeScript infers that this input is a number, returning InputSignal.
+ // TypeScript infiere que este input es un número, devolviendo InputSignal.
value = input(0);
}
```
-You can explicitly declare a type for the input by specifying a generic parameter to the function.
+Puedes declarar explícitamente un tipo para el input especificando un parámetro genérico a la función.
-If an input without a default value is not set, its value is `undefined`:
+Si un input sin un valor predeterminado no se establece, su valor es `undefined`:
```ts
@Component({/*...*/})
export class CustomSlider {
- // Produces an InputSignal because `value` may not be set.
+ // Produce un InputSignal porque `value` puede no estar establecido.
value = input();
}
```
-**Angular records inputs statically at compile-time**. Inputs cannot be added or removed at run-time.
+**Angular registra los inputs estáticamente en tiempo de compilación**. Los inputs no se pueden agregar o eliminar en tiempo de ejecución.
-The `input` function has special meaning to the Angular compiler. **You can exclusively call `input` in component and directive property initializers.**
+La función `input` tiene un significado especial para el compilador de Angular. **Solo puedes llamar a `input` en inicializadores de propiedades de componentes y directivas.**
-When extending a component class, **inputs are inherited by the child class.**
+Al extender una clase de componente, **los inputs son heredados por la clase hija.**
-**Input names are case-sensitive.**
+**Los nombres de input distinguen entre mayúsculas y minúsculas.**
-## Reading inputs
+## Leer inputs
-The `input` function returns an `InputSignal`. You can read the value by calling the signal:
+La función `input` devuelve un `InputSignal`. Puedes leer el valor llamando a la signal:
```ts {highlight:[5]}
import {Component, input, computed} from '@angular/core';
@Component({/*...*/})
export class CustomSlider {
- // Declare an input named 'value' with a default value of zero.
+ // Declara un input llamado 'value' con un valor predeterminado de cero.
value = input(0);
- // Create a computed expression that reads the value input
- label = computed(() => `The slider's value is ${this.value()}`);
+ // Crea una expresión computed que lee el input value
+ label = computed(() => `El valor del slider es ${this.value()}`);
}
```
-Signals created by the `input` function are read-only.
+Las signals creadas por la función `input` son de solo lectura.
-## Required inputs
+## Inputs requeridos
-You can declare that an input is `required` by calling `input.required` instead of `input`:
+Puedes declarar que un input es `required` llamando a `input.required` en lugar de `input`:
```ts {highlight:[3]}
@Component({/*...*/})
export class CustomSlider {
- // Declare a required input named value. Returns an `InputSignal`.
+ // Declara un input requerido llamado value. Devuelve un `InputSignal`.
value = input.required();
}
```
-Angular enforces that required inputs _must_ be set when the component is used in a template. If you try to use a component without specifying all of its required inputs, Angular reports an error at build-time.
+Angular exige que los inputs requeridos _deben_ establecerse cuando el componente se usa en una plantilla. Si intentas usar un componente sin especificar todos sus inputs requeridos, Angular reporta un error en tiempo de compilación.
-Required inputs do not automatically include `undefined` in the generic parameter of the returned `InputSignal`.
+Los inputs requeridos no incluyen automáticamente `undefined` en el parámetro genérico del `InputSignal` devuelto.
-## Configuring inputs
+## Configurar inputs
-The `input` function accepts a config object as a second parameter that lets you change the way that input works.
+La función `input` acepta un objeto de configuración como segundo parámetro que te permite cambiar la forma en que funciona el input.
-### Input transforms
+### Transformaciones de input
-You can specify a `transform` function to change the value of an input when it's set by Angular.
+Puedes especificar una función `transform` para cambiar el valor de un input cuando es establecido por Angular.
```ts {highlight:[6]}
@Component({
@@ -114,17 +114,17 @@ function trimString(value: string | undefined): string {
```
-In the example above, whenever the value of `systemVolume` changes, Angular runs `trimString` and sets `label` to the result.
+En el ejemplo anterior, cada vez que el valor de `systemVolume` cambia, Angular ejecuta `trimString` y establece `label` con el resultado.
-The most common use-case for input transforms is to accept a wider range of value types in templates, often including `null` and `undefined`.
+El caso de uso más común para las transformaciones de input es aceptar un rango más amplio de tipos de valor en las plantillas, frecuentemente incluyendo `null` y `undefined`.
-**Input transform function must be statically analyzable at build-time.** You cannot set transform functions conditionally or as the result of an expression evaluation.
+**La función de transformación de input debe ser analizable estáticamente en tiempo de compilación.** No puedes establecer funciones de transformación condicionalmente o como resultado de una evaluación de expresión.
-**Input transform functions should always be [pure functions](https://en.wikipedia.org/wiki/Pure_function).** Relying on state outside the transform function can lead to unpredictable behavior.
+**Las funciones de transformación de input siempre deben ser [funciones puras](https://en.wikipedia.org/wiki/Pure_function).** Depender de estado fuera de la función de transformación puede llevar a comportamiento impredecible.
-#### Type checking
+#### Verificación de tipos
-When you specify an input transform, the type of the transform function's parameter determines the types of values that can be set to the input in a template.
+Cuando especificas una transformación de input, el tipo del parámetro de la función de transformación determina los tipos de valores que se pueden establecer al input en una plantilla.
```ts
@Component({/*...*/})
@@ -137,11 +137,11 @@ function appendPx(value: number): string {
}
```
-In the example above, the `widthPx` input accepts a `number` while the `InputSignal` property returns a `string`.
+En el ejemplo anterior, el input `widthPx` acepta un `number` mientras que la propiedad `InputSignal` devuelve un `string`.
-#### Built-in transformations
+#### Transformaciones integradas
-Angular includes two built-in transform functions for the two most common scenarios: coercing values to boolean and numbers.
+Angular incluye dos funciones de transformación integradas para los dos escenarios más comunes: convertir valores a booleano y números.
```ts
import {Component, input, booleanAttribute, numberAttribute} from '@angular/core';
@@ -153,14 +153,14 @@ export class CustomSlider {
}
```
-`booleanAttribute` imitates the behavior of standard HTML [boolean attributes](https://developer.mozilla.org/docs/Glossary/Boolean/HTML), where the
-_presence_ of the attribute indicates a "true" value. However, Angular's `booleanAttribute` treats the literal string `"false"` as the boolean `false`.
+`booleanAttribute` imita el comportamiento de los [atributos booleanos](https://developer.mozilla.org/docs/Glossary/Boolean/HTML) estándar de HTML, donde la
+_presencia_ del atributo indica un valor "true". Sin embargo, el `booleanAttribute` de Angular trata la cadena literal `"false"` como el booleano `false`.
-`numberAttribute` attempts to parse the given value to a number, producing `NaN` if parsing fails.
+`numberAttribute` intenta parsear el valor dado a un número, produciendo `NaN` si el parseo falla.
-### Input aliases
+### Alias de input
-You can specify the `alias` option to change the name of an input in templates.
+Puedes especificar la opción `alias` para cambiar el nombre de un input en las plantillas.
```ts {highlight:[3]}
@Component({/*...*/})
@@ -173,58 +173,58 @@ export class CustomSlider {
```
-This alias does not affect usage of the property in TypeScript code.
+Este alias no afecta el uso de la propiedad en código TypeScript.
-While you should generally avoid aliasing inputs for components, this feature can be useful for renaming properties while preserving an alias for the original name or for avoiding collisions with the name of native DOM element properties.
+Aunque generalmente debes evitar usar alias para inputs de componentes, esta característica puede ser útil para renombrar propiedades mientras se preserva un alias para el nombre original o para evitar colisiones con el nombre de propiedades de elementos DOM nativos.
## Model inputs
-**Model inputs** are a special type of input that enable a component to propagate new values back to its parent component.
+Los **model inputs** son un tipo especial de input que permiten a un componente propagar nuevos valores de vuelta a su componente padre.
-When creating a component, you can define a model input similarly to how you create a standard input.
+Al crear un componente, puedes definir un model input de manera similar a como creas un input estándar.
-Both types of input allow someone to bind a value into the property. However, **model inputs allow the component author to write values into the property**. If the property is bound with a two-way binding, the new value propagates to that binding.
+Ambos tipos de input permiten a alguien enlazar un valor a la propiedad. Sin embargo, **los model inputs permiten al autor del componente escribir valores en la propiedad**. Si la propiedad está enlazada con un enlace bidireccional, el nuevo valor se propaga a ese enlace.
```ts
@Component({ /* ... */})
export class CustomSlider {
- // Define a model input named "value".
+ // Define un model input llamado "value".
value = model(0);
increment() {
- // Update the model input with a new value, propagating the value to any bindings.
+ // Actualiza el model input con un nuevo valor, propagando el valor a cualquier enlace.
this.value.update(oldValue => oldValue + 10);
}
}
@Component({
/* ... */
- // Using the two-way binding syntax means that any changes to the slider's
- // value automatically propagate back to the `volume` signal.
- // Note that this binding uses the signal *instance*, not the signal value.
+ // Usar la sintaxis de enlace bidireccional significa que cualquier cambio al valor del slider
+ // se propaga automáticamente de vuelta a la signal `volume`.
+ // Nota que este enlace usa la *instancia* de la signal, no el valor de la signal.
template: ``,
})
export class MediaControls {
- // Create a writable signal for the `volume` local state.
+ // Crea una signal escribible para el estado local `volume`.
volume = signal(0);
}
```
-In the above example, the `CustomSlider` can write values into its `value` model input, which then propagates those values back to the `volume` signal in `MediaControls`. This binding keeps the values of `value` and `volume` in sync. Notice that the binding passes the `volume` signal instance, not the _value_ of the signal.
+En el ejemplo anterior, `CustomSlider` puede escribir valores en su model input `value`, que luego propaga esos valores de vuelta a la signal `volume` en `MediaControls`. Este enlace mantiene los valores de `value` y `volume` sincronizados. Nota que el enlace pasa la instancia de la signal `volume`, no el _valor_ de la signal.
-In other respects, model inputs work similarly to standard inputs. You can read the value by calling the signal function, including in reactive contexts like `computed` and `effect`.
+En otros aspectos, los model inputs funcionan de manera similar a los inputs estándar. Puedes leer el valor llamando a la función de signal, incluyendo en contextos reactivos como `computed` y `effect`.
-See [Two-way binding](guide/templates/two-way-binding) for more details on two-way binding in templates.
+Consulta [Enlace bidireccional](guide/templates/two-way-binding) para más detalles sobre el enlace bidireccional en plantillas.
-### Two-way binding with plain properties
+### Enlace bidireccional con propiedades planas
-You can bind a plain JavaScript property to a model input.
+Puedes enlazar una propiedad JavaScript plana a un model input.
```angular-ts
@Component({
/* ... */
- // `value` is a model input.
- // The parenthesis-inside-square-brackets syntax (aka "banana-in-a-box") creates a two-way binding
+ // `value` es un model input.
+ // La sintaxis de paréntesis dentro de corchetes (también conocida como "banana-in-a-box") crea un enlace bidireccional
template: '',
})
export class MediaControls {
@@ -232,46 +232,46 @@ export class MediaControls {
}
```
-In the example above, the `CustomSlider` can write values into its `value` model input, which then propagates those values back to the `volume` property in `MediaControls`. This binding keeps the values of `value` and `volume` in sync.
+En el ejemplo anterior, `CustomSlider` puede escribir valores en su model input `value`, que luego propaga esos valores de vuelta a la propiedad `volume` en `MediaControls`. Este enlace mantiene los valores de `value` y `volume` sincronizados.
-### Implicit `change` events
+### Eventos `change` implícitos
-When you declare a model input in a component or directive, Angular automatically creates a corresponding [output](guide/components/outputs) for that model. The output's name is the model input's name suffixed with "Change".
+Cuando declaras un model input en un componente o directiva, Angular crea automáticamente un [output](guide/components/outputs) correspondiente para ese model. El nombre del output es el nombre del model input con el sufijo "Change".
```ts
@Directive({ /* ... */ })
export class CustomCheckbox {
- // This automatically creates an output named "checkedChange".
- // Can be subscribed to using `(checkedChange)="handler()"` in the template.
+ // Esto crea automáticamente un output llamado "checkedChange".
+ // Se puede suscribir usando `(checkedChange)="handler()"` en la plantilla.
checked = model(false);
}
```
-Angular emits this change event whenever you write a new value into the model input by calling its `set` or `update` methods.
+Angular emite este evento de cambio cada vez que escribes un nuevo valor en el model input llamando a sus métodos `set` o `update`.
-See [Custom events with outputs](guide/components/outputs) for more details on outputs.
+Consulta [Eventos personalizados con outputs](guide/components/outputs) para más detalles sobre outputs.
-### Customizing model inputs
+### Personalizar model inputs
-You can mark a model input as required or provide an alias in the same way as a [standard input](guide/signals/inputs).
+Puedes marcar un model input como requerido o proporcionar un alias de la misma manera que un [input estándar](guide/signals/inputs).
-Model inputs do not support input transforms.
+Los model inputs no admiten transformaciones de input.
-### When to use model inputs
+### Cuándo usar model inputs
-Use model inputs when you want a component to support two-way binding. This is typically appropriate when a component exists to modify a value based on user interaction. Most commonly, custom form controls, such as a date picker or combobox, should use model inputs for their primary value.
+Usa model inputs cuando quieras que un componente admita enlace bidireccional. Esto es típicamente apropiado cuando un componente existe para modificar un valor basado en la interacción del usuario. Más comúnmente, los controles de formulario personalizados, como un selector de fecha o combobox, deben usar model inputs para su valor principal.
-## Choosing input names
+## Elegir nombres de input
-Avoid choosing input names that collide with properties on DOM elements like HTMLElement. Name collisions introduce confusion about whether the bound property belongs to the component or the DOM element.
+Evita elegir nombres de input que colisionen con propiedades en elementos DOM como HTMLElement. Las colisiones de nombres introducen confusión sobre si la propiedad enlazada pertenece al componente o al elemento DOM.
-Avoid adding prefixes for component inputs like you would with component selectors. Since a given element can only host one component, any custom properties can be assumed to belong to the component.
+Evita agregar prefijos para inputs de componentes como lo harías con selectores de componentes. Dado que un elemento dado solo puede alojar un componente, se puede asumir que cualquier propiedad personalizada pertenece al componente.
-## Declaring inputs with the `@Input` decorator
+## Declarar inputs con el decorador `@Input`
-TIP: While the Angular team recommends using the signal-based `input` function for new projects, the original decorator-based `@Input` API remains fully supported.
+CONSEJO: Aunque el equipo de Angular recomienda usar la función `input` basada en signals para proyectos nuevos, la API original basada en decoradores `@Input` sigue siendo completamente compatible.
-You can alternatively declare component inputs by adding the `@Input` decorator to a property:
+Alternativamente puedes declarar inputs de componente agregando el decorador `@Input` a una propiedad:
```ts {highlight:[3]}
@Component({...})
@@ -280,19 +280,19 @@ export class CustomSlider {
}
```
-Binding to an input is the same in both signal-based and decorator-based inputs:
+Enlazar a un input es lo mismo tanto en inputs basados en signals como en inputs basados en decoradores:
```angular-html
```
-### Customizing decorator-based inputs
+### Personalizar inputs basados en decoradores
-The `@Input` decorator accepts a config object that lets you change the way that input works.
+El decorador `@Input` acepta un objeto de configuración que te permite cambiar la forma en que funciona el input.
-#### Required inputs
+#### Inputs requeridos
-You can specify the `required` option to enforce that a given input must always have a value.
+Puedes especificar la opción `required` para exigir que un input dado siempre tenga un valor.
```ts {highlight:[3]}
@Component({...})
@@ -301,11 +301,11 @@ export class CustomSlider {
}
```
-If you try to use a component without specifying all of its required inputs, Angular reports an error at build-time.
+Si intentas usar un componente sin especificar todos sus inputs requeridos, Angular reporta un error en tiempo de compilación.
-#### Input transforms
+#### Transformaciones de input
-You can specify a `transform` function to change the value of an input when it's set by Angular. This transform function works identically to transform functions for signal-based inputs described above.
+Puedes especificar una función `transform` para cambiar el valor de un input cuando es establecido por Angular. Esta función de transformación funciona de manera idéntica a las funciones de transformación para inputs basados en signals descritas anteriormente.
```ts {highlight:[6]}
@Component({
@@ -321,9 +321,9 @@ function trimString(value: string | undefined) {
}
```
-#### Input aliases
+#### Alias de input
-You can specify the `alias` option to change the name of an input in templates.
+Puedes especificar la opción `alias` para cambiar el nombre de un input en las plantillas.
```ts {highlight:[3]}
@Component({...})
@@ -336,13 +336,13 @@ export class CustomSlider {
```
-The `@Input` decorator also accepts the alias as its first parameter in place of the config object.
+El decorador `@Input` también acepta el alias como su primer parámetro en lugar del objeto de configuración.
-Input aliases work the same way as for signal-based inputs described above.
+Los alias de input funcionan de la misma manera que para inputs basados en signals descritos anteriormente.
-### Inputs with getters and setters
+### Inputs con getters y setters
-When using decorator-based inputs, a property implemented with a getter and setter can be an input:
+Cuando usas inputs basados en decoradores, una propiedad implementada con un getter y setter puede ser un input:
```ts
export class CustomSlider {
@@ -357,7 +357,7 @@ export class CustomSlider {
}
```
-You can even create a _write-only_ input by only defining a public setter:
+Incluso puedes crear un input _de solo escritura_ definiendo solo un setter público:
```ts
export class CustomSlider {
@@ -370,16 +370,16 @@ export class CustomSlider {
}
```
-**Prefer using input transforms instead of getters and setters** if possible.
+**Prefiere usar transformaciones de input en lugar de getters y setters** si es posible.
-Avoid complex or costly getters and setters. Angular may invoke an input's setter multiple times, which may negatively impact application performance if the setter performs any costly behaviors, such as DOM manipulation.
+Evita getters y setters complejos o costosos. Angular puede invocar el setter de un input múltiples veces, lo que puede impactar negativamente el rendimiento de la aplicación si el setter realiza comportamientos costosos, como manipulación del DOM.
-## Specify inputs in the `@Component` decorator
+## Especificar inputs en el decorador `@Component`
-In addition to the `@Input` decorator, you can also specify a component's inputs with the `inputs` property in the `@Component` decorator. This can be useful when a component inherits a property from a base class:
+Además del decorador `@Input`, también puedes especificar los inputs de un componente con la propiedad `inputs` en el decorador `@Component`. Esto puede ser útil cuando un componente hereda una propiedad de una clase base:
```ts {highlight:[4]}
-// `CustomSlider` inherits the `disabled` property from `BaseSlider`.
+// `CustomSlider` hereda la propiedad `disabled` de `BaseSlider`.
@Component({
...,
inputs: ['disabled'],
@@ -387,10 +387,10 @@ In addition to the `@Input` decorator, you can also specify a component's inputs
export class CustomSlider extends BaseSlider { }
```
-You can additionally specify an input alias in the `inputs` list by putting the alias after a colon in the string:
+Además puedes especificar un alias de input en la lista `inputs` poniendo el alias después de dos puntos en la cadena:
```ts {highlight:[4]}
-// `CustomSlider` inherits the `disabled` property from `BaseSlider`.
+// `CustomSlider` hereda la propiedad `disabled` de `BaseSlider`.
@Component({
...,
inputs: ['disabled: sliderDisabled'],
diff --git a/adev-es/src/content/guide/components/lifecycle.en.md b/adev-es/src/content/guide/components/lifecycle.en.md
new file mode 100644
index 0000000..6f07542
--- /dev/null
+++ b/adev-es/src/content/guide/components/lifecycle.en.md
@@ -0,0 +1,358 @@
+# Component Lifecycle
+
+TIP: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular.
+
+A component's **lifecycle** is the sequence of steps that happen between the component's creation
+and its destruction. Each step represents a different part of Angular's process for rendering
+components and checking them for updates over time.
+
+In your components, you can implement **lifecycle hooks** to run code during these steps.
+Lifecycle hooks that relate to a specific component instance are implemented as methods on your
+component class. Lifecycle hooks that relate the Angular application as a whole are implemented
+as functions that accept a callback.
+
+A component's lifecycle is tightly connected to how Angular checks your components for changes over
+time. For the purposes of understanding this lifecycle, you only need to know that Angular walks
+your application tree from top to bottom, checking template bindings for changes. The lifecycle
+hooks described below run while Angular is doing this traversal. This traversal visits each
+component exactly once, so you should always avoid making further state changes in the middle of the
+process.
+
+## Summary
+
+
Runs once after Angular has initialized all the component's inputs.
+
+
+
ngOnChanges
+
Runs every time the component's inputs have changed.
+
+
+
ngDoCheck
+
Runs every time this component is checked for changes.
+
+
+
ngAfterContentInit
+
Runs once after the component's content has been initialized.
+
+
+
ngAfterContentChecked
+
Runs every time this component content has been checked for changes.
+
+
+
ngAfterViewInit
+
Runs once after the component's view has been initialized.
+
+
+
ngAfterViewChecked
+
Runs every time the component's view has been checked for changes.
+
+
+
Rendering
+
afterNextRender
+
Runs once the next time that all components have been rendered to the DOM.
+
+
+
afterEveryRender
+
Runs every time all components have been rendered to the DOM.
+
+
+
Destruction
+
ngOnDestroy
+
Runs once before the component is destroyed.
+
+
+
+
+### ngOnInit
+
+The `ngOnInit` method runs after Angular has initialized all the components inputs with their
+initial values. A component's `ngOnInit` runs exactly once.
+
+This step happens _before_ the component's own template is initialized. This means that you can
+update the component's state based on its initial input values.
+
+### ngOnChanges
+
+The `ngOnChanges` method runs after any component inputs have changed.
+
+This step happens _before_ the component's own template is checked. This means that you can update
+the component's state based on its initial input values.
+
+During initialization, the first `ngOnChanges` runs before `ngOnInit`.
+
+#### Inspecting changes
+
+The `ngOnChanges` method accepts one `SimpleChanges` argument. This object is
+a [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)
+mapping each component input name to a `SimpleChange` object. Each `SimpleChange` contains the
+input's previous value, its current value, and a flag for whether this is the first time the input
+has changed.
+
+You can optionally pass the current class or this as the first generic argument for stronger type checking.
+
+```ts
+@Component({
+ /* ... */
+})
+export class UserProfile {
+ name = input('');
+
+ ngOnChanges(changes: SimpleChanges) {
+ if (changes.name) {
+ console.log(`Previous: ${changes.name.previousValue}`);
+ console.log(`Current: ${changes.name.currentValue}`);
+ console.log(`Is first ${changes.name.firstChange}`);
+ }
+ }
+}
+```
+
+If you provide an `alias` for any input properties, the `SimpleChanges` Record still uses the
+TypeScript property name as a key, rather than the alias.
+
+### ngOnDestroy
+
+The `ngOnDestroy` method runs once just before a component is destroyed. Angular destroys a
+component when it is no longer shown on the page, such as being hidden by `@if` or upon navigating
+to another page.
+
+#### DestroyRef
+
+As an alternative to the `ngOnDestroy` method, you can inject an instance of `DestroyRef`. You can
+register a callback to be invoked upon the component's destruction by calling the `onDestroy` method
+of `DestroyRef`.
+
+```ts
+@Component({
+ /* ... */
+})
+export class UserProfile {
+ constructor() {
+ inject(DestroyRef).onDestroy(() => {
+ console.log('UserProfile destruction');
+ });
+ }
+}
+```
+
+You can pass the `DestroyRef` instance to functions or classes outside your component. Use this
+pattern if you have other code that should run some cleanup behavior when the component is
+destroyed.
+
+You can also use `DestroyRef` to keep setup code close to cleanup code, rather than putting
+all cleanup code in the `ngOnDestroy` method.
+
+##### Detecting instance destruction
+
+`DestroyRef` provides a `destroyed` property that allows checking whether a given instance has already been destroyed. This is useful for avoiding operations on destroyed components, especially when dealing with delayed or asynchronous logic.
+
+By checking `destroyRef.destroyed`, you can prevent executing code after the instance has been cleaned up, avoiding potential errors such as `NG0911: View has already been destroyed.`.
+
+### ngDoCheck
+
+The `ngDoCheck` method runs before every time Angular checks a component's template for changes.
+
+You can use this lifecycle hook to manually check for state changes outside of Angular's normal
+change detection, manually updating the component's state.
+
+This method runs very frequently and can significantly impact your page's performance. Avoid
+defining this hook whenever possible, only using it when you have no alternative.
+
+During initialization, the first `ngDoCheck` runs after `ngOnInit`.
+
+### ngAfterContentInit
+
+The `ngAfterContentInit` method runs once after all the children nested inside the component (its
+_content_) have been initialized.
+
+You can use this lifecycle hook to read the results of
+[content queries](guide/components/queries#content-queries). While you can access the initialized
+state of these queries, attempting to change any state in this method results in an
+[ExpressionChangedAfterItHasBeenCheckedError](errors/NG0100)
+
+### ngAfterContentChecked
+
+The `ngAfterContentChecked` method runs every time the children nested inside the component (its
+_content_) have been checked for changes.
+
+This method runs very frequently and can significantly impact your page's performance. Avoid
+defining this hook whenever possible, only using it when you have no alternative.
+
+While you can access the updated state
+of [content queries](guide/components/queries#content-queries) here, attempting to
+change any state in this method results in
+an [ExpressionChangedAfterItHasBeenCheckedError](errors/NG0100).
+
+### ngAfterViewInit
+
+The `ngAfterViewInit` method runs once after all the children in the component's template (its
+_view_) have been initialized.
+
+You can use this lifecycle hook to read the results of
+[view queries](guide/components/queries#view-queries). While you can access the initialized state of
+these queries, attempting to change any state in this method results in an
+[ExpressionChangedAfterItHasBeenCheckedError](errors/NG0100)
+
+### ngAfterViewChecked
+
+The `ngAfterViewChecked` method runs every time the children in the component's template (its
+_view_) have been checked for changes.
+
+This method runs very frequently and can significantly impact your page's performance. Avoid
+defining this hook whenever possible, only using it when you have no alternative.
+
+While you can access the updated state of [view queries](guide/components/queries#view-queries)
+here, attempting to
+change any state in this method results in
+an [ExpressionChangedAfterItHasBeenCheckedError](errors/NG0100).
+
+### afterEveryRender and afterNextRender
+
+The `afterEveryRender` and `afterNextRender` functions let you register a **render callback** to be
+invoked after Angular has finished rendering _all components_ on the page into the DOM.
+
+These functions are different from the other lifecycle hooks described in this guide. Rather than a
+class method, they are standalone functions that accept a callback. The execution of render
+callbacks are not tied to any specific component instance, but instead an application-wide hook.
+
+`afterEveryRender` and `afterNextRender` must be called in
+an [injection context](guide/di/dependency-injection-context), typically a
+component's constructor.
+
+You can use render callbacks to perform manual DOM operations.
+See [Using DOM APIs](guide/components/dom-apis) for guidance on working with the DOM in Angular.
+
+Render callbacks do not run during server-side rendering or during build-time pre-rendering.
+
+#### after\*Render phases
+
+When using `afterEveryRender` or `afterNextRender`, you can optionally split the work into phases. The
+phase gives you control over the sequencing of DOM operations, letting you sequence _write_
+operations before _read_ operations in order to minimize
+[layout thrashing](https://web.dev/avoid-large-complex-layouts-and-layout-thrashing). In order to
+communicate across phases, a phase function may return a result value that can be accessed in the
+next phase.
+
+```ts
+import {Component, ElementRef, afterNextRender} from '@angular/core';
+
+@Component({...})
+export class UserProfile {
+ private prevPadding = 0;
+ private elementHeight = 0;
+
+ constructor() {
+ private elementRef = inject(ElementRef);
+ const nativeElement = elementRef.nativeElement;
+
+ afterNextRender({
+ // Use the `Write` phase to write to a geometric property.
+ write: () => {
+ const padding = computePadding();
+ const changed = padding !== this.prevPadding;
+ if (changed) {
+ nativeElement.style.padding = padding;
+ }
+ return changed; // Communicate whether anything changed to the read phase.
+ },
+
+ // Use the `Read` phase to read geometric properties after all writes have occurred.
+ read: (didWrite) => {
+ if (didWrite) {
+ this.elementHeight = nativeElement.getBoundingClientRect().height;
+ }
+ }
+ });
+ }
+}
+```
+
+There are four phases, run in the following order:
+
+| Phase | Description |
+| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `earlyRead` | Use this phase to read any layout-affecting DOM properties and styles that are strictly necessary for subsequent calculation. Avoid this phase if possible, preferring the `write` and `read` phases. |
+| `write` | Use this phase to write layout-affecting DOM properties and styles. |
+| `mixedReadWrite` | Default phase. Use for any operations need to both read and write layout-affecting properties and styles. Avoid this phase if possible, preferring the explicit `write` and `read` phases. |
+| `read` | Use this phase to read any layout-affecting DOM properties. |
+
+## Lifecycle interfaces
+
+Angular provides a TypeScript interface for each lifecycle method. You can optionally import
+and `implement` these interfaces to ensure that your implementation does not have any typos or
+misspellings.
+
+Each interface has the same name as the corresponding method without the `ng` prefix. For example,
+the interface for `ngOnInit` is `OnInit`.
+
+```ts
+@Component({
+ /* ... */
+})
+export class UserProfile implements OnInit {
+ ngOnInit() {
+ /* ... */
+ }
+}
+```
+
+## Execution order
+
+The following diagrams show the execution order of Angular's lifecycle hooks.
+
+### During initialization
+
+```mermaid
+graph TD;
+id[constructor]-->CHANGE;
+subgraph CHANGE [Change detection]
+direction TB
+ngOnChanges-->ngOnInit;
+ngOnInit-->ngDoCheck;
+ngDoCheck-->ngAfterContentInit;
+ngDoCheck-->ngAfterViewInit
+ngAfterContentInit-->ngAfterContentChecked
+ngAfterViewInit-->ngAfterViewChecked
+end
+CHANGE--Rendering-->afterNextRender-->afterEveryRender
+```
+
+### Subsequent updates
+
+```mermaid
+graph TD;
+subgraph CHANGE [Change detection]
+direction TB
+ngOnChanges-->ngDoCheck
+ngDoCheck-->ngAfterContentChecked;
+ngDoCheck-->ngAfterViewChecked
+end
+CHANGE--Rendering-->afterEveryRender
+```
+
+### Ordering with directives
+
+When you put one or more directives on the same element as a component, either in a template or with
+the `hostDirectives` property, the framework does not guarantee any ordering of a given lifecycle
+hook between the component and the directives on a single element. Never depend on an observed
+ordering, as this may change in later versions of Angular.
diff --git a/adev-es/src/content/guide/components/lifecycle.md b/adev-es/src/content/guide/components/lifecycle.md
index 6f07542..eabacef 100644
--- a/adev-es/src/content/guide/components/lifecycle.md
+++ b/adev-es/src/content/guide/components/lifecycle.md
@@ -1,114 +1,114 @@
-# Component Lifecycle
+# Ciclo de vida del componente
-TIP: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular.
+CONSEJO: Esta guía asume que ya has leído la [Guía de Esenciales](essentials). Lee esa primero si eres nuevo en Angular.
-A component's **lifecycle** is the sequence of steps that happen between the component's creation
-and its destruction. Each step represents a different part of Angular's process for rendering
-components and checking them for updates over time.
+El **ciclo de vida** de un componente es la secuencia de pasos que ocurren entre la creación del componente
+y su destrucción. Cada paso representa una parte diferente del proceso de Angular para renderizar
+componentes y verificar actualizaciones a lo largo del tiempo.
-In your components, you can implement **lifecycle hooks** to run code during these steps.
-Lifecycle hooks that relate to a specific component instance are implemented as methods on your
-component class. Lifecycle hooks that relate the Angular application as a whole are implemented
-as functions that accept a callback.
+En tus componentes, puedes implementar **hooks de ciclo de vida** para ejecutar código durante estos pasos.
+Los hooks de ciclo de vida que se relacionan con una instancia específica de componente se implementan como métodos en tu
+clase de componente. Los hooks de ciclo de vida que se relacionan con la aplicación Angular en su conjunto se implementan
+como funciones que aceptan un callback.
-A component's lifecycle is tightly connected to how Angular checks your components for changes over
-time. For the purposes of understanding this lifecycle, you only need to know that Angular walks
-your application tree from top to bottom, checking template bindings for changes. The lifecycle
-hooks described below run while Angular is doing this traversal. This traversal visits each
-component exactly once, so you should always avoid making further state changes in the middle of the
-process.
+El ciclo de vida de un componente está estrechamente conectado con cómo Angular verifica los cambios en tus componentes a lo largo del
+tiempo. Para entender este ciclo de vida, solo necesitas saber que Angular recorre
+tu árbol de aplicación de arriba hacia abajo, verificando los enlaces de plantilla en busca de cambios. Los hooks de ciclo
+de vida descritos a continuación se ejecutan mientras Angular realiza este recorrido. Este recorrido visita cada
+componente exactamente una vez, por lo que siempre debes evitar hacer más cambios de estado en medio del
+proceso.
-## Summary
+## Resumen
Runs once after Angular has initialized all the component's inputs.
+
Se ejecuta una vez después de que Angular ha inicializado todos los inputs del componente.
ngOnChanges
-
Runs every time the component's inputs have changed.
+
Se ejecuta cada vez que los inputs del componente han cambiado.
ngDoCheck
-
Runs every time this component is checked for changes.
+
Se ejecuta cada vez que este componente es verificado en busca de cambios.
ngAfterContentInit
-
Runs once after the component's content has been initialized.
+
Se ejecuta una vez después de que el contenido del componente ha sido inicializado.
ngAfterContentChecked
-
Runs every time this component content has been checked for changes.
+
Se ejecuta cada vez que el contenido de este componente ha sido verificado en busca de cambios.
ngAfterViewInit
-
Runs once after the component's view has been initialized.
+
Se ejecuta una vez después de que la vista del componente ha sido inicializada.
ngAfterViewChecked
-
Runs every time the component's view has been checked for changes.
+
Se ejecuta cada vez que la vista del componente ha sido verificada en busca de cambios.
-
Rendering
+
Renderizado
afterNextRender
-
Runs once the next time that all components have been rendered to the DOM.
+
Se ejecuta una vez la próxima vez que todos los componentes han sido renderizados en el DOM.
afterEveryRender
-
Runs every time all components have been rendered to the DOM.
+
Se ejecuta cada vez que todos los componentes han sido renderizados en el DOM.
-
Destruction
+
Destrucción
ngOnDestroy
-
Runs once before the component is destroyed.
+
Se ejecuta una vez antes de que el componente sea destruido.
### ngOnInit
-The `ngOnInit` method runs after Angular has initialized all the components inputs with their
-initial values. A component's `ngOnInit` runs exactly once.
+El método `ngOnInit` se ejecuta después de que Angular ha inicializado todos los inputs del componente con sus
+valores iniciales. El `ngOnInit` de un componente se ejecuta exactamente una vez.
-This step happens _before_ the component's own template is initialized. This means that you can
-update the component's state based on its initial input values.
+Este paso ocurre _antes_ de que la propia plantilla del componente sea inicializada. Esto significa que puedes
+actualizar el estado del componente basándote en sus valores de input iniciales.
### ngOnChanges
-The `ngOnChanges` method runs after any component inputs have changed.
+El método `ngOnChanges` se ejecuta después de que cualquier input del componente ha cambiado.
-This step happens _before_ the component's own template is checked. This means that you can update
-the component's state based on its initial input values.
+Este paso ocurre _antes_ de que la propia plantilla del componente sea verificada. Esto significa que puedes actualizar
+el estado del componente basándote en sus valores de input iniciales.
-During initialization, the first `ngOnChanges` runs before `ngOnInit`.
+Durante la inicialización, el primer `ngOnChanges` se ejecuta antes de `ngOnInit`.
-#### Inspecting changes
+#### Inspeccionar cambios
-The `ngOnChanges` method accepts one `SimpleChanges` argument. This object is
-a [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)
-mapping each component input name to a `SimpleChange` object. Each `SimpleChange` contains the
-input's previous value, its current value, and a flag for whether this is the first time the input
-has changed.
+El método `ngOnChanges` acepta un argumento `SimpleChanges`. Este objeto es
+un [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)
+que mapea cada nombre de input del componente a un objeto `SimpleChange`. Cada `SimpleChange` contiene el
+valor anterior del input, su valor actual, y una bandera que indica si esta es la primera vez que el input
+ha cambiado.
-You can optionally pass the current class or this as the first generic argument for stronger type checking.
+Opcionalmente puedes pasar la clase actual o this como el primer argumento genérico para una verificación de tipos más fuerte.
```ts
@Component({
@@ -119,28 +119,28 @@ export class UserProfile {
ngOnChanges(changes: SimpleChanges) {
if (changes.name) {
- console.log(`Previous: ${changes.name.previousValue}`);
- console.log(`Current: ${changes.name.currentValue}`);
- console.log(`Is first ${changes.name.firstChange}`);
+ console.log(`Anterior: ${changes.name.previousValue}`);
+ console.log(`Actual: ${changes.name.currentValue}`);
+ console.log(`Es el primero: ${changes.name.firstChange}`);
}
}
}
```
-If you provide an `alias` for any input properties, the `SimpleChanges` Record still uses the
-TypeScript property name as a key, rather than the alias.
+Si proporcionas un `alias` para cualquier propiedad de input, el Record `SimpleChanges` todavía usa el
+nombre de la propiedad TypeScript como clave, en lugar del alias.
### ngOnDestroy
-The `ngOnDestroy` method runs once just before a component is destroyed. Angular destroys a
-component when it is no longer shown on the page, such as being hidden by `@if` or upon navigating
-to another page.
+El método `ngOnDestroy` se ejecuta una vez justo antes de que un componente sea destruido. Angular destruye un
+componente cuando ya no se muestra en la página, como cuando es ocultado por `@if` o al navegar
+a otra página.
#### DestroyRef
-As an alternative to the `ngOnDestroy` method, you can inject an instance of `DestroyRef`. You can
-register a callback to be invoked upon the component's destruction by calling the `onDestroy` method
-of `DestroyRef`.
+Como alternativa al método `ngOnDestroy`, puedes inyectar una instancia de `DestroyRef`. Puedes
+registrar un callback para ser invocado en la destrucción del componente llamando al método `onDestroy`
+de `DestroyRef`.
```ts
@Component({
@@ -149,109 +149,109 @@ of `DestroyRef`.
export class UserProfile {
constructor() {
inject(DestroyRef).onDestroy(() => {
- console.log('UserProfile destruction');
+ console.log('Destrucción de UserProfile');
});
}
}
```
-You can pass the `DestroyRef` instance to functions or classes outside your component. Use this
-pattern if you have other code that should run some cleanup behavior when the component is
-destroyed.
+Puedes pasar la instancia de `DestroyRef` a funciones o clases fuera de tu componente. Usa este
+patrón si tienes otro código que debe ejecutar algún comportamiento de limpieza cuando el componente es
+destruido.
-You can also use `DestroyRef` to keep setup code close to cleanup code, rather than putting
-all cleanup code in the `ngOnDestroy` method.
+También puedes usar `DestroyRef` para mantener el código de configuración cerca del código de limpieza, en lugar de poner
+todo el código de limpieza en el método `ngOnDestroy`.
-##### Detecting instance destruction
+##### Detectar destrucción de instancia
-`DestroyRef` provides a `destroyed` property that allows checking whether a given instance has already been destroyed. This is useful for avoiding operations on destroyed components, especially when dealing with delayed or asynchronous logic.
+`DestroyRef` proporciona una propiedad `destroyed` que permite verificar si una instancia dada ya ha sido destruida. Esto es útil para evitar operaciones en componentes destruidos, especialmente cuando se trata de lógica retrasada o asíncrona.
-By checking `destroyRef.destroyed`, you can prevent executing code after the instance has been cleaned up, avoiding potential errors such as `NG0911: View has already been destroyed.`.
+Al verificar `destroyRef.destroyed`, puedes prevenir la ejecución de código después de que la instancia ha sido limpiada, evitando errores potenciales como `NG0911: View has already been destroyed.`.
### ngDoCheck
-The `ngDoCheck` method runs before every time Angular checks a component's template for changes.
+El método `ngDoCheck` se ejecuta antes de cada vez que Angular verifica la plantilla de un componente en busca de cambios.
-You can use this lifecycle hook to manually check for state changes outside of Angular's normal
-change detection, manually updating the component's state.
+Puedes usar este hook de ciclo de vida para verificar manualmente cambios de estado fuera de la detección normal de
+cambios de Angular, actualizando manualmente el estado del componente.
-This method runs very frequently and can significantly impact your page's performance. Avoid
-defining this hook whenever possible, only using it when you have no alternative.
+Este método se ejecuta muy frecuentemente y puede impactar significativamente el rendimiento de tu página. Evita
+definir este hook siempre que sea posible, usándolo solo cuando no tengas alternativa.
-During initialization, the first `ngDoCheck` runs after `ngOnInit`.
+Durante la inicialización, el primer `ngDoCheck` se ejecuta después de `ngOnInit`.
### ngAfterContentInit
-The `ngAfterContentInit` method runs once after all the children nested inside the component (its
-_content_) have been initialized.
+El método `ngAfterContentInit` se ejecuta una vez después de que todos los hijos anidados dentro del componente (su
+_contenido_) han sido inicializados.
-You can use this lifecycle hook to read the results of
-[content queries](guide/components/queries#content-queries). While you can access the initialized
-state of these queries, attempting to change any state in this method results in an
+Puedes usar este hook de ciclo de vida para leer los resultados de las
+[consultas de contenido](guide/components/queries#content-queries). Aunque puedes acceder al estado inicializado
+de estas consultas, intentar cambiar cualquier estado en este método resulta en un
[ExpressionChangedAfterItHasBeenCheckedError](errors/NG0100)
### ngAfterContentChecked
-The `ngAfterContentChecked` method runs every time the children nested inside the component (its
-_content_) have been checked for changes.
+El método `ngAfterContentChecked` se ejecuta cada vez que los hijos anidados dentro del componente (su
+_contenido_) han sido verificados en busca de cambios.
-This method runs very frequently and can significantly impact your page's performance. Avoid
-defining this hook whenever possible, only using it when you have no alternative.
+Este método se ejecuta muy frecuentemente y puede impactar significativamente el rendimiento de tu página. Evita
+definir este hook siempre que sea posible, usándolo solo cuando no tengas alternativa.
-While you can access the updated state
-of [content queries](guide/components/queries#content-queries) here, attempting to
-change any state in this method results in
-an [ExpressionChangedAfterItHasBeenCheckedError](errors/NG0100).
+Aunque puedes acceder al estado actualizado
+de las [consultas de contenido](guide/components/queries#content-queries) aquí, intentar
+cambiar cualquier estado en este método resulta en
+un [ExpressionChangedAfterItHasBeenCheckedError](errors/NG0100).
### ngAfterViewInit
-The `ngAfterViewInit` method runs once after all the children in the component's template (its
-_view_) have been initialized.
+El método `ngAfterViewInit` se ejecuta una vez después de que todos los hijos en la plantilla del componente (su
+_vista_) han sido inicializados.
-You can use this lifecycle hook to read the results of
-[view queries](guide/components/queries#view-queries). While you can access the initialized state of
-these queries, attempting to change any state in this method results in an
+Puedes usar este hook de ciclo de vida para leer los resultados de las
+[consultas de vista](guide/components/queries#view-queries). Aunque puedes acceder al estado inicializado de
+estas consultas, intentar cambiar cualquier estado en este método resulta en un
[ExpressionChangedAfterItHasBeenCheckedError](errors/NG0100)
### ngAfterViewChecked
-The `ngAfterViewChecked` method runs every time the children in the component's template (its
-_view_) have been checked for changes.
+El método `ngAfterViewChecked` se ejecuta cada vez que los hijos en la plantilla del componente (su
+_vista_) han sido verificados en busca de cambios.
-This method runs very frequently and can significantly impact your page's performance. Avoid
-defining this hook whenever possible, only using it when you have no alternative.
+Este método se ejecuta muy frecuentemente y puede impactar significativamente el rendimiento de tu página. Evita
+definir este hook siempre que sea posible, usándolo solo cuando no tengas alternativa.
-While you can access the updated state of [view queries](guide/components/queries#view-queries)
-here, attempting to
-change any state in this method results in
-an [ExpressionChangedAfterItHasBeenCheckedError](errors/NG0100).
+Aunque puedes acceder al estado actualizado de las [consultas de vista](guide/components/queries#view-queries)
+aquí, intentar
+cambiar cualquier estado en este método resulta en
+un [ExpressionChangedAfterItHasBeenCheckedError](errors/NG0100).
-### afterEveryRender and afterNextRender
+### afterEveryRender y afterNextRender
-The `afterEveryRender` and `afterNextRender` functions let you register a **render callback** to be
-invoked after Angular has finished rendering _all components_ on the page into the DOM.
+Las funciones `afterEveryRender` y `afterNextRender` te permiten registrar un **callback de renderizado** para ser
+invocado después de que Angular ha terminado de renderizar _todos los componentes_ en la página en el DOM.
-These functions are different from the other lifecycle hooks described in this guide. Rather than a
-class method, they are standalone functions that accept a callback. The execution of render
-callbacks are not tied to any specific component instance, but instead an application-wide hook.
+Estas funciones son diferentes de los otros hooks de ciclo de vida descritos en esta guía. En lugar de un
+método de clase, son funciones standalone que aceptan un callback. La ejecución de los callbacks de renderizado
+no está vinculada a ninguna instancia específica de componente, sino que es un hook a nivel de aplicación.
-`afterEveryRender` and `afterNextRender` must be called in
-an [injection context](guide/di/dependency-injection-context), typically a
-component's constructor.
+`afterEveryRender` y `afterNextRender` deben ser llamados en
+un [contexto de inyección](guide/di/dependency-injection-context), típicamente el
+constructor de un componente.
-You can use render callbacks to perform manual DOM operations.
-See [Using DOM APIs](guide/components/dom-apis) for guidance on working with the DOM in Angular.
+Puedes usar callbacks de renderizado para realizar operaciones manuales del DOM.
+Consulta [Usar APIs del DOM](guide/components/dom-apis) para orientación sobre trabajar con el DOM en Angular.
-Render callbacks do not run during server-side rendering or during build-time pre-rendering.
+Los callbacks de renderizado no se ejecutan durante el renderizado del lado del servidor o durante el pre-renderizado en tiempo de compilación.
-#### after\*Render phases
+#### Fases de after\*Render
-When using `afterEveryRender` or `afterNextRender`, you can optionally split the work into phases. The
-phase gives you control over the sequencing of DOM operations, letting you sequence _write_
-operations before _read_ operations in order to minimize
-[layout thrashing](https://web.dev/avoid-large-complex-layouts-and-layout-thrashing). In order to
-communicate across phases, a phase function may return a result value that can be accessed in the
-next phase.
+Al usar `afterEveryRender` o `afterNextRender`, opcionalmente puedes dividir el trabajo en fases. La
+fase te da control sobre la secuenciación de operaciones del DOM, permitiéndote secuenciar operaciones de _escritura_
+antes de operaciones de _lectura_ para minimizar el
+[layout thrashing](https://web.dev/avoid-large-complex-layouts-and-layout-thrashing). Para
+comunicarse entre fases, una función de fase puede devolver un valor de resultado que puede ser accedido en la
+siguiente fase.
```ts
import {Component, ElementRef, afterNextRender} from '@angular/core';
@@ -266,17 +266,17 @@ export class UserProfile {
const nativeElement = elementRef.nativeElement;
afterNextRender({
- // Use the `Write` phase to write to a geometric property.
+ // Usa la fase `Write` para escribir a una propiedad geométrica.
write: () => {
const padding = computePadding();
const changed = padding !== this.prevPadding;
if (changed) {
nativeElement.style.padding = padding;
}
- return changed; // Communicate whether anything changed to the read phase.
+ return changed; // Comunica si algo cambió a la fase read.
},
- // Use the `Read` phase to read geometric properties after all writes have occurred.
+ // Usa la fase `Read` para leer propiedades geométricas después de que todas las escrituras hayan ocurrido.
read: (didWrite) => {
if (didWrite) {
this.elementHeight = nativeElement.getBoundingClientRect().height;
@@ -287,23 +287,23 @@ export class UserProfile {
}
```
-There are four phases, run in the following order:
+Hay cuatro fases, ejecutadas en el siguiente orden:
-| Phase | Description |
+| Fase | Descripción |
| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `earlyRead` | Use this phase to read any layout-affecting DOM properties and styles that are strictly necessary for subsequent calculation. Avoid this phase if possible, preferring the `write` and `read` phases. |
-| `write` | Use this phase to write layout-affecting DOM properties and styles. |
-| `mixedReadWrite` | Default phase. Use for any operations need to both read and write layout-affecting properties and styles. Avoid this phase if possible, preferring the explicit `write` and `read` phases. |
-| `read` | Use this phase to read any layout-affecting DOM properties. |
+| `earlyRead` | Usa esta fase para leer cualquier propiedad y estilo del DOM que afecte el layout y que sea estrictamente necesario para cálculos posteriores. Evita esta fase si es posible, prefiriendo las fases `write` y `read`. |
+| `write` | Usa esta fase para escribir propiedades y estilos del DOM que afecten el layout. |
+| `mixedReadWrite` | Fase predeterminada. Usa para cualquier operación que necesite tanto leer como escribir propiedades y estilos que afecten el layout. Evita esta fase si es posible, prefiriendo las fases explícitas `write` y `read`. |
+| `read` | Usa esta fase para leer cualquier propiedad del DOM que afecte el layout. |
-## Lifecycle interfaces
+## Interfaces de ciclo de vida
-Angular provides a TypeScript interface for each lifecycle method. You can optionally import
-and `implement` these interfaces to ensure that your implementation does not have any typos or
-misspellings.
+Angular proporciona una interfaz TypeScript para cada método de ciclo de vida. Opcionalmente puedes importar
+e `implementar` estas interfaces para asegurar que tu implementación no tenga errores tipográficos o
+de ortografía.
-Each interface has the same name as the corresponding method without the `ng` prefix. For example,
-the interface for `ngOnInit` is `OnInit`.
+Cada interfaz tiene el mismo nombre que el método correspondiente sin el prefijo `ng`. Por ejemplo,
+la interfaz para `ngOnInit` es `OnInit`.
```ts
@Component({
@@ -316,16 +316,16 @@ export class UserProfile implements OnInit {
}
```
-## Execution order
+## Orden de ejecución
-The following diagrams show the execution order of Angular's lifecycle hooks.
+Los siguientes diagramas muestran el orden de ejecución de los hooks de ciclo de vida de Angular.
-### During initialization
+### Durante la inicialización
```mermaid
graph TD;
id[constructor]-->CHANGE;
-subgraph CHANGE [Change detection]
+subgraph CHANGE [Detección de cambios]
direction TB
ngOnChanges-->ngOnInit;
ngOnInit-->ngDoCheck;
@@ -334,25 +334,25 @@ ngDoCheck-->ngAfterViewInit
ngAfterContentInit-->ngAfterContentChecked
ngAfterViewInit-->ngAfterViewChecked
end
-CHANGE--Rendering-->afterNextRender-->afterEveryRender
+CHANGE--Renderizado-->afterNextRender-->afterEveryRender
```
-### Subsequent updates
+### Actualizaciones posteriores
```mermaid
graph TD;
-subgraph CHANGE [Change detection]
+subgraph CHANGE [Detección de cambios]
direction TB
ngOnChanges-->ngDoCheck
ngDoCheck-->ngAfterContentChecked;
ngDoCheck-->ngAfterViewChecked
end
-CHANGE--Rendering-->afterEveryRender
+CHANGE--Renderizado-->afterEveryRender
```
-### Ordering with directives
+### Orden con directivas
-When you put one or more directives on the same element as a component, either in a template or with
-the `hostDirectives` property, the framework does not guarantee any ordering of a given lifecycle
-hook between the component and the directives on a single element. Never depend on an observed
-ordering, as this may change in later versions of Angular.
+Cuando pones una o más directivas en el mismo elemento que un componente, ya sea en una plantilla o con
+la propiedad `hostDirectives`, el framework no garantiza ningún orden de un hook de ciclo de vida
+dado entre el componente y las directivas en un solo elemento. Nunca dependas de un orden
+observado, ya que esto puede cambiar en versiones posteriores de Angular.
diff --git a/adev-es/src/content/guide/components/output-function.en.md b/adev-es/src/content/guide/components/output-function.en.md
new file mode 100644
index 0000000..7723178
--- /dev/null
+++ b/adev-es/src/content/guide/components/output-function.en.md
@@ -0,0 +1,109 @@
+# Function-based outputs
+
+The `output()` function declares an output in a directive or component.
+Outputs allow you to emit values to parent components.
+
+HELPFUL: The `output()` function is currently in [developer preview](/reference/releases#developer-preview).
+
+
+import {Component, output} from '@angular/core';
+
+@Component({...})
+export class MyComp {
+ onNameChange = output() // OutputEmitterRef
+
+ setNewName(newName: string) {
+ this.onNameChange.emit(newName);
+ }
+}
+
+
+An output is automatically recognized by Angular whenever you use the `output` function as an initializer of a class member.
+Parent components can listen to outputs in templates by using the event binding syntax.
+
+```html
+
+```
+
+## Aliasing an output
+
+Angular uses the class member name as the name of the output.
+You can alias outputs to change their public name to be different.
+
+```typescript
+class MyComp {
+ onNameChange = output({alias: 'ngxNameChange'});
+}
+```
+
+This allows users to bind to your output using `(ngxNameChange)`, while inside your component you can access the output emitter using `this.onNameChange`.
+
+## Subscribing programmatically
+
+Consumers may create your component dynamically with a reference to a `ComponentRef`.
+In those cases, parents can subscribe to outputs by directly accessing the property of type `OutputRef`.
+
+```ts
+const myComp = viewContainerRef.createComponent(...);
+
+myComp.instance.onNameChange.subscribe(newName => {
+ console.log(newName);
+});
+```
+
+Angular will automatically clean up the subscription when `myComp` is destroyed.
+Alternatively, an object with a function to explicitly unsubscribe earlier is returned.
+
+## Using RxJS observables as source
+
+In some cases, you may want to emit output values based on RxJS observables.
+Angular provides a way to use RxJS observables as source for outputs.
+
+The `outputFromObservable` function is a compiler primitive, similar to the `output()` function, and declares outputs that are driven by RxJS observables.
+
+
+import {Directive} from '@angular/core';
+import {outputFromObservable} from '@angular/core/rxjs-interop';
+
+@Directive(...)
+class MyDir {
+ nameChange$ = this.dataService.get(); // Observable
+ nameChange = outputFromObservable(this.nameChange$);
+}
+
+
+Angular will forward subscriptions to the observable, but will stop forwarding values when the owning directive is destroyed.
+In the example above, if `MyDir` is destroyed, `nameChange` will no longer emit values.
+
+HELPFUL: Most of the time, using `output()` is sufficient and you can emit values imperatively.
+
+## Converting an output to an observable
+
+You can subscribe to outputs by calling `.subscribe` method on `OutputRef`.
+In other cases, Angular provides a helper function that converts an `OutputRef` to an observable.
+
+
+import {outputToObservable} from '@angular/core/rxjs-interop';
+
+@Component(...)
+class MyComp {
+ onNameChange = output();
+}
+
+// Instance reference to `MyComp`.
+const myComp: MyComp;
+
+outputToObservable(this.myComp.instance.onNameChange) // Observable
+ .pipe(...)
+ .subscribe(...);
+
+
+## Why you should use `output()` over decorator-based `@Output()`?
+
+The `output()` function provides numerous benefits over decorator-based `@Output` and `EventEmitter`:
+
+1. Simpler mental model and API:
+ • No concept of error channel, completion channels, or other APIs from RxJS.
+ • Outputs are simple emitters. You can emit values using the `.emit` function.
+2. More accurate types.
+ • `OutputEmitterRef.emit(value)` is now correctly typed, while `EventEmitter` has broken types and can cause runtime errors.
diff --git a/adev-es/src/content/guide/components/output-function.md b/adev-es/src/content/guide/components/output-function.md
index 7723178..da940f6 100644
--- a/adev-es/src/content/guide/components/output-function.md
+++ b/adev-es/src/content/guide/components/output-function.md
@@ -1,9 +1,9 @@
-# Function-based outputs
+# Outputs basados en funciones
-The `output()` function declares an output in a directive or component.
-Outputs allow you to emit values to parent components.
+La función `output()` declara un output en una directiva o componente.
+Los outputs te permiten emitir valores a los componentes padre.
-HELPFUL: The `output()` function is currently in [developer preview](/reference/releases#developer-preview).
+ÚTIL: La función `output()` está actualmente en [developer preview](/reference/releases#developer-preview).
import {Component, output} from '@angular/core';
@@ -18,17 +18,17 @@ export class MyComp {
}
-An output is automatically recognized by Angular whenever you use the `output` function as an initializer of a class member.
-Parent components can listen to outputs in templates by using the event binding syntax.
+Un output es automáticamente reconocido por Angular cada vez que usas la función `output` como inicializador de un miembro de clase.
+Los componentes padre pueden escuchar outputs en las plantillas usando la sintaxis de enlace de eventos.
```html
```
-## Aliasing an output
+## Alias de un output
-Angular uses the class member name as the name of the output.
-You can alias outputs to change their public name to be different.
+Angular usa el nombre del miembro de clase como el nombre del output.
+Puedes crear un alias para los outputs para cambiar su nombre público y que sea diferente.
```typescript
class MyComp {
@@ -36,12 +36,12 @@ class MyComp {
}
```
-This allows users to bind to your output using `(ngxNameChange)`, while inside your component you can access the output emitter using `this.onNameChange`.
+Esto permite a los usuarios enlazar a tu output usando `(ngxNameChange)`, mientras que dentro de tu componente puedes acceder al emisor de output usando `this.onNameChange`.
-## Subscribing programmatically
+## Suscripción programática
-Consumers may create your component dynamically with a reference to a `ComponentRef`.
-In those cases, parents can subscribe to outputs by directly accessing the property of type `OutputRef`.
+Los consumidores pueden crear tu componente dinámicamente con una referencia a un `ComponentRef`.
+En esos casos, los padres pueden suscribirse a los outputs accediendo directamente a la propiedad de tipo `OutputRef`.
```ts
const myComp = viewContainerRef.createComponent(...);
@@ -51,15 +51,15 @@ myComp.instance.onNameChange.subscribe(newName => {
});
```
-Angular will automatically clean up the subscription when `myComp` is destroyed.
-Alternatively, an object with a function to explicitly unsubscribe earlier is returned.
+Angular limpiará automáticamente la suscripción cuando `myComp` sea destruido.
+Alternativamente, se devuelve un objeto con una función para cancelar explícitamente la suscripción antes.
-## Using RxJS observables as source
+## Usando observables de RxJS como fuente
-In some cases, you may want to emit output values based on RxJS observables.
-Angular provides a way to use RxJS observables as source for outputs.
+En algunos casos, puedes querer emitir valores de output basados en observables de RxJS.
+Angular proporciona una forma de usar observables de RxJS como fuente para outputs.
-The `outputFromObservable` function is a compiler primitive, similar to the `output()` function, and declares outputs that are driven by RxJS observables.
+La función `outputFromObservable` es una primitiva del compilador, similar a la función `output()`, y declara outputs que son impulsados por observables de RxJS.
import {Directive} from '@angular/core';
@@ -72,15 +72,15 @@ class MyDir {
}
-Angular will forward subscriptions to the observable, but will stop forwarding values when the owning directive is destroyed.
-In the example above, if `MyDir` is destroyed, `nameChange` will no longer emit values.
+Angular reenviará las suscripciones al observable, pero dejará de reenviar valores cuando la directiva propietaria sea destruida.
+En el ejemplo anterior, si `MyDir` es destruida, `nameChange` dejará de emitir valores.
-HELPFUL: Most of the time, using `output()` is sufficient and you can emit values imperatively.
+ÚTIL: La mayoría de las veces, usar `output()` es suficiente y puedes emitir valores imperativamente.
-## Converting an output to an observable
+## Convirtiendo un output a un observable
-You can subscribe to outputs by calling `.subscribe` method on `OutputRef`.
-In other cases, Angular provides a helper function that converts an `OutputRef` to an observable.
+Puedes suscribirte a outputs llamando al método `.subscribe` en `OutputRef`.
+En otros casos, Angular proporciona una función auxiliar que convierte un `OutputRef` a un observable.
import {outputToObservable} from '@angular/core/rxjs-interop';
@@ -90,7 +90,7 @@ class MyComp {
onNameChange = output();
}
-// Instance reference to `MyComp`.
+// Referencia de instancia a `MyComp`.
const myComp: MyComp;
outputToObservable(this.myComp.instance.onNameChange) // Observable
@@ -98,12 +98,12 @@ outputToObservable(this.myComp.instance.onNameChange) // Observable
.subscribe(...);
-## Why you should use `output()` over decorator-based `@Output()`?
+## ¿Por qué deberías usar `output()` sobre `@Output()` basado en decoradores?
-The `output()` function provides numerous benefits over decorator-based `@Output` and `EventEmitter`:
+La función `output()` proporciona numerosos beneficios sobre `@Output` y `EventEmitter` basados en decoradores:
-1. Simpler mental model and API:
- • No concept of error channel, completion channels, or other APIs from RxJS.
- • Outputs are simple emitters. You can emit values using the `.emit` function.
-2. More accurate types.
- • `OutputEmitterRef.emit(value)` is now correctly typed, while `EventEmitter` has broken types and can cause runtime errors.
+1. Modelo mental y API más simples:
+ • Sin concepto de canal de error, canales de completado, u otras APIs de RxJS.
+ • Los outputs son simples emisores. Puedes emitir valores usando la función `.emit`.
+2. Tipos más precisos.
+ • `OutputEmitterRef.emit(value)` ahora está correctamente tipado, mientras que `EventEmitter` tiene tipos rotos y puede causar errores en tiempo de ejecución.
diff --git a/adev-es/src/content/guide/components/outputs.en.md b/adev-es/src/content/guide/components/outputs.en.md
new file mode 100644
index 0000000..57a302c
--- /dev/null
+++ b/adev-es/src/content/guide/components/outputs.en.md
@@ -0,0 +1,180 @@
+# Custom events with outputs
+
+TIP: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular.
+
+Angular components can define custom events by assigning a property to the `output` function:
+
+```ts {highlight:[3]}
+@Component({/*...*/})
+export class ExpandablePanel {
+ panelClosed = output();
+}
+```
+
+```angular-html
+
+```
+
+The `output` function returns an `OutputEmitterRef`. You can emit an event by calling the `emit` method on the `OutputEmitterRef`:
+
+```ts
+ this.panelClosed.emit();
+```
+
+Angular refers to properties initialized with the `output` function as **outputs**. You can use outputs to raise custom events, similar to native browser events like `click`.
+
+**Angular custom events do not bubble up the DOM**.
+
+**Output names are case-sensitive.**
+
+When extending a component class, **outputs are inherited by the child class.**
+
+The `output` function has special meaning to the Angular compiler. **You can exclusively call `output` in component and directive property initializers.**
+
+## Emitting event data
+
+You can pass event data when calling `emit`:
+
+```ts
+// You can emit primitive values.
+this.valueChanged.emit(7);
+
+// You can emit custom event objects
+this.thumbDropped.emit({
+ pointerX: 123,
+ pointerY: 456,
+})
+```
+
+When defining an event listener in a template, you can access the event data from the `$event` variable:
+
+```angular-html
+
+```
+
+Receive the event data in the parent component:
+
+```ts
+@Component({
+ /*...*/
+})
+export class App {
+ logValue(value: number) {
+ ...
+ }
+}
+
+```
+
+## Customizing output names
+
+The `output` function accepts a parameter that lets you specify a different name for the event in a template:
+
+```ts
+@Component({/*...*/})
+export class CustomSlider {
+ changed = output({alias: 'valueChanged'});
+}
+```
+
+```angular-html
+
+```
+
+This alias does not affect usage of the property in TypeScript code.
+
+While you should generally avoid aliasing outputs for components, this feature can be useful for renaming properties while preserving an alias for the original name or for avoiding collisions with the name of native DOM events.
+
+## Subscribing to outputs programmatically
+
+When creating a component dynamically, you can programmatically subscribe to output events
+from the component instance. The `OutputRef` type includes a `subscribe` method:
+
+```ts
+const someComponentRef: ComponentRef = viewContainerRef.createComponent(/*...*/);
+
+someComponentRef.instance.someEventProperty.subscribe(eventData => {
+ console.log(eventData);
+});
+```
+
+Angular automatically cleans up event subscriptions when it destroys components with subscribers. Alternatively, you can manually unsubscribe from an event. The `subscribe` function returns an `OutputRefSubscription` with an `unsubscribe` method:
+
+```ts
+const eventSubscription = someComponent.someEventProperty.subscribe(eventData => {
+ console.log(eventData);
+});
+
+// ...
+
+eventSubscription.unsubscribe();
+```
+
+## Choosing event names
+
+Avoid choosing output names that collide with events on DOM elements like HTMLElement. Name collisions introduce confusion about whether the bound property belongs to the component or the DOM element.
+
+Avoid adding prefixes for component outputs like you would with component selectors. Since a given element can only host one component, any custom properties can be assumed to belong to the component.
+
+Always use [camelCase](https://en.wikipedia.org/wiki/Camel_case) output names. Avoid prefixing output names with "on".
+
+## Using outputs with RxJS
+
+See [RxJS interop with component and directive outputs](ecosystem/rxjs-interop/output-interop) for details on interoperability between outputs and RxJS.
+
+## Declaring outputs with the `@Output` decorator
+
+TIP: While the Angular team recommends using the `output` function for new projects, the
+original decorator-based `@Output` API remains fully supported.
+
+You can alternatively define custom events by assigning a property to a new `EventEmitter` and adding the `@Output` decorator:
+
+```ts
+@Component({/*...*/})
+export class ExpandablePanel {
+ @Output() panelClosed = new EventEmitter();
+}
+```
+
+You can emit an event by calling the `emit` method on the `EventEmitter`.
+
+### Aliases with the `@Output` decorator
+
+The `@Output` decorator accepts a parameter that lets you specify a different name for the event in a template:
+
+```ts
+@Component({/*...*/})
+export class CustomSlider {
+ @Output('valueChanged') changed = new EventEmitter();
+}
+```
+
+```angular-html
+
+```
+
+This alias does not affect usage of the property in TypeScript code.
+
+## Specify outputs in the `@Component` decorator
+
+In addition to the `@Output` decorator, you can also specify a component's outputs with the `outputs` property in the `@Component` decorator. This can be useful when a component inherits a property from a base class:
+
+```ts
+// `CustomSlider` inherits the `valueChanged` property from `BaseSlider`.
+@Component({
+ /*...*/
+ outputs: ['valueChanged'],
+})
+export class CustomSlider extends BaseSlider {}
+```
+
+You can additionally specify an output alias in the `outputs` list by putting the alias after a colon in the string:
+
+```ts
+// `CustomSlider` inherits the `valueChanged` property from `BaseSlider`.
+@Component({
+ /*...*/
+ outputs: ['valueChanged: volumeChanged'],
+})
+export class CustomSlider extends BaseSlider {}
+```
diff --git a/adev-es/src/content/guide/components/outputs.md b/adev-es/src/content/guide/components/outputs.md
index 57a302c..bd666ce 100644
--- a/adev-es/src/content/guide/components/outputs.md
+++ b/adev-es/src/content/guide/components/outputs.md
@@ -1,8 +1,8 @@
-# Custom events with outputs
+# Eventos personalizados con outputs
-TIP: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular.
+CONSEJO: Esta guía asume que ya has leído la [Guía de Esenciales](essentials). Lee esa primero si eres nuevo en Angular.
-Angular components can define custom events by assigning a property to the `output` function:
+Los componentes de Angular pueden definir eventos personalizados asignando una propiedad a la función `output`:
```ts {highlight:[3]}
@Component({/*...*/})
@@ -15,44 +15,44 @@ export class ExpandablePanel {
```
-The `output` function returns an `OutputEmitterRef`. You can emit an event by calling the `emit` method on the `OutputEmitterRef`:
+La función `output` devuelve un `OutputEmitterRef`. Puedes emitir un evento llamando al método `emit` en el `OutputEmitterRef`:
```ts
this.panelClosed.emit();
```
-Angular refers to properties initialized with the `output` function as **outputs**. You can use outputs to raise custom events, similar to native browser events like `click`.
+Angular se refiere a las propiedades inicializadas con la función `output` como **outputs**. Puedes usar outputs para generar eventos personalizados, similares a los eventos nativos del navegador como `click`.
-**Angular custom events do not bubble up the DOM**.
+**Los eventos personalizados de Angular no propagan hacia arriba en el DOM**.
-**Output names are case-sensitive.**
+**Los nombres de output distinguen entre mayúsculas y minúsculas.**
-When extending a component class, **outputs are inherited by the child class.**
+Al extender una clase de componente, **los outputs son heredados por la clase hija.**
-The `output` function has special meaning to the Angular compiler. **You can exclusively call `output` in component and directive property initializers.**
+La función `output` tiene un significado especial para el compilador de Angular. **Solo puedes llamar a `output` en inicializadores de propiedades de componentes y directivas.**
-## Emitting event data
+## Emitir datos del evento
-You can pass event data when calling `emit`:
+Puedes pasar datos del evento al llamar a `emit`:
```ts
-// You can emit primitive values.
+// Puedes emitir valores primitivos.
this.valueChanged.emit(7);
-// You can emit custom event objects
+// Puedes emitir objetos de evento personalizados
this.thumbDropped.emit({
pointerX: 123,
pointerY: 456,
})
```
-When defining an event listener in a template, you can access the event data from the `$event` variable:
+Al definir un event listener en una plantilla, puedes acceder a los datos del evento desde la variable `$event`:
```angular-html
```
-Receive the event data in the parent component:
+Recibe los datos del evento en el componente padre:
```ts
@Component({
@@ -66,9 +66,9 @@ export class App {
```
-## Customizing output names
+## Personalizar nombres de output
-The `output` function accepts a parameter that lets you specify a different name for the event in a template:
+La función `output` acepta un parámetro que te permite especificar un nombre diferente para el evento en una plantilla:
```ts
@Component({/*...*/})
@@ -81,14 +81,14 @@ export class CustomSlider {
```
-This alias does not affect usage of the property in TypeScript code.
+Este alias no afecta el uso de la propiedad en código TypeScript.
-While you should generally avoid aliasing outputs for components, this feature can be useful for renaming properties while preserving an alias for the original name or for avoiding collisions with the name of native DOM events.
+Aunque generalmente debes evitar usar alias para outputs de componentes, esta característica puede ser útil para renombrar propiedades mientras se preserva un alias para el nombre original o para evitar colisiones con el nombre de eventos DOM nativos.
-## Subscribing to outputs programmatically
+## Suscribirse a outputs programáticamente
-When creating a component dynamically, you can programmatically subscribe to output events
-from the component instance. The `OutputRef` type includes a `subscribe` method:
+Al crear un componente dinámicamente, puedes suscribirte programáticamente a eventos de output
+desde la instancia del componente. El tipo `OutputRef` incluye un método `subscribe`:
```ts
const someComponentRef: ComponentRef = viewContainerRef.createComponent(/*...*/);
@@ -98,7 +98,7 @@ someComponentRef.instance.someEventProperty.subscribe(eventData => {
});
```
-Angular automatically cleans up event subscriptions when it destroys components with subscribers. Alternatively, you can manually unsubscribe from an event. The `subscribe` function returns an `OutputRefSubscription` with an `unsubscribe` method:
+Angular limpia automáticamente las suscripciones de eventos cuando destruye componentes con suscriptores. Alternativamente, puedes cancelar manualmente la suscripción a un evento. La función `subscribe` devuelve un `OutputRefSubscription` con un método `unsubscribe`:
```ts
const eventSubscription = someComponent.someEventProperty.subscribe(eventData => {
@@ -110,24 +110,24 @@ const eventSubscription = someComponent.someEventProperty.subscribe(eventData =>
eventSubscription.unsubscribe();
```
-## Choosing event names
+## Elegir nombres de eventos
-Avoid choosing output names that collide with events on DOM elements like HTMLElement. Name collisions introduce confusion about whether the bound property belongs to the component or the DOM element.
+Evita elegir nombres de output que colisionen con eventos en elementos DOM como HTMLElement. Las colisiones de nombres introducen confusión sobre si la propiedad enlazada pertenece al componente o al elemento DOM.
-Avoid adding prefixes for component outputs like you would with component selectors. Since a given element can only host one component, any custom properties can be assumed to belong to the component.
+Evita agregar prefijos para outputs de componentes como lo harías con selectores de componentes. Dado que un elemento dado solo puede alojar un componente, se puede asumir que cualquier propiedad personalizada pertenece al componente.
-Always use [camelCase](https://en.wikipedia.org/wiki/Camel_case) output names. Avoid prefixing output names with "on".
+Siempre usa [camelCase](https://en.wikipedia.org/wiki/Camel_case) para nombres de output. Evita prefijar nombres de output con "on".
-## Using outputs with RxJS
+## Usar outputs con RxJS
-See [RxJS interop with component and directive outputs](ecosystem/rxjs-interop/output-interop) for details on interoperability between outputs and RxJS.
+Consulta [Interoperabilidad de RxJS con outputs de componentes y directivas](ecosystem/rxjs-interop/output-interop) para detalles sobre la interoperabilidad entre outputs y RxJS.
-## Declaring outputs with the `@Output` decorator
+## Declarar outputs con el decorador `@Output`
-TIP: While the Angular team recommends using the `output` function for new projects, the
-original decorator-based `@Output` API remains fully supported.
+CONSEJO: Aunque el equipo de Angular recomienda usar la función `output` para proyectos nuevos, la
+API original basada en decoradores `@Output` sigue siendo completamente compatible.
-You can alternatively define custom events by assigning a property to a new `EventEmitter` and adding the `@Output` decorator:
+Alternativamente puedes definir eventos personalizados asignando una propiedad a un nuevo `EventEmitter` y agregando el decorador `@Output`:
```ts
@Component({/*...*/})
@@ -136,11 +136,11 @@ export class ExpandablePanel {
}
```
-You can emit an event by calling the `emit` method on the `EventEmitter`.
+Puedes emitir un evento llamando al método `emit` en el `EventEmitter`.
-### Aliases with the `@Output` decorator
+### Alias con el decorador `@Output`
-The `@Output` decorator accepts a parameter that lets you specify a different name for the event in a template:
+El decorador `@Output` acepta un parámetro que te permite especificar un nombre diferente para el evento en una plantilla:
```ts
@Component({/*...*/})
@@ -153,14 +153,14 @@ export class CustomSlider {
```
-This alias does not affect usage of the property in TypeScript code.
+Este alias no afecta el uso de la propiedad en código TypeScript.
-## Specify outputs in the `@Component` decorator
+## Especificar outputs en el decorador `@Component`
-In addition to the `@Output` decorator, you can also specify a component's outputs with the `outputs` property in the `@Component` decorator. This can be useful when a component inherits a property from a base class:
+Además del decorador `@Output`, también puedes especificar los outputs de un componente con la propiedad `outputs` en el decorador `@Component`. Esto puede ser útil cuando un componente hereda una propiedad de una clase base:
```ts
-// `CustomSlider` inherits the `valueChanged` property from `BaseSlider`.
+// `CustomSlider` hereda la propiedad `valueChanged` de `BaseSlider`.
@Component({
/*...*/
outputs: ['valueChanged'],
@@ -168,10 +168,10 @@ In addition to the `@Output` decorator, you can also specify a component's outpu
export class CustomSlider extends BaseSlider {}
```
-You can additionally specify an output alias in the `outputs` list by putting the alias after a colon in the string:
+Además puedes especificar un alias de output en la lista `outputs` poniendo el alias después de dos puntos en la cadena:
```ts
-// `CustomSlider` inherits the `valueChanged` property from `BaseSlider`.
+// `CustomSlider` hereda la propiedad `valueChanged` de `BaseSlider`.
@Component({
/*...*/
outputs: ['valueChanged: volumeChanged'],
diff --git a/adev-es/src/content/guide/components/programmatic-rendering.en.md b/adev-es/src/content/guide/components/programmatic-rendering.en.md
new file mode 100644
index 0000000..e604e73
--- /dev/null
+++ b/adev-es/src/content/guide/components/programmatic-rendering.en.md
@@ -0,0 +1,255 @@
+# Programmatically rendering components
+
+TIP: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular.
+
+In addition to using a component directly in a template, you can also dynamically render components
+programmatically. This is helpful for situations when a component is unknown initially (thus can not
+be referenced in a template directly) and it depends on some conditions.
+
+There are two main ways to render a component programmatically: in a template using `NgComponentOutlet`,
+or in your TypeScript code using `ViewContainerRef`.
+
+HELPFUL: for lazy-loading use-cases (for example if you want to delay loading of a heavy component), consider
+using the built-in [`@defer` feature](/guide/templates/defer) instead. The `@defer` feature allows the code
+of any components, directives, and pipes inside the `@defer` block to be extracted into separate JavaScript
+chunks automatically and loaded only when necessary, based on the configured triggers.
+
+## Using NgComponentOutlet
+
+`NgComponentOutlet` is a structural directive that dynamically renders a given component in a
+template.
+
+```angular-ts
+@Component({ ... })
+export class AdminBio { /* ... */ }
+
+@Component({ ... })
+export class StandardBio { /* ... */ }
+
+@Component({
+ ...,
+ template: `
+
Profile for {{user.name}}
+ `
+})
+export class CustomDialog {
+ user = input.required();
+
+ getBioComponent() {
+ return this.user().isAdmin ? AdminBio : StandardBio;
+ }
+}
+```
+
+See the [NgComponentOutlet API reference](api/common/NgComponentOutlet) for more information on the
+directive's capabilities.
+
+## Using ViewContainerRef
+
+A **view container** is a node in Angular's component tree that can contain content. Any component
+or directive can inject `ViewContainerRef` to get a reference to a view container corresponding to
+that component or directive's location in the DOM.
+
+You can use the `createComponent`method on `ViewContainerRef` to dynamically create and render a
+component. When you create a new component with a `ViewContainerRef`, Angular appends it into the
+DOM as the next sibling of the component or directive that injected the `ViewContainerRef`.
+
+```angular-ts
+@Component({
+ selector: 'leaf-content',
+ template: `
+ This is the leaf content
+ `,
+})
+export class LeafContent {}
+
+@Component({
+ selector: 'outer-container',
+ template: `
+
This is the start of the outer container
+
+
This is the end of the outer container
+ `,
+})
+export class OuterContainer {}
+
+@Component({
+ selector: 'inner-item',
+ template: `
+
+ `,
+})
+export class InnerItem {
+ private viewContainer = inject(ViewContainerRef);
+
+ loadContent() {
+ this.viewContainer.createComponent(LeafContent);
+ }
+}
+```
+
+In the example above, clicking the "Load content" button results in the following DOM structure
+
+```angular-html
+
+
This is the start of the outer container
+
+
+
+ This is the leaf content
+
This is the end of the outer container
+
+```
+
+## Lazy-loading components
+
+HELPFUL: if you want to lazy-load some components, you may consider using the built-in [`@defer` feature](/guide/templates/defer)
+instead.
+
+If your use-case is not covered by the `@defer` feature, you can use either `NgComponentOutlet` or
+`ViewContainerRef` with a standard JavaScript [dynamic import](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/import).
+
+```angular-ts
+@Component({
+ ...,
+ template: `
+
+
Basic settings
+
+
+
+
Advanced settings
+ @if(!advancedSettings) {
+
+ }
+
+
+ `
+})
+export class AdminSettings {
+ advancedSettings: {new(): AdvancedSettings} | undefined;
+
+ async loadAdvanced() {
+ const { AdvancedSettings } = await import('path/to/advanced_settings.js');
+ this.advancedSettings = AdvancedSettings;
+ }
+}
+```
+
+The example above loads and displays the `AdvancedSettings` upon receiving a button click.
+
+## Binding inputs, outputs and setting host directives at creation
+
+When dynamically creating components, manually setting inputs and subscribing to outputs can be error-prone. You often need to write extra code just to wire up bindings after the component is instantiated.
+
+To simplify this, both `createComponent` and `ViewContainerRef.createComponent` support passing a `bindings` array with helpers like `inputBinding()`, `outputBinding()`, and `twoWayBinding()` to configure inputs and outputs up front. You can also specify a `directives` array to apply any host directives. This enables creating components programmatically with template-like bindings in a single, declarative call.
+
+### Host view using `ViewContainerRef.createComponent`
+
+`ViewContainerRef.createComponent` creates a component and automatically inserts its host view and host element into the container's view hierarchy at the container's location. Use this when the dynamic component should become part of the container's logical and visual structure (for example, adding list items or inline UI).
+
+By contrast, the standalone `createComponent` API does not attach the new component to any existing view or DOM location — it returns a `ComponentRef` and gives you explicit control over where to place the component's host element.
+
+```angular-ts
+import { Component, input, model, output } from "@angular/core";
+
+@Component({
+ selector: 'app-warning',
+ template: `
+ @if(isExpanded()) {
+
+
Warning: Action needed!
+
+
+ }
+ `
+})
+export class AppWarningComponent {
+ readonly canClose = input.required();
+ readonly isExpanded = model();
+ readonly close = output();
+}
+```
+
+```ts
+import { Component, ViewContainerRef, signal, inputBinding, outputBinding, twoWayBinding, inject } from '@angular/core';
+import { FocusTrap } from "@angular/cdk/a11y";
+import { ThemeDirective } from '../theme.directive';
+
+@Component({
+ template: ``
+})
+export class HostComponent {
+ private vcr = inject(ViewContainerRef);
+ readonly canClose = signal(true);
+ readonly isExpanded = signal(true);
+
+ showWarning() {
+ const compRef = this.vcr.createComponent(AppWarningComponent, {
+ bindings: [
+ inputBinding('canClose', this.canClose),
+ twoWayBinding('isExpanded', this.isExpanded),
+ outputBinding('close', (confirmed) => {
+ console.log('Closed with result:', confirmed);
+ })
+ ],
+ directives: [
+ FocusTrap,
+ { type: ThemeDirective, bindings: [inputBinding('theme', () => 'warning')] }
+ ]
+ });
+ }
+}
+```
+
+In the example above, the dynamic **AppWarningComponent** is created with its `canClose` input bound to a reactive signal, a two-way binding on its `isExpanded` state, and an output listener for `close`. The `FocusTrap` and `ThemeDirective` are attached to the host element via `directives`.
+
+### Popup attached to `document.body` with `createComponent` + `hostElement`
+
+Use this when rendering outside the current view hierarchy (e.g., overlays). The provided `hostElement` becomes the component's host in the DOM, so Angular doesn't create a new element matching the selector. Lets you configure **bindings** directly.
+
+```ts
+import {
+ ApplicationRef,
+ createComponent,
+ EnvironmentInjector,
+ inject,
+ Injectable,
+ inputBinding,
+ outputBinding,
+} from '@angular/core';
+import { PopupComponent } from './popup.component';
+
+@Injectable({ providedIn: 'root' })
+export class PopupService {
+ private readonly injector = inject(EnvironmentInjector);
+ private readonly appRef = inject(ApplicationRef);
+
+ show(message: string) {
+ // Create a host element for the popup
+ const host = document.createElement('popup-host');
+
+ // Create the component and bind in one call
+ const ref = createComponent(PopupComponent, {
+ environmentInjector: this.injector,
+ hostElement: host,
+ bindings: [
+ inputBinding('message', () => message),
+ outputBinding('closed', () => {
+ document.body.removeChild(host);
+ this.appRef.detachView(ref.hostView);
+ ref.destroy();
+ }),
+ ],
+ });
+
+ // Registers the component's view so it participates in change detection cycle.
+ this.appRef.attachView(ref.hostView);
+ // Inserts the provided host element into the DOM (outside the normal Angular view hierarchy).
+ // This is what makes the popup visible on screen, typically used for overlays or modals.
+ document.body.appendChild(host);
+ }
+}
+```
diff --git a/adev-es/src/content/guide/components/programmatic-rendering.md b/adev-es/src/content/guide/components/programmatic-rendering.md
index 51887ae..5e85df9 100644
--- a/adev-es/src/content/guide/components/programmatic-rendering.md
+++ b/adev-es/src/content/guide/components/programmatic-rendering.md
@@ -1,23 +1,23 @@
-# Programmatically rendering components
+# Renderizado programático de componentes
-TIP: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular.
+CONSEJO: Esta guía asume que ya has leído la [Guía de Esenciales](essentials). Lee eso primero si eres nuevo en Angular.
-In addition to using a component directly in a template, you can also dynamically render components
-programmatically. This is helpful for situations when a component is unknown initially (thus can not
-be referenced in a template directly) and it depends on some conditions.
+Además de usar un componente directamente en una plantilla, también puedes renderizar componentes dinámicamente
+de forma programática. Esto es útil para situaciones cuando un componente es desconocido inicialmente (por lo tanto no puede
+ser referenciado en una plantilla directamente) y depende de algunas condiciones.
-There are two main ways to render a component programmatically: in a template using `NgComponentOutlet`,
-or in your TypeScript code using `ViewContainerRef`.
+Hay dos formas principales de renderizar un componente programáticamente: en una plantilla usando `NgComponentOutlet`,
+o en tu código TypeScript usando `ViewContainerRef`.
-HELPFUL: for lazy-loading use-cases (for example if you want to delay loading of a heavy component), consider
-using the built-in [`@defer` feature](/guide/templates/defer) instead. The `@defer` feature allows the code
-of any components, directives, and pipes inside the `@defer` block to be extracted into separate JavaScript
-chunks automatically and loaded only when necessary, based on the configured triggers.
+ÚTIL: para casos de uso de carga diferida (por ejemplo si quieres retrasar la carga de un componente pesado), considera
+usar la funcionalidad incorporada [`@defer`](/guide/templates/defer) en su lugar. La funcionalidad `@defer` permite que el código
+de cualquier componente, directiva y pipe dentro del bloque `@defer` sea extraído en chunks de JavaScript
+separados automáticamente y cargados solo cuando sea necesario, basado en los triggers configurados.
-## Using NgComponentOutlet
+## Usando NgComponentOutlet
-`NgComponentOutlet` is a structural directive that dynamically renders a given component in a
-template.
+`NgComponentOutlet` es una directiva estructural que renderiza dinámicamente un componente dado en una
+plantilla.
```angular-ts
@Component({ ... })
@@ -41,18 +41,18 @@ export class CustomDialog {
}
```
-See the [NgComponentOutlet API reference](api/common/NgComponentOutlet) for more information on the
-directive's capabilities.
+Ve la [referencia de API de NgComponentOutlet](api/common/NgComponentOutlet) para más información sobre las
+capacidades de la directiva.
-## Using ViewContainerRef
+## Usando ViewContainerRef
-A **view container** is a node in Angular's component tree that can contain content. Any component
-or directive can inject `ViewContainerRef` to get a reference to a view container corresponding to
-that component or directive's location in the DOM.
+Un **contenedor de vista** es un nodo en el árbol de componentes de Angular que puede contener contenido. Cualquier componente
+o directiva puede inyectar `ViewContainerRef` para obtener una referencia a un contenedor de vista correspondiente a
+la ubicación de ese componente o directiva en el DOM.
-You can use the `createComponent`method on `ViewContainerRef` to dynamically create and render a
-component. When you create a new component with a `ViewContainerRef`, Angular appends it into the
-DOM as the next sibling of the component or directive that injected the `ViewContainerRef`.
+Puedes usar el método `createComponent` en `ViewContainerRef` para crear y renderizar dinámicamente un
+componente. Cuando creas un nuevo componente con un `ViewContainerRef`, Angular lo añade al
+DOM como el siguiente hermano del componente o directiva que inyectó el `ViewContainerRef`.
```angular-ts
@Component({
@@ -88,7 +88,7 @@ export class InnerItem {
}
```
-In the example above, clicking the "Load content" button results in the following DOM structure
+En el ejemplo anterior, hacer clic en el botón "Load content" resulta en la siguiente estructura DOM
```angular-html
@@ -101,13 +101,13 @@ In the example above, clicking the "Load content" button results in the followin
```
-## Lazy-loading components
+## Carga diferida de componentes
-HELPFUL: if you want to lazy-load some components, you may consider using the built-in [`@defer` feature](/guide/templates/defer)
-instead.
+ÚTIL: si quieres cargar de forma diferida algunos componentes, puedes considerar usar la funcionalidad incorporada [`@defer`](/guide/templates/defer)
+en su lugar.
-If your use-case is not covered by the `@defer` feature, you can use either `NgComponentOutlet` or
-`ViewContainerRef` with a standard JavaScript [dynamic import](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/import).
+Si tu caso de uso no está cubierto por la funcionalidad `@defer`, puedes usar ya sea `NgComponentOutlet` o
+`ViewContainerRef` con un [import dinámico](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/import) estándar de JavaScript.
```angular-ts
@Component({
@@ -138,19 +138,19 @@ export class AdminSettings {
}
```
-The example above loads and displays the `AdvancedSettings` upon receiving a button click.
+El ejemplo anterior carga y muestra el `AdvancedSettings` al recibir un clic en el botón.
-## Binding inputs, outputs and setting host directives at creation
+## Enlazando inputs, outputs y estableciendo directivas host en la creación
-When dynamically creating components, manually setting inputs and subscribing to outputs can be error-prone. You often need to write extra code just to wire up bindings after the component is instantiated.
+Cuando creas componentes dinámicamente, establecer inputs manualmente y suscribirse a outputs puede ser propenso a errores. A menudo necesitas escribir código extra solo para conectar los enlaces después de que el componente es instanciado.
-To simplify this, both `createComponent` and `ViewContainerRef.createComponent` support passing a `bindings` array with helpers like `inputBinding()`, `outputBinding()`, and `twoWayBinding()` to configure inputs and outputs up front. You can also specify a `directives` array to apply any host directives. This enables creating components programmatically with template-like bindings in a single, declarative call.
+Para simplificar esto, tanto `createComponent` como `ViewContainerRef.createComponent` soportan pasar un array `bindings` con helpers como `inputBinding()`, `outputBinding()` y `twoWayBinding()` para configurar inputs y outputs de antemano. También puedes especificar un array `directives` para aplicar cualquier directiva host. Esto permite crear componentes programáticamente con enlaces similares a plantillas en una sola llamada declarativa.
-### Host view using `ViewContainerRef.createComponent`
+### Vista host usando `ViewContainerRef.createComponent`
-`ViewContainerRef.createComponent` creates a component and automatically inserts its host view and host element into the container’s view hierarchy at the container’s location. Use this when the dynamic component should become part of the container’s logical and visual structure (for example, adding list items or inline UI).
+`ViewContainerRef.createComponent` crea un componente e inserta automáticamente su vista host y elemento host en la jerarquía de vistas del contenedor en la ubicación del contenedor. Usa esto cuando el componente dinámico debe convertirse en parte de la estructura lógica y visual del contenedor (por ejemplo, añadiendo elementos de lista o UI en línea).
-By contrast, the standalone `createComponent` API does not attach the new component to any existing view or DOM location — it returns a `ComponentRef` and gives you explicit control over where to place the component’s host element.
+Por contraste, la API standalone `createComponent` no adjunta el nuevo componente a ninguna vista existente o ubicación DOM — devuelve un `ComponentRef` y te da control explícito sobre dónde colocar el elemento host del componente.
```angular-ts
import { Component, input, model, output } from "@angular/core";
@@ -204,11 +204,11 @@ export class HostComponent {
}
```
-In the example above, the dynamic **AppWarningComponent** is created with its `canClose` input bound to a reactive signal, a two-way binding on its `isExpanded` state, and an output listener for `close`. The `FocusTrap` and `ThemeDirective` are attached to the host element via `directives`.
+En el ejemplo anterior, el **AppWarningComponent** dinámico es creado con su input `canClose` enlazado a un signal reactivo, un enlace bidireccional en su estado `isExpanded`, y un listener de output para `close`. El `FocusTrap` y `ThemeDirective` están adjuntos al elemento host a través de `directives`.
-### Popup attached to `document.body` with `createComponent` + `hostElement`
+### Popup adjunto a `document.body` con `createComponent` + `hostElement`
-Use this when rendering outside the current view hierarchy (e.g., overlays). The provided `hostElement` becomes the component’s host in the DOM, so Angular doesn’t create a new element matching the selector. Lets you configure **bindings** directly.
+Usa esto cuando renderizas fuera de la jerarquía de vistas actual (por ejemplo, overlays). El `hostElement` proporcionado se convierte en el host del componente en el DOM, por lo que Angular no crea un nuevo elemento que coincida con el selector. Te permite configurar **bindings** directamente.
```ts
import {
@@ -228,10 +228,10 @@ export class PopupService {
private readonly appRef = inject(ApplicationRef);
show(message: string) {
- // Create a host element for the popup
+ // Crear un elemento host para el popup
const host = document.createElement('popup-host');
- // Create the component and bind in one call
+ // Crear el componente y enlazar en una sola llamada
const ref = createComponent(PopupComponent, {
environmentInjector: this.injector,
hostElement: host,
@@ -245,10 +245,10 @@ export class PopupService {
],
});
- // Registers the component’s view so it participates in change detection cycle.
+ // Registra la vista del componente para que participe en el ciclo de detección de cambios.
this.appRef.attachView(ref.hostView);
- // Inserts the provided host element into the DOM (outside the normal Angular view hierarchy).
- // This is what makes the popup visible on screen, typically used for overlays or modals.
+ // Inserta el elemento host proporcionado en el DOM (fuera de la jerarquía normal de vistas de Angular).
+ // Esto es lo que hace el popup visible en pantalla, típicamente usado para overlays o modales.
document.body.appendChild(host);
}
}
diff --git a/adev-es/src/content/guide/components/queries.en.md b/adev-es/src/content/guide/components/queries.en.md
new file mode 100644
index 0000000..075d2c7
--- /dev/null
+++ b/adev-es/src/content/guide/components/queries.en.md
@@ -0,0 +1,458 @@
+# Referencing component children with queries
+
+TIP: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular.
+
+A component can define **queries** that find child elements and read values from their injectors.
+
+Developers most commonly use queries to retrieve references to child components, directives, DOM elements, and more.
+
+All query functions return signals that reflect the most up-to-date results. You can read the
+result by calling the signal function, including in reactive contexts like `computed` and `effect`.
+
+There are two categories of query: **view queries** and **content queries.**
+
+## View queries
+
+View queries retrieve results from the elements in the component's _view_ — the elements defined in the component's own template. You can query for a single result with the `viewChild` function.
+
+```typescript {highlight: [14, 15]}
+@Component({
+ selector: 'custom-card-header',
+ /*...*/
+})
+export class CustomCardHeader {
+ text: string;
+}
+
+@Component({
+ selector: 'custom-card',
+ template: 'Visit sunny California!',
+})
+export class CustomCard {
+ header = viewChild(CustomCardHeader);
+ headerText = computed(() => this.header()?.text);
+}
+```
+
+In this example, the `CustomCard` component queries for a child `CustomCardHeader` and uses the result in a `computed`.
+
+If the query does not find a result, its value is `undefined`. This may occur if the target element is hidden by `@if`. Angular keeps the result of `viewChild` up to date as your application state changes.
+
+You can also query for multiple results with the `viewChildren` function.
+
+```typescript {highlight: [17]}
+@Component({
+ selector: 'custom-card-action',
+ /*...*/
+})
+export class CustomCardAction {
+ text: string;
+}
+
+@Component({
+ selector: 'custom-card',
+ template: `Save
+ Cancel
+ `,
+})
+export class CustomCard {
+ actions = viewChildren(CustomCardAction);
+ actionsTexts = computed(() => this.actions().map(action => action.text);
+}
+```
+
+`viewChildren` creates a signal with an `Array` of the query results.
+
+**Queries never pierce through component boundaries.** View queries can only retrieve results from the component's template.
+
+## Content queries
+
+Content queries retrieve results from the elements in the component's _content_— the elements nested inside the component in the template where it's used. You can query for a single result with the `contentChild` function.
+
+```typescript {highlight: [14, 15]}
+@Component({
+ selector: 'custom-toggle',
+ /*...*/
+})
+export class CustomToggle {
+ text: string;
+}
+
+@Component({
+ selector: 'custom-expando',
+ /* ... */
+})
+export class CustomExpando {
+ toggle = contentChild(CustomToggle);
+ toggleText = computed(() => this.toggle()?.text);
+}
+
+@Component({
+/* ... */
+// CustomToggle is used inside CustomExpando as content.
+template: `
+
+ Show
+
+ `
+})
+
+export class UserProfile { }
+```
+
+If the query does not find a result, its value is `undefined`. This may occur if the target element is absent or hidden by `@if`. Angular keeps the result of `contentChild` up to date as your application state changes.
+
+By default, content queries find only _direct_ children of the component and do not traverse into descendants.
+
+You can also query for multiple results with the `contentChildren` function.
+
+```typescript {highlight: [14, 16, 17, 18, 19, 20]}
+@Component({
+ selector: 'custom-menu-item',
+ /*...*/
+})
+export class CustomMenuItem {
+ text: string;
+}
+
+@Component({
+ selector: 'custom-menu',
+ /*...*/
+})
+
+export class CustomMenu {
+ items = contentChildren(CustomMenuItem);
+ itemTexts = computed(() => this.items().map(item => item.text));
+}
+
+@Component({
+ selector: 'user-profile',
+ template: `
+
+ Cheese
+ Tomato
+
+ `
+})
+export class UserProfile { }
+```
+
+`contentChildren` creates a signal with an `Array` of the query results.
+
+**Queries never pierce through component boundaries.** Content queries can only retrieve results from the same template as the component itself.
+
+## Required queries
+
+If a child query (`viewChild` or `contentChild`) does not find a result, its value is `undefined`. This may occur if the target element is hidden by a control flow statement like `@if` or `@for`. Because of this, the child queries return a signal that include `undefined` in their value type.
+
+In some cases, especially with `viewChild`, you know with certainty that a specific child is always available. In other cases, you may want to strictly enforce that a specific child is present. For these cases, you can use a _required query_.
+
+```angular-ts
+@Component({/* ... */})
+export class CustomCard {
+ header = viewChild.required(CustomCardHeader);
+ body = contentChild.required(CustomCardBody);
+}
+```
+
+If a required query does not find a matching result, Angular reports an error. Because this guarantees that a result is available, required queries do not automatically include `undefined` in the signal's value type.
+
+## Query locators
+
+This first parameter for each query decorator is its **locator**.
+
+Most of the time, you want to use a component or directive as your locator.
+
+You can alternatively specify a string locator corresponding to
+a [template reference variable](guide/templates/variables#template-reference-variables).
+
+```angular-ts
+@Component({
+ /*...*/
+ template: `
+
+
+ `
+})
+export class ActionBar {
+ saveButton = viewChild>('save');
+}
+```
+
+If more than one element defines the same template reference variable, the query retrieves the first matching element.
+
+Angular does not support CSS selectors as query locators.
+
+### Queries and the injector tree
+
+TIP: See [Dependency Injection](guide/di) for background on providers and Angular's injection tree.
+
+For more advanced cases, you can use any `ProviderToken` as a locator. This lets you locate elements based on component and directive providers.
+
+```angular-ts
+const SUB_ITEM = new InjectionToken('sub-item');
+
+@Component({
+ /*...*/
+ providers: [{provide: SUB_ITEM, useValue: 'special-item'}],
+})
+export class SpecialItem { }
+
+@Component({/*...*/})
+export class CustomList {
+ subItemType = contentChild(SUB_ITEM);
+}
+```
+
+The above example uses an `InjectionToken` as a locator, but you can use any `ProviderToken` to locate specific elements.
+
+## Query options
+
+All query functions accept an options object as a second parameter. These options control how the query finds its results.
+
+### Reading specific values from an element's injector
+
+By default, the query locator indicates both the element you're searching for and the value retrieved. You can alternatively specify the `read` option to retrieve a different value from the element matched by the locator.
+
+```ts
+
+@Component({/*...*/})
+export class CustomExpando {
+ toggle = contentChild(ExpandoContent, {read: TemplateRef});
+}
+```
+
+The above example, locates an element with the directive `ExpandoContent` and retrieves
+the `TemplateRef` associated with that element.
+
+Developers most commonly use `read` to retrieve `ElementRef` and `TemplateRef`.
+
+### Content descendants
+
+By default, `contentChildren` queries find only _direct_ children of the component and do not traverse into descendants.
+`contentChild` queries do traverse into descendants by default.
+
+```typescript {highlight: [13, 14, 15, 16]}
+@Component({
+ selector: 'custom-expando',
+ /*...*/
+})
+export class CustomExpando {
+ toggle = contentChildren(CustomToggle); // none found
+ // toggle = contentChild(CustomToggle); // found
+}
+
+@Component({
+ selector: 'user-profile',
+ template: `
+
+ Show
+
+
+ `
+})
+export class UserProfile { }
+```
+
+In the example above, `CustomExpando` cannot find `` with `contentChildren` because it is not a direct child of ``. By setting `descendants: true`, you configure the query to traverse all descendants in the same template. Queries, however, _never_ pierce into components to traverse elements in other templates.
+
+View queries do not have this option because they _always_ traverse into descendants.
+
+## Decorator-based queries
+
+TIP: While the Angular team recommends using the signal-based query function for new projects, the
+original decorator-based query APIs remain fully supported.
+
+You can alternatively declare queries by adding the corresponding decorator to a property. Decorator-based queries behave the same way as signal-based queries except as described below.
+
+### View queries
+
+You can query for a single result with the `@ViewChild` decorator.
+
+```typescript {highlight: [14, 16, 17, 18]}
+@Component({
+ selector: 'custom-card-header',
+ /*...*/
+})
+export class CustomCardHeader {
+ text: string;
+}
+
+@Component({
+ selector: 'custom-card',
+ template: 'Visit sunny California!',
+})
+export class CustomCard {
+ @ViewChild(CustomCardHeader) header: CustomCardHeader;
+
+ ngAfterViewInit() {
+ console.log(this.header.text);
+ }
+}
+```
+
+In this example, the `CustomCard` component queries for a child `CustomCardHeader` and accesses the result in `ngAfterViewInit`.
+
+Angular keeps the result of `@ViewChild` up to date as your application state changes.
+
+**View query results become available in the `ngAfterViewInit` lifecycle method**. Before this point, the value is `undefined`. See the [Lifecycle](guide/components/lifecycle) section for details on the component lifecycle.
+
+You can also query for multiple results with the `@ViewChildren` decorator.
+
+```typescript {highlight: [17, 19, 20, 21, 22, 23]}
+@Component({
+ selector: 'custom-card-action',
+ /*...*/
+})
+export class CustomCardAction {
+ text: string;
+}
+
+@Component({
+ selector: 'custom-card',
+ template: `
+ Save
+ Cancel
+ `,
+})
+export class CustomCard {
+ @ViewChildren(CustomCardAction) actions: QueryList;
+
+ ngAfterViewInit() {
+ this.actions.forEach(action => {
+ console.log(action.text);
+ });
+ }
+}
+```
+
+`@ViewChildren` creates a `QueryList` object that contains the query results. You can subscribe to changes to the query results over time via the `changes` property.
+
+### Content queries
+
+You can query for a single result with the `@ContentChild` decorator.
+
+```typescript {highlight: [14, 16, 17, 18, 25]}
+@Component({
+ selector: 'custom-toggle',
+ /*...*/
+})
+export class CustomToggle {
+ text: string;
+}
+
+@Component({
+ selector: 'custom-expando',
+ /*...*/
+})
+
+export class CustomExpando {
+ @ContentChild(CustomToggle) toggle: CustomToggle;
+
+ ngAfterContentInit() {
+ console.log(this.toggle.text);
+ }
+}
+
+@Component({
+ selector: 'user-profile',
+ template: `
+
+ Show
+
+ `
+})
+export class UserProfile { }
+```
+
+In this example, the `CustomExpando` component queries for a child `CustomToggle` and accesses the result in `ngAfterContentInit`.
+
+Angular keeps the result of `@ContentChild` up to date as your application state changes.
+
+**Content query results become available in the `ngAfterContentInit` lifecycle method**. Before this point, the value is `undefined`. See the [Lifecycle](guide/components/lifecycle) section for details on the component lifecycle.
+
+You can also query for multiple results with the `@ContentChildren` decorator.
+
+```typescript {highlight: [15, 17, 18, 19, 20, 21]}
+@Component({
+ selector: 'custom-menu-item',
+ /*...*/
+})
+export class CustomMenuItem {
+ text: string;
+}
+
+@Component({
+ selector: 'custom-menu',
+ /*...*/
+})
+
+export class CustomMenu {
+ @ContentChildren(CustomMenuItem) items: QueryList;
+
+ ngAfterContentInit() {
+ this.items.forEach(item => {
+ console.log(item.text);
+ });
+ }
+}
+
+@Component({
+ selector: 'user-profile',
+ template: `
+
+ Cheese
+ Tomato
+
+ `
+})
+export class UserProfile { }
+```
+
+`@ContentChildren` creates a `QueryList` object that contains the query results. You can subscribe to changes to the query results over time via the `changes` property.
+
+### Decorator-based query options
+
+All query decorators accept an options object as a second parameter. These options work the same way as signal-based queries except where described below.
+
+### Static queries
+
+`@ViewChild` and `@ContentChild` decorators accept the `static` option.
+
+```angular-ts
+@Component({
+ selector: 'custom-card',
+ template: 'Visit sunny California!',
+})
+export class CustomCard {
+ @ViewChild(CustomCardHeader, {static: true}) header: CustomCardHeader;
+
+ ngOnInit() {
+ console.log(this.header.text);
+ }
+}
+```
+
+By setting `static: true`, you guarantee to Angular that the target of this query is _always_ present and is not conditionally rendered. This makes the result available earlier, in the `ngOnInit` lifecycle method.
+
+Static query results do not update after initialization.
+
+The `static` option is not available for `@ViewChildren` and `@ContentChildren` queries.
+
+### Using QueryList
+
+`@ViewChildren` and `@ContentChildren` both provide a `QueryList` object that contains a list of results.
+
+`QueryList` offers a number of convenience APIs for working with results in an array-like manner, such as `map`, `reduce`, and `forEach`. You can get an array of the current results by calling `toArray`.
+
+You can subscribe to the `changes` property to do something any time the results change.
+
+## Common query pitfalls
+
+When using queries, common pitfalls can make your code harder to understand and maintain.
+
+Always maintain a single source of truth for state shared between multiple components. This avoids scenarios where repeated state in different components becomes out of sync.
+
+Avoid directly writing state to child components. This pattern can lead to brittle code that is hard to understand and is prone to [ExpressionChangedAfterItHasBeenChecked](errors/NG0100) errors.
+
+Never directly write state to parent or ancestor components. This pattern can lead to brittle code that is hard to understand and is prone to [ExpressionChangedAfterItHasBeenChecked](errors/NG0100) errors.
diff --git a/adev-es/src/content/guide/components/queries.md b/adev-es/src/content/guide/components/queries.md
index 075d2c7..8e8578a 100644
--- a/adev-es/src/content/guide/components/queries.md
+++ b/adev-es/src/content/guide/components/queries.md
@@ -1,19 +1,19 @@
-# Referencing component children with queries
+# Referenciando hijos de componentes con consultas
-TIP: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular.
+CONSEJO: Esta guía asume que ya has leído la [Guía de Esenciales](essentials). Lee eso primero si eres nuevo en Angular.
-A component can define **queries** that find child elements and read values from their injectors.
+Un componente puede definir **consultas** que encuentran elementos hijos y leen valores de sus inyectores.
-Developers most commonly use queries to retrieve references to child components, directives, DOM elements, and more.
+Los desarrolladores más comúnmente usan consultas para recuperar referencias a componentes hijos, directivas, elementos DOM, y más.
-All query functions return signals that reflect the most up-to-date results. You can read the
-result by calling the signal function, including in reactive contexts like `computed` and `effect`.
+Todas las funciones de consulta devuelven signals que reflejan los resultados más actualizados. Puedes leer el
+resultado llamando a la función signal, incluyendo en contextos reactivos como `computed` y `effect`.
-There are two categories of query: **view queries** and **content queries.**
+Hay dos categorías de consulta: **consultas de vista** y **consultas de contenido.**
-## View queries
+## Consultas de vista
-View queries retrieve results from the elements in the component's _view_ — the elements defined in the component's own template. You can query for a single result with the `viewChild` function.
+Las consultas de vista recuperan resultados de los elementos en la _vista_ del componente — los elementos definidos en la propia plantilla del componente. Puedes consultar por un solo resultado con la función `viewChild`.
```typescript {highlight: [14, 15]}
@Component({
@@ -34,11 +34,11 @@ export class CustomCard {
}
```
-In this example, the `CustomCard` component queries for a child `CustomCardHeader` and uses the result in a `computed`.
+En este ejemplo, el componente `CustomCard` consulta por un hijo `CustomCardHeader` y usa el resultado en un `computed`.
-If the query does not find a result, its value is `undefined`. This may occur if the target element is hidden by `@if`. Angular keeps the result of `viewChild` up to date as your application state changes.
+Si la consulta no encuentra un resultado, su valor es `undefined`. Esto puede ocurrir si el elemento objetivo está oculto por `@if`. Angular mantiene el resultado de `viewChild` actualizado a medida que el estado de tu aplicación cambia.
-You can also query for multiple results with the `viewChildren` function.
+También puedes consultar por múltiples resultados con la función `viewChildren`.
```typescript {highlight: [17]}
@Component({
@@ -61,13 +61,13 @@ export class CustomCard {
}
```
-`viewChildren` creates a signal with an `Array` of the query results.
+`viewChildren` crea un signal con un `Array` de los resultados de la consulta.
-**Queries never pierce through component boundaries.** View queries can only retrieve results from the component's template.
+**Las consultas nunca atraviesan los límites de los componentes.** Las consultas de vista solo pueden recuperar resultados de la plantilla del componente.
-## Content queries
+## Consultas de contenido
-Content queries retrieve results from the elements in the component's _content_— the elements nested inside the component in the template where it's used. You can query for a single result with the `contentChild` function.
+Las consultas de contenido recuperan resultados de los elementos en el _contenido_ del componente — los elementos anidados dentro del componente en la plantilla donde se usa. Puedes consultar por un solo resultado con la función `contentChild`.
```typescript {highlight: [14, 15]}
@Component({
@@ -89,7 +89,7 @@ export class CustomExpando {
@Component({
/* ... */
-// CustomToggle is used inside CustomExpando as content.
+// CustomToggle se usa dentro de CustomExpando como contenido.
template: `
Show
@@ -100,11 +100,11 @@ template: `
export class UserProfile { }
```
-If the query does not find a result, its value is `undefined`. This may occur if the target element is absent or hidden by `@if`. Angular keeps the result of `contentChild` up to date as your application state changes.
+Si la consulta no encuentra un resultado, su valor es `undefined`. Esto puede ocurrir si el elemento objetivo está ausente u oculto por `@if`. Angular mantiene el resultado de `contentChild` actualizado a medida que el estado de tu aplicación cambia.
-By default, content queries find only _direct_ children of the component and do not traverse into descendants.
+Por defecto, las consultas de contenido encuentran solo hijos _directos_ del componente y no atraviesan hacia los descendientes.
-You can also query for multiple results with the `contentChildren` function.
+También puedes consultar por múltiples resultados con la función `contentChildren`.
```typescript {highlight: [14, 16, 17, 18, 19, 20]}
@Component({
@@ -137,15 +137,15 @@ export class CustomMenu {
export class UserProfile { }
```
-`contentChildren` creates a signal with an `Array` of the query results.
+`contentChildren` crea un signal con un `Array` de los resultados de la consulta.
-**Queries never pierce through component boundaries.** Content queries can only retrieve results from the same template as the component itself.
+**Las consultas nunca atraviesan los límites de los componentes.** Las consultas de contenido solo pueden recuperar resultados de la misma plantilla que el componente mismo.
-## Required queries
+## Consultas requeridas
-If a child query (`viewChild` or `contentChild`) does not find a result, its value is `undefined`. This may occur if the target element is hidden by a control flow statement like `@if` or `@for`. Because of this, the child queries return a signal that include `undefined` in their value type.
+Si una consulta de hijo (`viewChild` o `contentChild`) no encuentra un resultado, su valor es `undefined`. Esto puede ocurrir si el elemento objetivo está oculto por una declaración de flujo de control como `@if` o `@for`. Debido a esto, las consultas de hijo devuelven un signal que incluye `undefined` en su tipo de valor.
-In some cases, especially with `viewChild`, you know with certainty that a specific child is always available. In other cases, you may want to strictly enforce that a specific child is present. For these cases, you can use a _required query_.
+En algunos casos, especialmente con `viewChild`, sabes con certeza que un hijo específico siempre está disponible. En otros casos, puedes querer exigir estrictamente que un hijo específico esté presente. Para estos casos, puedes usar una _consulta requerida_.
```angular-ts
@Component({/* ... */})
@@ -155,16 +155,16 @@ export class CustomCard {
}
```
-If a required query does not find a matching result, Angular reports an error. Because this guarantees that a result is available, required queries do not automatically include `undefined` in the signal's value type.
+Si una consulta requerida no encuentra un resultado coincidente, Angular reporta un error. Debido a que esto garantiza que un resultado está disponible, las consultas requeridas no incluyen automáticamente `undefined` en el tipo de valor del signal.
-## Query locators
+## Localizadores de consulta
-This first parameter for each query decorator is its **locator**.
+El primer parámetro para cada decorador de consulta es su **localizador**.
-Most of the time, you want to use a component or directive as your locator.
+La mayoría de las veces, quieres usar un componente o directiva como tu localizador.
-You can alternatively specify a string locator corresponding to
-a [template reference variable](guide/templates/variables#template-reference-variables).
+Alternativamente puedes especificar un localizador de cadena correspondiente a
+una [variable de referencia de plantilla](guide/templates/variables#template-reference-variables).
```angular-ts
@Component({
@@ -179,15 +179,15 @@ export class ActionBar {
}
```
-If more than one element defines the same template reference variable, the query retrieves the first matching element.
+Si más de un elemento define la misma variable de referencia de plantilla, la consulta recupera el primer elemento coincidente.
-Angular does not support CSS selectors as query locators.
+Angular no soporta selectores CSS como localizadores de consulta.
-### Queries and the injector tree
+### Consultas y el árbol de inyectores
-TIP: See [Dependency Injection](guide/di) for background on providers and Angular's injection tree.
+CONSEJO: Ve [Inyección de Dependencias](guide/di) para información de fondo sobre providers y el árbol de inyección de Angular.
-For more advanced cases, you can use any `ProviderToken` as a locator. This lets you locate elements based on component and directive providers.
+Para casos más avanzados, puedes usar cualquier `ProviderToken` como localizador. Esto te permite localizar elementos basados en providers de componentes y directivas.
```angular-ts
const SUB_ITEM = new InjectionToken('sub-item');
@@ -204,15 +204,15 @@ export class CustomList {
}
```
-The above example uses an `InjectionToken` as a locator, but you can use any `ProviderToken` to locate specific elements.
+El ejemplo anterior usa un `InjectionToken` como localizador, pero puedes usar cualquier `ProviderToken` para localizar elementos específicos.
-## Query options
+## Opciones de consulta
-All query functions accept an options object as a second parameter. These options control how the query finds its results.
+Todas las funciones de consulta aceptan un objeto de opciones como segundo parámetro. Estas opciones controlan cómo la consulta encuentra sus resultados.
-### Reading specific values from an element's injector
+### Leyendo valores específicos del inyector de un elemento
-By default, the query locator indicates both the element you're searching for and the value retrieved. You can alternatively specify the `read` option to retrieve a different value from the element matched by the locator.
+Por defecto, el localizador de consulta indica tanto el elemento que estás buscando como el valor recuperado. Alternativamente puedes especificar la opción `read` para recuperar un valor diferente del elemento coincidente con el localizador.
```ts
@@ -222,15 +222,15 @@ export class CustomExpando {
}
```
-The above example, locates an element with the directive `ExpandoContent` and retrieves
-the `TemplateRef` associated with that element.
+El ejemplo anterior localiza un elemento con la directiva `ExpandoContent` y recupera
+el `TemplateRef` asociado con ese elemento.
-Developers most commonly use `read` to retrieve `ElementRef` and `TemplateRef`.
+Los desarrolladores más comúnmente usan `read` para recuperar `ElementRef` y `TemplateRef`.
-### Content descendants
+### Descendientes de contenido
-By default, `contentChildren` queries find only _direct_ children of the component and do not traverse into descendants.
-`contentChild` queries do traverse into descendants by default.
+Por defecto, las consultas de `contentChildren` encuentran solo hijos _directos_ del componente y no atraviesan hacia los descendientes.
+Las consultas de `contentChild` sí atraviesan hacia los descendientes por defecto.
```typescript {highlight: [13, 14, 15, 16]}
@Component({
@@ -238,8 +238,8 @@ By default, `contentChildren` queries find only _direct_ children of the compone
/*...*/
})
export class CustomExpando {
- toggle = contentChildren(CustomToggle); // none found
- // toggle = contentChild(CustomToggle); // found
+ toggle = contentChildren(CustomToggle); // ninguno encontrado
+ // toggle = contentChild(CustomToggle); // encontrado
}
@Component({
@@ -254,20 +254,20 @@ export class CustomExpando {
export class UserProfile { }
```
-In the example above, `CustomExpando` cannot find `` with `contentChildren` because it is not a direct child of ``. By setting `descendants: true`, you configure the query to traverse all descendants in the same template. Queries, however, _never_ pierce into components to traverse elements in other templates.
+En el ejemplo anterior, `CustomExpando` no puede encontrar `` con `contentChildren` porque no es un hijo directo de ``. Estableciendo `descendants: true`, configuras la consulta para atravesar todos los descendientes en la misma plantilla. Las consultas, sin embargo, _nunca_ atraviesan hacia dentro de componentes para recorrer elementos en otras plantillas.
-View queries do not have this option because they _always_ traverse into descendants.
+Las consultas de vista no tienen esta opción porque _siempre_ atraviesan hacia los descendientes.
-## Decorator-based queries
+## Consultas basadas en decoradores
-TIP: While the Angular team recommends using the signal-based query function for new projects, the
-original decorator-based query APIs remain fully supported.
+CONSEJO: Aunque el equipo de Angular recomienda usar la función de consulta basada en signals para proyectos nuevos, las
+APIs de consulta basadas en decoradores originales permanecen completamente soportadas.
-You can alternatively declare queries by adding the corresponding decorator to a property. Decorator-based queries behave the same way as signal-based queries except as described below.
+Alternativamente puedes declarar consultas añadiendo el decorador correspondiente a una propiedad. Las consultas basadas en decoradores se comportan de la misma manera que las consultas basadas en signals excepto como se describe a continuación.
-### View queries
+### Consultas de vista
-You can query for a single result with the `@ViewChild` decorator.
+Puedes consultar por un solo resultado con el decorador `@ViewChild`.
```typescript {highlight: [14, 16, 17, 18]}
@Component({
@@ -291,13 +291,13 @@ export class CustomCard {
}
```
-In this example, the `CustomCard` component queries for a child `CustomCardHeader` and accesses the result in `ngAfterViewInit`.
+En este ejemplo, el componente `CustomCard` consulta por un hijo `CustomCardHeader` y accede al resultado en `ngAfterViewInit`.
-Angular keeps the result of `@ViewChild` up to date as your application state changes.
+Angular mantiene el resultado de `@ViewChild` actualizado a medida que el estado de tu aplicación cambia.
-**View query results become available in the `ngAfterViewInit` lifecycle method**. Before this point, the value is `undefined`. See the [Lifecycle](guide/components/lifecycle) section for details on the component lifecycle.
+**Los resultados de consulta de vista están disponibles en el método de ciclo de vida `ngAfterViewInit`**. Antes de este punto, el valor es `undefined`. Ve la sección [Ciclo de vida](guide/components/lifecycle) para detalles sobre el ciclo de vida del componente.
-You can also query for multiple results with the `@ViewChildren` decorator.
+También puedes consultar por múltiples resultados con el decorador `@ViewChildren`.
```typescript {highlight: [17, 19, 20, 21, 22, 23]}
@Component({
@@ -326,11 +326,11 @@ export class CustomCard {
}
```
-`@ViewChildren` creates a `QueryList` object that contains the query results. You can subscribe to changes to the query results over time via the `changes` property.
+`@ViewChildren` crea un objeto `QueryList` que contiene los resultados de la consulta. Puedes suscribirte a cambios en los resultados de la consulta a lo largo del tiempo a través de la propiedad `changes`.
-### Content queries
+### Consultas de contenido
-You can query for a single result with the `@ContentChild` decorator.
+Puedes consultar por un solo resultado con el decorador `@ContentChild`.
```typescript {highlight: [14, 16, 17, 18, 25]}
@Component({
@@ -365,13 +365,13 @@ export class CustomExpando {
export class UserProfile { }
```
-In this example, the `CustomExpando` component queries for a child `CustomToggle` and accesses the result in `ngAfterContentInit`.
+En este ejemplo, el componente `CustomExpando` consulta por un hijo `CustomToggle` y accede al resultado en `ngAfterContentInit`.
-Angular keeps the result of `@ContentChild` up to date as your application state changes.
+Angular mantiene el resultado de `@ContentChild` actualizado a medida que el estado de tu aplicación cambia.
-**Content query results become available in the `ngAfterContentInit` lifecycle method**. Before this point, the value is `undefined`. See the [Lifecycle](guide/components/lifecycle) section for details on the component lifecycle.
+**Los resultados de consulta de contenido están disponibles en el método de ciclo de vida `ngAfterContentInit`**. Antes de este punto, el valor es `undefined`. Ve la sección [Ciclo de vida](guide/components/lifecycle) para detalles sobre el ciclo de vida del componente.
-You can also query for multiple results with the `@ContentChildren` decorator.
+También puedes consultar por múltiples resultados con el decorador `@ContentChildren`.
```typescript {highlight: [15, 17, 18, 19, 20, 21]}
@Component({
@@ -409,15 +409,15 @@ export class CustomMenu {
export class UserProfile { }
```
-`@ContentChildren` creates a `QueryList` object that contains the query results. You can subscribe to changes to the query results over time via the `changes` property.
+`@ContentChildren` crea un objeto `QueryList` que contiene los resultados de la consulta. Puedes suscribirte a cambios en los resultados de la consulta a lo largo del tiempo a través de la propiedad `changes`.
-### Decorator-based query options
+### Opciones de consulta basadas en decoradores
-All query decorators accept an options object as a second parameter. These options work the same way as signal-based queries except where described below.
+Todos los decoradores de consulta aceptan un objeto de opciones como segundo parámetro. Estas opciones funcionan de la misma manera que las consultas basadas en signals excepto donde se describe a continuación.
-### Static queries
+### Consultas estáticas
-`@ViewChild` and `@ContentChild` decorators accept the `static` option.
+Los decoradores `@ViewChild` y `@ContentChild` aceptan la opción `static`.
```angular-ts
@Component({
@@ -433,26 +433,26 @@ export class CustomCard {
}
```
-By setting `static: true`, you guarantee to Angular that the target of this query is _always_ present and is not conditionally rendered. This makes the result available earlier, in the `ngOnInit` lifecycle method.
+Estableciendo `static: true`, garantizas a Angular que el objetivo de esta consulta está _siempre_ presente y no se renderiza condicionalmente. Esto hace que el resultado esté disponible antes, en el método de ciclo de vida `ngOnInit`.
-Static query results do not update after initialization.
+Los resultados de consultas estáticas no se actualizan después de la inicialización.
-The `static` option is not available for `@ViewChildren` and `@ContentChildren` queries.
+La opción `static` no está disponible para las consultas `@ViewChildren` y `@ContentChildren`.
-### Using QueryList
+### Usando QueryList
-`@ViewChildren` and `@ContentChildren` both provide a `QueryList` object that contains a list of results.
+`@ViewChildren` y `@ContentChildren` ambos proporcionan un objeto `QueryList` que contiene una lista de resultados.
-`QueryList` offers a number of convenience APIs for working with results in an array-like manner, such as `map`, `reduce`, and `forEach`. You can get an array of the current results by calling `toArray`.
+`QueryList` ofrece varias APIs de conveniencia para trabajar con resultados de manera similar a un array, como `map`, `reduce` y `forEach`. Puedes obtener un array de los resultados actuales llamando a `toArray`.
-You can subscribe to the `changes` property to do something any time the results change.
+Puedes suscribirte a la propiedad `changes` para hacer algo cada vez que los resultados cambien.
-## Common query pitfalls
+## Errores comunes con consultas
-When using queries, common pitfalls can make your code harder to understand and maintain.
+Al usar consultas, errores comunes pueden hacer que tu código sea más difícil de entender y mantener.
-Always maintain a single source of truth for state shared between multiple components. This avoids scenarios where repeated state in different components becomes out of sync.
+Siempre mantén una única fuente de verdad para el estado compartido entre múltiples componentes. Esto evita escenarios donde el estado repetido en diferentes componentes se desincroniza.
-Avoid directly writing state to child components. This pattern can lead to brittle code that is hard to understand and is prone to [ExpressionChangedAfterItHasBeenChecked](errors/NG0100) errors.
+Evita escribir estado directamente a componentes hijos. Este patrón puede llevar a código frágil que es difícil de entender y es propenso a errores de [ExpressionChangedAfterItHasBeenChecked](errors/NG0100).
-Never directly write state to parent or ancestor components. This pattern can lead to brittle code that is hard to understand and is prone to [ExpressionChangedAfterItHasBeenChecked](errors/NG0100) errors.
+Nunca escribas estado directamente a componentes padre o ancestros. Este patrón puede llevar a código frágil que es difícil de entender y es propenso a errores de [ExpressionChangedAfterItHasBeenChecked](errors/NG0100).
diff --git a/adev-es/src/content/guide/components/styling.md b/adev-es/src/content/guide/components/styling.md
index c09cdf3..75154e3 100644
--- a/adev-es/src/content/guide/components/styling.md
+++ b/adev-es/src/content/guide/components/styling.md
@@ -59,10 +59,10 @@ los estilos globales definidos fuera de un componente aún puede afectar element
con encapsulación emulada.
En modo emulado, Angular admite
-la pseudo-clase [`:host`](https://developer.mozilla.org/docs/Web/CSS/:host).
+la pseudo-clase [`:host`](https://developer.mozilla.org/es/docs/Web/CSS/Reference/Selectors/:host).
Aunque la pseudo-clase [`:host-context()`](https://developer.mozilla.org/docs/Web/CSS/:host-context) está
deprecada en navegadores modernos, el compilador de Angular proporciona soporte completo para ella. Ambas pseudo-clases
-pueden usarse sin depender de [Shadow DOM](https://developer.mozilla.org/docs/Web/Web_Components/Using_shadow_DOM) nativo.
+pueden usarse sin depender de [Shadow DOM](https://developer.mozilla.org/es/docs/Web/API/Web_components/Using_shadow_DOM) nativo.
Durante la compilación, el framework transforma estas pseudo-clases en atributos para que no
cumpla con las reglas de estas pseudo-clases nativas en tiempo de ejecución
(ej. compatibilidad del navegador, especificidad). El modo de encapsulación emulada de Angular no admite ninguna otra pseudo-clase relacionada con Shadow DOM,
@@ -86,7 +86,7 @@ Los estilos dentro del árbol de sombra no pueden afectar a elementos fuera de e
Habilitar la encapsulación `ShadowDom`, sin embargo, impacta más que el alcance de estilos. Renderizar el
componente en un árbol de sombra afecta la propagación de eventos, la interacción
-con [la API ``](https://developer.mozilla.org/docs/Web/Web_Components/Using_templates_and_slots),
+con [la API ``](https://developer.mozilla.org/es/docs/Web/API/Web_components/Using_templates_and_slots),
y cómo las herramientas de desarrollador del navegador muestran elementos. Siempre entiende las implicaciones completas de usar
Shadow DOM en tu aplicación antes de habilitar esta opción.
@@ -114,7 +114,7 @@ Angular no admite enlaces dentro de elementos de estilo.
## Referenciar archivos de estilo externos
Las plantillas de componentes pueden
-usar [el elemento ``](https://developer.mozilla.org/docs/Web/HTML/Element/link) para
+usar [el elemento ``](https://developer.mozilla.org/es/docs/Web/HTML/Reference/Elements/link) para
referenciar archivos CSS. Además, tu CSS puede
usar [la regla at `@import`](https://developer.mozilla.org/es/docs/Web/CSS/@import) para referenciar
archivos CSS. Angular trata estas referencias como estilos _externos_. Los estilos externos no se ven afectados por
diff --git a/adev-es/src/content/guide/elements.en.md b/adev-es/src/content/guide/elements.en.md
new file mode 100644
index 0000000..421af2c
--- /dev/null
+++ b/adev-es/src/content/guide/elements.en.md
@@ -0,0 +1,175 @@
+# Angular elements overview
+
+_Angular elements_ are Angular components packaged as _custom elements_ \(also called Web Components\), a web standard for defining new HTML elements in a framework-agnostic way.
+
+[Custom elements](https://developer.mozilla.org/docs/Web/Web_Components/Using_custom_elements) are a Web Platform feature available on all browsers supported by Angular.
+A custom element extends HTML by allowing you to define a tag whose content is created and controlled by JavaScript code.
+The browser maintains a `CustomElementRegistry` of defined custom elements, which maps an instantiable JavaScript class to an HTML tag.
+
+The `@angular/elements` package exports a `createCustomElement()` API that provides a bridge from Angular's component interface and change detection functionality to the built-in DOM API.
+
+Transforming a component to a custom element makes all the required Angular infrastructure available to the browser.
+Creating a custom element is simple and straightforward, and automatically connects your component-defined view with change detection and data binding, mapping Angular functionality to the corresponding built-in HTML equivalents.
+
+## Using custom elements
+
+Custom elements bootstrap themselves - they start when they are added to the DOM, and are destroyed when removed from the DOM.
+Once a custom element is added to the DOM for any page, it looks and behaves like any other HTML element, and does not require any special knowledge of Angular terms or usage conventions.
+
+To add the `@angular/elements` package to your workspace, run the following command:
+
+
+
+ npm install @angular/elements
+
+
+ yarn add @angular/elements
+
+
+ pnpm add @angular/elements
+
+
+ bun add @angular/elements
+
+
+
+### How it works
+
+The `createCustomElement()` function converts a component into a class that can be registered with the browser as a custom element.
+After you register your configured class with the browser's custom-element registry, use the new element just like a built-in HTML element in content that you add directly into the DOM:
+
+```html
+
+
+
+```
+
+When your custom element is placed on a page, the browser creates an instance of the registered class and adds it to the DOM.
+The content is provided by the component's template, which uses Angular template syntax, and is rendered using the component and DOM data.
+Input properties in the component correspond to input attributes for the element.
+
+## Transforming components to custom elements
+
+Angular provides the `createCustomElement()` function for converting an Angular component, together with its dependencies, to a custom element.
+
+The conversion process implements the `NgElementConstructor` interface, and creates a
+constructor class that is configured to produce a self-bootstrapping instance of your component.
+
+Use the browser's native [`customElements.define()`](https://developer.mozilla.org/docs/Web/API/CustomElementRegistry/define) function to register the configured constructor and its associated custom-element tag with the browser's [`CustomElementRegistry`](https://developer.mozilla.org/docs/Web/API/CustomElementRegistry).
+When the browser encounters the tag for the registered element, it uses the constructor to create a custom-element instance.
+
+IMPORTANT: Avoid using the component's selector as the custom element tag name.
+This can lead to unexpected behavior, due to Angular creating two component instances for a single DOM element:
+One regular Angular component and a second one using the custom element.
+
+### Mapping
+
+A custom element _hosts_ an Angular component, providing a bridge between the data and logic defined in the component and standard DOM APIs.
+Component properties and logic maps directly into HTML attributes and the browser's event system.
+
+- The creation API parses the component looking for input properties, and defines corresponding attributes for the custom element.
+ It transforms the property names to make them compatible with custom elements, which do not recognize case distinctions.
+ The resulting attribute names use dash-separated lowercase.
+ For example, for a component with `inputProp = input({alias: 'myInputProp'})`, the corresponding custom element defines an attribute `my-input-prop`.
+
+- Component outputs are dispatched as HTML [Custom Events](https://developer.mozilla.org/docs/Web/API/CustomEvent), with the name of the custom event matching the output name.
+ For example, for a component `with valueChanged = output()`, the corresponding custom element dispatches events with the name "valueChanged", and the emitted data is stored on the event's `detail` property.
+ If you provide an alias, that value is used; for example, `clicks = output({alias: 'myClick'});` results in dispatch events with the name "myClick".
+
+For more information, see Web Component documentation for [Creating custom events](https://developer.mozilla.org/docs/Web/Guide/Events/Creating_and_triggering_events#Creating_custom_events).
+
+## Example: A Popup Service
+
+Previously, when you wanted to add a component to an application at runtime, you had to define a _dynamic component_, and then you would have to load it, attach it to an element in the DOM, and wire up all of the dependencies, change detection, and event handling.
+
+Using an Angular custom element makes the process simpler and more transparent, by providing all the infrastructure and framework automatically —all you have to do is define the kind of event handling you want.
+\(You do still have to exclude the component from compilation, if you are not going to use it in your application.\)
+
+The following Popup Service example application defines a component that you can either load dynamically or convert to a custom element.
+
+| Files | Details |
+| :------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `popup.component.ts` | Defines a simple pop-up element that displays an input message, with some animation and styling. |
+| `popup.service.ts` | Creates an injectable service that provides two different ways to invoke the `PopupComponent`; as a dynamic component, or as a custom element. Notice how much more setup is required for the dynamic-loading method. |
+| `app.component.ts` | Defines the application's root component, which uses the `PopupService` to add the pop-up to the DOM at run time. When the application runs, the root component's constructor converts `PopupComponent` to a custom element. |
+
+For comparison, the demo shows both methods.
+One button adds the popup using the dynamic-loading method, and the other uses the custom element.
+The result is the same, but the preparation is different.
+
+
+
+
+
+
+
+## Typings for custom elements
+
+Generic DOM APIs, such as `document.createElement()` or `document.querySelector()`, return an element type that is appropriate for the specified arguments.
+For example, calling `document.createElement('a')` returns an `HTMLAnchorElement`, which TypeScript knows has an `href` property.
+Similarly, `document.createElement('div')` returns an `HTMLDivElement`, which TypeScript knows has no `href` property.
+
+When called with unknown elements, such as a custom element name \(`popup-element` in our example\), the methods return a generic type, such as `HTMLElement`, because TypeScript can't infer the correct type of the returned element.
+
+Custom elements created with Angular extend `NgElement` \(which in turn extends `HTMLElement`\).
+Additionally, these custom elements will have a property for each input of the corresponding component.
+For example, our `popup-element` has a `message` property of type `string`.
+
+There are a few options if you want to get correct types for your custom elements.
+Assume you create a `my-dialog` custom element based on the following component:
+
+```ts
+
+@Component(…)
+class MyDialog {
+ content = input(string);
+}
+
+```
+
+The most straightforward way to get accurate typings is to cast the return value of the relevant DOM methods to the correct type.
+For that, use the `NgElement` and `WithProperties` types \(both exported from `@angular/elements`\):
+
+```ts
+
+const aDialog = document.createElement('my-dialog') as NgElement & WithProperties<{content: string}>;
+aDialog.content = 'Hello, world!';
+aDialog.content = 123; // <-- ERROR: TypeScript knows this should be a string.
+aDialog.body = 'News'; // <-- ERROR: TypeScript knows there is no `body` property on `aDialog`.
+
+```
+
+This is a good way to quickly get TypeScript features, such as type checking and autocomplete support, for your custom element.
+But it can get cumbersome if you need it in several places, because you have to cast the return type on every occurrence.
+
+An alternative way, that only requires defining each custom element's type once, is augmenting the `HTMLElementTagNameMap`, which TypeScript uses to infer the type of a returned element based on its tag name \(for DOM methods such as `document.createElement()`, `document.querySelector()`, etc.\):
+
+```ts
+
+declare global {
+ interface HTMLElementTagNameMap {
+ 'my-dialog': NgElement & WithProperties<{content: string}>;
+ 'my-other-element': NgElement & WithProperties<{foo: 'bar'}>;
+ …
+ }
+}
+
+```
+
+Now, TypeScript can infer the correct type the same way it does for built-in elements:
+
+```ts
+
+document.createElement('div') //--> HTMLDivElement (built-in element)
+document.querySelector('foo') //--> Element (unknown element)
+document.createElement('my-dialog') //--> NgElement & WithProperties<{content: string}> (custom element)
+document.querySelector('my-other-element') //--> NgElement & WithProperties<{foo: 'bar'}> (custom element)
+
+```
+
+## Limitations
+
+Care should be taken when destroying and then re-attaching custom elements created with `@angular/elements` due to issues with the [disconnect()](https://github.com/angular/angular/issues/38778) callback. Cases where you may run into this issue are:
+
+- Rendering a component in an `ng-if` or `ng-repeat` in `AngularJs`
+- Manually detaching and re-attaching an element to the DOM
diff --git a/adev-es/src/content/guide/elements.md b/adev-es/src/content/guide/elements.md
index 421af2c..3dfa2c9 100644
--- a/adev-es/src/content/guide/elements.md
+++ b/adev-es/src/content/guide/elements.md
@@ -1,22 +1,22 @@
-# Angular elements overview
+# Visión general de Angular elements
-_Angular elements_ are Angular components packaged as _custom elements_ \(also called Web Components\), a web standard for defining new HTML elements in a framework-agnostic way.
+Los _Angular elements_ son componentes de Angular empaquetados como _elementos personalizados_ \(también llamados Web Components\), un estándar web para definir nuevos elementos HTML de manera agnóstica al framework.
-[Custom elements](https://developer.mozilla.org/docs/Web/Web_Components/Using_custom_elements) are a Web Platform feature available on all browsers supported by Angular.
-A custom element extends HTML by allowing you to define a tag whose content is created and controlled by JavaScript code.
-The browser maintains a `CustomElementRegistry` of defined custom elements, which maps an instantiable JavaScript class to an HTML tag.
+Los [elementos personalizados](https://developer.mozilla.org/es/docs/Web/API/Web_components/Using_custom_elements) son una característica de la Plataforma Web disponible en todos los navegadores soportados por Angular.
+Un elemento personalizado extiende HTML al permitirte definir una etiqueta cuyo contenido es creado y controlado por código JavaScript.
+El navegador mantiene un `CustomElementRegistry` de elementos personalizados definidos, que mapea una clase JavaScript instanciable a una etiqueta HTML.
-The `@angular/elements` package exports a `createCustomElement()` API that provides a bridge from Angular's component interface and change detection functionality to the built-in DOM API.
+El paquete `@angular/elements` exporta una API `createCustomElement()` que proporciona un puente desde la interfaz de componentes de Angular y la funcionalidad de detección de cambios hacia la API del DOM incorporada.
-Transforming a component to a custom element makes all the required Angular infrastructure available to the browser.
-Creating a custom element is simple and straightforward, and automatically connects your component-defined view with change detection and data binding, mapping Angular functionality to the corresponding built-in HTML equivalents.
+Transformar un componente a un elemento personalizado hace toda la infraestructura requerida de Angular disponible para el navegador.
+Crear un elemento personalizado es simple y directo, y conecta automáticamente la vista definida por tu componente con la detección de cambios y el enlace de datos, mapeando la funcionalidad de Angular a los equivalentes HTML incorporados correspondientes.
-## Using custom elements
+## Usando elementos personalizados
-Custom elements bootstrap themselves - they start when they are added to the DOM, and are destroyed when removed from the DOM.
-Once a custom element is added to the DOM for any page, it looks and behaves like any other HTML element, and does not require any special knowledge of Angular terms or usage conventions.
+Los elementos personalizados hacen bootstrap de sí mismos - comienzan cuando se agregan al DOM, y se destruyen cuando se eliminan del DOM.
+Una vez que un elemento personalizado se agrega al DOM de cualquier página, se ve y comporta como cualquier otro elemento HTML, y no requiere ningún conocimiento especial de términos o convenciones de uso de Angular.
-To add the `@angular/elements` package to your workspace, run the following command:
+Para agregar el paquete `@angular/elements` a tu espacio de trabajo, ejecuta el siguiente comando:
@@ -33,10 +33,10 @@ To add the `@angular/elements` package to your workspace, run the following comm
-### How it works
+### Cómo funciona
-The `createCustomElement()` function converts a component into a class that can be registered with the browser as a custom element.
-After you register your configured class with the browser's custom-element registry, use the new element just like a built-in HTML element in content that you add directly into the DOM:
+La función `createCustomElement()` convierte un componente en una clase que puede ser registrada con el navegador como un elemento personalizado.
+Después de registrar tu clase configurada con el registro de elementos personalizados del navegador, usa el nuevo elemento igual que un elemento HTML incorporado en el contenido que agregas directamente al DOM:
```html
@@ -44,58 +44,58 @@ After you register your configured class with the browser's custom-element regis
```
-When your custom element is placed on a page, the browser creates an instance of the registered class and adds it to the DOM.
-The content is provided by the component's template, which uses Angular template syntax, and is rendered using the component and DOM data.
-Input properties in the component correspond to input attributes for the element.
+Cuando tu elemento personalizado se coloca en una página, el navegador crea una instancia de la clase registrada y la agrega al DOM.
+El contenido es proporcionado por la plantilla del componente, que usa la sintaxis de plantillas de Angular, y se renderiza usando los datos del componente y del DOM.
+Las propiedades de entrada en el componente corresponden a los atributos de entrada del elemento.
-## Transforming components to custom elements
+## Transformando componentes a elementos personalizados
-Angular provides the `createCustomElement()` function for converting an Angular component, together with its dependencies, to a custom element.
+Angular proporciona la función `createCustomElement()` para convertir un componente de Angular, junto con sus dependencias, a un elemento personalizado.
-The conversion process implements the `NgElementConstructor` interface, and creates a
-constructor class that is configured to produce a self-bootstrapping instance of your component.
+El proceso de conversión implementa la interfaz `NgElementConstructor`, y crea una
+clase constructora que está configurada para producir una instancia self-bootstrapping de tu componente.
-Use the browser's native [`customElements.define()`](https://developer.mozilla.org/docs/Web/API/CustomElementRegistry/define) function to register the configured constructor and its associated custom-element tag with the browser's [`CustomElementRegistry`](https://developer.mozilla.org/docs/Web/API/CustomElementRegistry).
-When the browser encounters the tag for the registered element, it uses the constructor to create a custom-element instance.
+Usa la función nativa del navegador [`customElements.define()`](https://developer.mozilla.org/docs/Web/API/CustomElementRegistry/define) para registrar el constructor configurado y su etiqueta de elemento personalizado asociada con el [`CustomElementRegistry`](https://developer.mozilla.org/docs/Web/API/CustomElementRegistry) del navegador.
+Cuando el navegador encuentra la etiqueta del elemento registrado, usa el constructor para crear una instancia del elemento personalizado.
-IMPORTANT: Avoid using the component's selector as the custom element tag name.
-This can lead to unexpected behavior, due to Angular creating two component instances for a single DOM element:
-One regular Angular component and a second one using the custom element.
+IMPORTANTE: Evita usar el selector del componente como el nombre de etiqueta del elemento personalizado.
+Esto puede llevar a comportamiento inesperado, debido a que Angular crea dos instancias del componente para un solo elemento DOM:
+Un componente de Angular regular y un segundo usando el elemento personalizado.
-### Mapping
+### Mapeo
-A custom element _hosts_ an Angular component, providing a bridge between the data and logic defined in the component and standard DOM APIs.
-Component properties and logic maps directly into HTML attributes and the browser's event system.
+Un elemento personalizado _aloja_ un componente de Angular, proporcionando un puente entre los datos y la lógica definidos en el componente y las APIs estándar del DOM.
+Las propiedades y la lógica del componente se mapean directamente a los atributos HTML y al sistema de eventos del navegador.
-- The creation API parses the component looking for input properties, and defines corresponding attributes for the custom element.
- It transforms the property names to make them compatible with custom elements, which do not recognize case distinctions.
- The resulting attribute names use dash-separated lowercase.
- For example, for a component with `inputProp = input({alias: 'myInputProp'})`, the corresponding custom element defines an attribute `my-input-prop`.
+- La API de creación analiza el componente buscando propiedades de entrada, y define los atributos correspondientes para el elemento personalizado.
+ Transforma los nombres de las propiedades para hacerlos compatibles con los elementos personalizados, que no reconocen distinciones de mayúsculas y minúsculas.
+ Los nombres de atributos resultantes usan minúsculas separadas por guiones.
+ Por ejemplo, para un componente con `inputProp = input({alias: 'myInputProp'})`, el elemento personalizado correspondiente define un atributo `my-input-prop`.
-- Component outputs are dispatched as HTML [Custom Events](https://developer.mozilla.org/docs/Web/API/CustomEvent), with the name of the custom event matching the output name.
- For example, for a component `with valueChanged = output()`, the corresponding custom element dispatches events with the name "valueChanged", and the emitted data is stored on the event's `detail` property.
- If you provide an alias, that value is used; for example, `clicks = output({alias: 'myClick'});` results in dispatch events with the name "myClick".
+- Los outputs del componente se despachan como [Custom Events](https://developer.mozilla.org/docs/Web/API/CustomEvent) HTML, con el nombre del evento personalizado coincidiendo con el nombre del output.
+ Por ejemplo, para un componente con `valueChanged = output()`, el elemento personalizado correspondiente despacha eventos con el nombre "valueChanged", y los datos emitidos se almacenan en la propiedad `detail` del evento.
+ Si proporcionas un alias, ese valor se usa; por ejemplo, `clicks = output({alias: 'myClick'});` resulta en despacho de eventos con el nombre "myClick".
-For more information, see Web Component documentation for [Creating custom events](https://developer.mozilla.org/docs/Web/Guide/Events/Creating_and_triggering_events#Creating_custom_events).
+Para más información, ve la documentación de Web Components para [Creación de eventos personalizados](https://developer.mozilla.org/docs/Web/Guide/Events/Creating_and_triggering_events#Creating_custom_events).
-## Example: A Popup Service
+## Ejemplo: Un Servicio de Popup
-Previously, when you wanted to add a component to an application at runtime, you had to define a _dynamic component_, and then you would have to load it, attach it to an element in the DOM, and wire up all of the dependencies, change detection, and event handling.
+Anteriormente, cuando querías agregar un componente a una aplicación en tiempo de ejecución, tenías que definir un _componente dinámico_, y luego tendrías que cargarlo, adjuntarlo a un elemento en el DOM, y conectar todas las dependencias, detección de cambios, y manejo de eventos.
-Using an Angular custom element makes the process simpler and more transparent, by providing all the infrastructure and framework automatically —all you have to do is define the kind of event handling you want.
-\(You do still have to exclude the component from compilation, if you are not going to use it in your application.\)
+Usar un elemento personalizado de Angular hace el proceso más simple y transparente, al proporcionar toda la infraestructura y el framework automáticamente —todo lo que tienes que hacer es definir el tipo de manejo de eventos que quieres.
+\(Aún tienes que excluir el componente de la compilación, si no vas a usarlo en tu aplicación.\)
-The following Popup Service example application defines a component that you can either load dynamically or convert to a custom element.
+La siguiente aplicación de ejemplo de Servicio de Popup define un componente que puedes cargar dinámicamente o convertir a un elemento personalizado.
-| Files | Details |
-| :------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `popup.component.ts` | Defines a simple pop-up element that displays an input message, with some animation and styling. |
-| `popup.service.ts` | Creates an injectable service that provides two different ways to invoke the `PopupComponent`; as a dynamic component, or as a custom element. Notice how much more setup is required for the dynamic-loading method. |
-| `app.component.ts` | Defines the application's root component, which uses the `PopupService` to add the pop-up to the DOM at run time. When the application runs, the root component's constructor converts `PopupComponent` to a custom element. |
+| Archivos | Detalles |
+| :------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `popup.component.ts` | Define un simple elemento pop-up que muestra un mensaje de entrada, con algo de animación y estilos. |
+| `popup.service.ts` | Crea un servicio inyectable que proporciona dos formas diferentes de invocar el `PopupComponent`; como un componente dinámico, o como un elemento personalizado. Nota cuánta más configuración se requiere para el método de carga dinámica. |
+| `app.component.ts` | Define el componente raíz de la aplicación, que usa el `PopupService` para agregar el pop-up al DOM en tiempo de ejecución. Cuando la aplicación se ejecuta, el constructor del componente raíz convierte `PopupComponent` a un elemento personalizado. |
-For comparison, the demo shows both methods.
-One button adds the popup using the dynamic-loading method, and the other uses the custom element.
-The result is the same, but the preparation is different.
+Para comparación, la demo muestra ambos métodos.
+Un botón agrega el popup usando el método de carga dinámica, y el otro usa el elemento personalizado.
+El resultado es el mismo, pero la preparación es diferente.
@@ -103,20 +103,20 @@ The result is the same, but the preparation is different.
-## Typings for custom elements
+## Tipado para elementos personalizados
-Generic DOM APIs, such as `document.createElement()` or `document.querySelector()`, return an element type that is appropriate for the specified arguments.
-For example, calling `document.createElement('a')` returns an `HTMLAnchorElement`, which TypeScript knows has an `href` property.
-Similarly, `document.createElement('div')` returns an `HTMLDivElement`, which TypeScript knows has no `href` property.
+Las APIs genéricas del DOM, como `document.createElement()` o `document.querySelector()`, devuelven un tipo de elemento que es apropiado para los argumentos especificados.
+Por ejemplo, llamar `document.createElement('a')` devuelve un `HTMLAnchorElement`, que TypeScript sabe que tiene una propiedad `href`.
+De manera similar, `document.createElement('div')` devuelve un `HTMLDivElement`, que TypeScript sabe que no tiene propiedad `href`.
-When called with unknown elements, such as a custom element name \(`popup-element` in our example\), the methods return a generic type, such as `HTMLElement`, because TypeScript can't infer the correct type of the returned element.
+Cuando se llama con elementos desconocidos, como el nombre de un elemento personalizado \(`popup-element` en nuestro ejemplo\), los métodos devuelven un tipo genérico, como `HTMLElement`, porque TypeScript no puede inferir el tipo correcto del elemento devuelto.
-Custom elements created with Angular extend `NgElement` \(which in turn extends `HTMLElement`\).
-Additionally, these custom elements will have a property for each input of the corresponding component.
-For example, our `popup-element` has a `message` property of type `string`.
+Los elementos personalizados creados con Angular extienden `NgElement` \(que a su vez extiende `HTMLElement`\).
+Además, estos elementos personalizados tendrán una propiedad por cada input del componente correspondiente.
+Por ejemplo, nuestro `popup-element` tiene una propiedad `message` de tipo `string`.
-There are a few options if you want to get correct types for your custom elements.
-Assume you create a `my-dialog` custom element based on the following component:
+Hay algunas opciones si quieres obtener tipos correctos para tus elementos personalizados.
+Asume que creas un elemento personalizado `my-dialog` basado en el siguiente componente:
```ts
@@ -127,22 +127,22 @@ class MyDialog {
```
-The most straightforward way to get accurate typings is to cast the return value of the relevant DOM methods to the correct type.
-For that, use the `NgElement` and `WithProperties` types \(both exported from `@angular/elements`\):
+La forma más directa de obtener tipado preciso es hacer cast del valor de retorno de los métodos DOM relevantes al tipo correcto.
+Para eso, usa los tipos `NgElement` y `WithProperties` \(ambos exportados de `@angular/elements`\):
```ts
const aDialog = document.createElement('my-dialog') as NgElement & WithProperties<{content: string}>;
aDialog.content = 'Hello, world!';
-aDialog.content = 123; // <-- ERROR: TypeScript knows this should be a string.
-aDialog.body = 'News'; // <-- ERROR: TypeScript knows there is no `body` property on `aDialog`.
+aDialog.content = 123; // <-- ERROR: TypeScript sabe que esto debería ser un string.
+aDialog.body = 'News'; // <-- ERROR: TypeScript sabe que no hay propiedad `body` en `aDialog`.
```
-This is a good way to quickly get TypeScript features, such as type checking and autocomplete support, for your custom element.
-But it can get cumbersome if you need it in several places, because you have to cast the return type on every occurrence.
+Esta es una buena forma de obtener rápidamente las características de TypeScript, como verificación de tipos y soporte de autocompletado, para tu elemento personalizado.
+Pero puede volverse engorroso si lo necesitas en varios lugares, porque tienes que hacer cast del tipo de retorno en cada ocurrencia.
-An alternative way, that only requires defining each custom element's type once, is augmenting the `HTMLElementTagNameMap`, which TypeScript uses to infer the type of a returned element based on its tag name \(for DOM methods such as `document.createElement()`, `document.querySelector()`, etc.\):
+Una forma alternativa, que solo requiere definir el tipo de cada elemento personalizado una vez, es aumentar el `HTMLElementTagNameMap`, que TypeScript usa para inferir el tipo de un elemento devuelto basado en su nombre de etiqueta \(para métodos DOM como `document.createElement()`, `document.querySelector()`, etc.\):
```ts
@@ -156,20 +156,20 @@ declare global {
```
-Now, TypeScript can infer the correct type the same way it does for built-in elements:
+Ahora, TypeScript puede inferir el tipo correcto de la misma forma que lo hace para los elementos incorporados:
```ts
-document.createElement('div') //--> HTMLDivElement (built-in element)
-document.querySelector('foo') //--> Element (unknown element)
-document.createElement('my-dialog') //--> NgElement & WithProperties<{content: string}> (custom element)
-document.querySelector('my-other-element') //--> NgElement & WithProperties<{foo: 'bar'}> (custom element)
+document.createElement('div') //--> HTMLDivElement (elemento incorporado)
+document.querySelector('foo') //--> Element (elemento desconocido)
+document.createElement('my-dialog') //--> NgElement & WithProperties<{content: string}> (elemento personalizado)
+document.querySelector('my-other-element') //--> NgElement & WithProperties<{foo: 'bar'}> (elemento personalizado)
```
-## Limitations
+## Limitaciones
-Care should be taken when destroying and then re-attaching custom elements created with `@angular/elements` due to issues with the [disconnect()](https://github.com/angular/angular/issues/38778) callback. Cases where you may run into this issue are:
+Se debe tener cuidado al destruir y luego volver a adjuntar elementos personalizados creados con `@angular/elements` debido a problemas con el callback [disconnect()](https://github.com/angular/angular/issues/38778). Los casos donde puedes encontrar este problema son:
-- Rendering a component in an `ng-if` or `ng-repeat` in `AngularJs`
-- Manually detaching and re-attaching an element to the DOM
+- Renderizar un componente en un `ng-if` o `ng-repeat` en AngularJS
+- Desconectar y volver a conectar manualmente un elemento al DOM