diff --git a/adev-es/src/content/reference/errors/NG0100.en.md b/adev-es/src/content/reference/errors/NG0100.en.md new file mode 100644 index 0000000..7ec50c0 --- /dev/null +++ b/adev-es/src/content/reference/errors/NG0100.en.md @@ -0,0 +1,19 @@ +# Expression Changed After Checked + + + +Angular throws an `ExpressionChangedAfterItHasBeenCheckedError` when an expression value has been changed after change detection has completed. Angular only throws this error in development mode. + +In development mode, Angular performs an additional check after each change detection run, to ensure the bindings haven't changed. This catches errors where the view is left in an inconsistent state. This can occur, for example, if a method or getter returns a different value each time it is called, or if a child component changes values on its parent. If either of these occurs, this is a sign that change detection is not stabilized. Angular throws the error to ensure data is always reflected correctly in the view, which prevents erratic UI behavior or a possible infinite loop. + +This error commonly occurs when you've added template expressions or have begun to implement lifecycle hooks like `ngAfterViewInit` or `ngOnChanges`. It is also common when dealing with loading status and asynchronous operations, or when a child component changes its parent bindings. + +## Debugging the error + +The [source maps](https://developer.mozilla.org/docs/Tools/Debugger/How_to/Use_a_source_map) generated by the CLI are very useful when debugging. Navigate up the call stack until you find a template expression where the value displayed in the error has changed. + +Ensure that there are no changes to the bindings in the template after change detection is run. This often means refactoring to use the correct component lifecycle hook for your use case. If the issue exists within `ngAfterViewInit`, the recommended solution is to use a constructor or `ngOnInit` to set initial values, or use `ngAfterContentInit` for other value bindings. + +If you are binding to methods in the view, ensure that the invocation does not update any of the other bindings in the template. + +Read more about which solution is right for you in ['Everything you need to know about the "ExpressionChangedAfterItHasBeenCheckedError" error'](https://angularindepth.com/posts/1001/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error) and why this is useful at ['Angular Debugging "Expression has changed after it was checked": Simple Explanation (and Fix)'](https://blog.angular-university.io/angular-debugging). diff --git a/adev-es/src/content/reference/errors/NG0100.md b/adev-es/src/content/reference/errors/NG0100.md index 7ec50c0..c566901 100644 --- a/adev-es/src/content/reference/errors/NG0100.md +++ b/adev-es/src/content/reference/errors/NG0100.md @@ -2,18 +2,18 @@ -Angular throws an `ExpressionChangedAfterItHasBeenCheckedError` when an expression value has been changed after change detection has completed. Angular only throws this error in development mode. +Angular lanza un `ExpressionChangedAfterItHasBeenCheckedError` cuando el valor de una expresión ha cambiado después de que la detección de cambios ha completado. Angular solo lanza este error en modo de desarrollo. -In development mode, Angular performs an additional check after each change detection run, to ensure the bindings haven't changed. This catches errors where the view is left in an inconsistent state. This can occur, for example, if a method or getter returns a different value each time it is called, or if a child component changes values on its parent. If either of these occurs, this is a sign that change detection is not stabilized. Angular throws the error to ensure data is always reflected correctly in the view, which prevents erratic UI behavior or a possible infinite loop. +En modo de desarrollo, Angular realiza una verificación adicional después de cada ejecución de detección de cambios para asegurarse de que los enlaces no hayan cambiado. Esto detecta errores donde la vista queda en un estado inconsistente. Esto puede ocurrir, por ejemplo, si un método o getter devuelve un valor diferente cada vez que se llama, o si un componente hijo cambia valores en su componente padre. Si cualquiera de estos casos ocurre, es una señal de que la detección de cambios no se ha estabilizado. Angular lanza el error para garantizar que los datos siempre se reflejen correctamente en la vista, lo que previene un comportamiento errático de la UI o un posible bucle infinito. -This error commonly occurs when you've added template expressions or have begun to implement lifecycle hooks like `ngAfterViewInit` or `ngOnChanges`. It is also common when dealing with loading status and asynchronous operations, or when a child component changes its parent bindings. +Este error ocurre comúnmente cuando has agregado expresiones de plantilla o has comenzado a implementar hooks de ciclo de vida como `ngAfterViewInit` o `ngOnChanges`. También es común cuando se trabaja con estados de carga y operaciones asíncronas, o cuando un componente hijo cambia los enlaces de su componente padre. -## Debugging the error +## Depurando el error -The [source maps](https://developer.mozilla.org/docs/Tools/Debugger/How_to/Use_a_source_map) generated by the CLI are very useful when debugging. Navigate up the call stack until you find a template expression where the value displayed in the error has changed. +Los [source maps](https://developer.mozilla.org/docs/Tools/Debugger/How_to/Use_a_source_map) generados por el CLI son muy útiles para depurar. Navega hacia arriba en la pila de llamadas hasta encontrar una expresión de plantilla donde el valor mostrado en el error haya cambiado. -Ensure that there are no changes to the bindings in the template after change detection is run. This often means refactoring to use the correct component lifecycle hook for your use case. If the issue exists within `ngAfterViewInit`, the recommended solution is to use a constructor or `ngOnInit` to set initial values, or use `ngAfterContentInit` for other value bindings. +Asegúrate de que no haya cambios en los enlaces de la plantilla después de que se ejecute la detección de cambios. Esto generalmente implica refactorizar para usar el hook de ciclo de vida correcto para tu caso de uso. Si el problema existe dentro de `ngAfterViewInit`, la solución recomendada es usar un constructor o `ngOnInit` para establecer valores iniciales, o usar `ngAfterContentInit` para otros enlaces de valores. -If you are binding to methods in the view, ensure that the invocation does not update any of the other bindings in the template. +Si estás enlazando a métodos en la vista, asegúrate de que la invocación no actualice ninguno de los otros enlaces en la plantilla. -Read more about which solution is right for you in ['Everything you need to know about the "ExpressionChangedAfterItHasBeenCheckedError" error'](https://angularindepth.com/posts/1001/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error) and why this is useful at ['Angular Debugging "Expression has changed after it was checked": Simple Explanation (and Fix)'](https://blog.angular-university.io/angular-debugging). +Lee más sobre qué solución es la correcta para ti en ['Everything you need to know about the "ExpressionChangedAfterItHasBeenCheckedError" error'](https://angularindepth.com/posts/1001/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error) y por qué esto es útil en ['Angular Debugging "Expression has changed after it was checked": Simple Explanation (and Fix)'](https://blog.angular-university.io/angular-debugging). diff --git a/adev-es/src/content/reference/errors/NG01101.en.md b/adev-es/src/content/reference/errors/NG01101.en.md new file mode 100644 index 0000000..dcb6911 --- /dev/null +++ b/adev-es/src/content/reference/errors/NG01101.en.md @@ -0,0 +1,20 @@ +# Wrong Async Validator Return Type + +Async validators must return a promise or an observable, and emit/resolve them whether the validation fails or succeeds. In particular, they must implement the [AsyncValidatorFn API](api/forms/AsyncValidator) + +```typescript +export function isTenAsync(control: AbstractControl): + Observable { + const v: number = control.value; + if (v !== 10) { + // Emit an object with a validation error. + return of({ 'notTen': true, 'requiredValue': 10 }); + } + // Emit null, to indicate no error occurred. + return of(null); + } +``` + +## Debugging the error + +Did you mistakenly use a synchronous validator instead of an async validator? diff --git a/adev-es/src/content/reference/errors/NG01101.md b/adev-es/src/content/reference/errors/NG01101.md index dcb6911..97e47bf 100644 --- a/adev-es/src/content/reference/errors/NG01101.md +++ b/adev-es/src/content/reference/errors/NG01101.md @@ -1,20 +1,20 @@ # Wrong Async Validator Return Type -Async validators must return a promise or an observable, and emit/resolve them whether the validation fails or succeeds. In particular, they must implement the [AsyncValidatorFn API](api/forms/AsyncValidator) +Los validadores asíncronos deben retornar una promesa o un observable, y emitirlos/resolverlos tanto si la validación falla como si tiene éxito. En particular, deben implementar la [API AsyncValidatorFn](api/forms/AsyncValidator) ```typescript export function isTenAsync(control: AbstractControl): Observable { const v: number = control.value; if (v !== 10) { - // Emit an object with a validation error. + // Emite un objeto con un error de validación. return of({ 'notTen': true, 'requiredValue': 10 }); } - // Emit null, to indicate no error occurred. + // Emite null, para indicar que no ocurrió ningún error. return of(null); } ``` -## Debugging the error +## Depurando el error -Did you mistakenly use a synchronous validator instead of an async validator? +¿Usaste por error un validador síncrono en lugar de un validador asíncrono? diff --git a/adev-es/src/content/reference/errors/NG01203.en.md b/adev-es/src/content/reference/errors/NG01203.en.md new file mode 100644 index 0000000..7aa92fe --- /dev/null +++ b/adev-es/src/content/reference/errors/NG01203.en.md @@ -0,0 +1,26 @@ +# Missing value accessor + +For all custom form controls, you must register a value accessor. + +Here's an example of how to provide one: + +```typescript +providers: [ + { + provide: NG_VALUE_ACCESSOR, + useExisting: forwardRef(() => MyInputField), + multi: true, + } +] +``` + +## Debugging the error + +As described above, your control was expected to have a value accessor, but was missing one. However, there are many different reasons this can happen in practice. Here's a listing of some known problems leading to this error. + +1. If you **defined** a custom form control, did you remember to provide a value accessor? +1. Did you put `ngModel` on an element with no value, or an **invalid element** (e.g. `
`)? +1. Are you using a custom form control declared inside an `NgModule`? if so, make sure you are **importing** the `NgModule`. +1. Are you using `ngModel` with a third-party custom form control? Check whether that control provides a value accessor. If not, use **`ngDefaultControl`** on the control's element. +1. Are you **testing** a custom form control? Be sure to configure your testbed to know about the control. You can do so with `Testbed.configureTestingModule`. +1. Are you using **Nx and Module Federation** with webpack? Your `webpack.config.js` may require [extra configuration](https://github.com/angular/angular/issues/43821#issuecomment-1054845431) to ensure the forms package is shared. diff --git a/adev-es/src/content/reference/errors/NG01203.md b/adev-es/src/content/reference/errors/NG01203.md index 7aa92fe..39f7abf 100644 --- a/adev-es/src/content/reference/errors/NG01203.md +++ b/adev-es/src/content/reference/errors/NG01203.md @@ -1,8 +1,8 @@ # Missing value accessor -For all custom form controls, you must register a value accessor. +Para todos los controles de formulario personalizados, debes registrar un accessor de valor. -Here's an example of how to provide one: +Aquí hay un ejemplo de cómo proporcionar uno: ```typescript providers: [ @@ -14,13 +14,13 @@ providers: [ ] ``` -## Debugging the error +## Depurando el error -As described above, your control was expected to have a value accessor, but was missing one. However, there are many different reasons this can happen in practice. Here's a listing of some known problems leading to this error. +Como se describió anteriormente, se esperaba que tu control tuviera un accessor de valor, pero le faltaba uno. Sin embargo, hay muchas razones diferentes por las que esto puede suceder en la práctica. Aquí hay una lista de algunos problemas conocidos que llevan a este error. -1. If you **defined** a custom form control, did you remember to provide a value accessor? -1. Did you put `ngModel` on an element with no value, or an **invalid element** (e.g. `
`)? -1. Are you using a custom form control declared inside an `NgModule`? if so, make sure you are **importing** the `NgModule`. -1. Are you using `ngModel` with a third-party custom form control? Check whether that control provides a value accessor. If not, use **`ngDefaultControl`** on the control's element. -1. Are you **testing** a custom form control? Be sure to configure your testbed to know about the control. You can do so with `Testbed.configureTestingModule`. -1. Are you using **Nx and Module Federation** with webpack? Your `webpack.config.js` may require [extra configuration](https://github.com/angular/angular/issues/43821#issuecomment-1054845431) to ensure the forms package is shared. +1. Si **definiste** un control de formulario personalizado, ¿recuerdas proporcionar un accessor de valor? +1. ¿Pusiste `ngModel` en un elemento sin valor, o en un **elemento inválido** (por ejemplo, `
`)? +1. ¿Estás usando un control de formulario personalizado declarado dentro de un `NgModule`? Si es así, asegúrate de estar **importando** el `NgModule`. +1. ¿Estás usando `ngModel` con un control de formulario personalizado de terceros? Verifica si ese control proporciona un accessor de valor. Si no lo hace, usa **`ngDefaultControl`** en el elemento del control. +1. ¿Estás **probando** un control de formulario personalizado? Asegúrate de configurar tu testbed para que conozca el control. Puedes hacerlo con `Testbed.configureTestingModule`. +1. ¿Estás usando **Nx y Module Federation** con webpack? Tu `webpack.config.js` puede requerir [configuración adicional](https://github.com/angular/angular/issues/43821#issuecomment-1054845431) para asegurarte de que el paquete de formularios sea compartido. diff --git a/adev-es/src/content/reference/errors/NG0200.en.md b/adev-es/src/content/reference/errors/NG0200.en.md new file mode 100644 index 0000000..0b5f0c4 --- /dev/null +++ b/adev-es/src/content/reference/errors/NG0200.en.md @@ -0,0 +1,12 @@ +# Circular Dependency in DI + + + +A cyclic dependency exists when a [dependency of a service](guide/di/hierarchical-dependency-injection) directly or indirectly depends on the service itself. For example, if `UserService` depends on `EmployeeService`, which also depends on `UserService`. Angular will have to instantiate `EmployeeService` to create `UserService`, which depends on `UserService`, itself. + +## Debugging the error + +Use the call stack to determine where the cyclical dependency exists. +You will be able to see if any child dependencies rely on the original file by [mapping out](guide/di/di-in-action) the component, module, or service's dependencies, and identifying the loop causing the problem. + +Break this loop \(or circle\) of dependency to resolve this error. This most commonly means removing or refactoring the dependencies to not be reliant on one another. diff --git a/adev-es/src/content/reference/errors/NG0200.md b/adev-es/src/content/reference/errors/NG0200.md index 0b5f0c4..702fb40 100644 --- a/adev-es/src/content/reference/errors/NG0200.md +++ b/adev-es/src/content/reference/errors/NG0200.md @@ -2,11 +2,11 @@ -A cyclic dependency exists when a [dependency of a service](guide/di/hierarchical-dependency-injection) directly or indirectly depends on the service itself. For example, if `UserService` depends on `EmployeeService`, which also depends on `UserService`. Angular will have to instantiate `EmployeeService` to create `UserService`, which depends on `UserService`, itself. +Existe una dependencia cíclica cuando una [dependencia de un servicio](guide/di/hierarchical-dependency-injection) depende directa o indirectamente del servicio mismo. Por ejemplo, si `UserService` depende de `EmployeeService`, que a su vez depende de `UserService`. Angular tendría que instanciar `EmployeeService` para crear `UserService`, el cual depende de `UserService` en sí mismo. -## Debugging the error +## Depurando el error -Use the call stack to determine where the cyclical dependency exists. -You will be able to see if any child dependencies rely on the original file by [mapping out](guide/di/di-in-action) the component, module, or service's dependencies, and identifying the loop causing the problem. +Usa la pila de llamadas para determinar dónde existe la dependencia cíclica. +Podrás ver si alguna dependencia hija depende del archivo original [trazando](guide/di/di-in-action) las dependencias del componente, módulo o servicio e identificando el bucle que causa el problema. -Break this loop \(or circle\) of dependency to resolve this error. This most commonly means removing or refactoring the dependencies to not be reliant on one another. +Rompe este bucle \(o círculo\) de dependencia para resolver este error. Esto generalmente significa eliminar o refactorizar las dependencias para que no dependan unas de otras. diff --git a/adev-es/src/content/reference/errors/NG0201.en.md b/adev-es/src/content/reference/errors/NG0201.en.md new file mode 100644 index 0000000..cf7fa57 --- /dev/null +++ b/adev-es/src/content/reference/errors/NG0201.en.md @@ -0,0 +1,19 @@ +# No Provider Found + + + +You see this error when you try to inject a service but have not declared a corresponding provider. A provider is a mapping that supplies a value that you can inject into the constructor of a class in your application. + +Read more on providers in our [Dependency Injection guide](guide/di). + +## Debugging the error + +Work backwards from the object where the error states that a provider is missing: `No provider for ${this}!`. This is commonly thrown in services, which require non-existing providers. + +To fix the error ensure that your service is registered in the list of providers of an `NgModule` or has the `@Injectable` decorator with a `providedIn` property at top. + +The most common solution is to add a provider in `@Injectable` using `providedIn`: + +```ts +@Injectable({ providedIn: 'app' }) +``` diff --git a/adev-es/src/content/reference/errors/NG0201.md b/adev-es/src/content/reference/errors/NG0201.md index cf7fa57..a3aa5a9 100644 --- a/adev-es/src/content/reference/errors/NG0201.md +++ b/adev-es/src/content/reference/errors/NG0201.md @@ -2,17 +2,17 @@ -You see this error when you try to inject a service but have not declared a corresponding provider. A provider is a mapping that supplies a value that you can inject into the constructor of a class in your application. +Ves este error cuando intentas inyectar un servicio pero no has declarado el proveedor correspondiente. Un proveedor es un mapeo que suministra un valor que puedes inyectar en el constructor de una clase en tu aplicación. -Read more on providers in our [Dependency Injection guide](guide/di). +Lee más sobre proveedores en nuestra [guía de Inyección de Dependencias](guide/di). -## Debugging the error +## Depurando el error -Work backwards from the object where the error states that a provider is missing: `No provider for ${this}!`. This is commonly thrown in services, which require non-existing providers. +Trabaja hacia atrás desde el objeto donde el error indica que falta un proveedor: `No provider for ${this}!`. Este error comúnmente se lanza en servicios que requieren proveedores inexistentes. -To fix the error ensure that your service is registered in the list of providers of an `NgModule` or has the `@Injectable` decorator with a `providedIn` property at top. +Para corregir el error, asegúrate de que tu servicio esté registrado en la lista de proveedores de un `NgModule` o tenga el decorador `@Injectable` con una propiedad `providedIn` en la parte superior. -The most common solution is to add a provider in `@Injectable` using `providedIn`: +La solución más común es agregar un proveedor en `@Injectable` usando `providedIn`: ```ts @Injectable({ providedIn: 'app' }) diff --git a/adev-es/src/content/reference/errors/NG0203.en.md b/adev-es/src/content/reference/errors/NG0203.en.md new file mode 100644 index 0000000..a0df691 --- /dev/null +++ b/adev-es/src/content/reference/errors/NG0203.en.md @@ -0,0 +1,60 @@ +# `inject()` must be called from an injection context + +You see this error when you try to use the [`inject`](api/core/inject) function outside of the allowed [injection context](guide/di/dependency-injection-context). The injection context is available during the class creation and initialization. It is also available to functions +used with `runInInjectionContext`. + +In practice the `inject()` calls are allowed in a constructor, a constructor parameter and a field initializer: + +```typescript +@Injectable({providedIn: 'root'}) +export class Car { + radio: Radio|undefined; + + // OK: field initializer + spareTyre = inject(Tyre); + + constructor() { + // OK: constructor body + this.radio = inject(Radio); + } +} +``` + +It is also legal to call [`inject`](api/core/inject) from a provider's factory: + +```typescript +providers: [ + {provide: Car, useFactory: () => { + // OK: a class factory + const engine = inject(Engine); + return new Car(engine); + }} +] +``` + +Calls to the [`inject`](api/core/inject) function outside of the class creation or `runInInjectionContext` will result in error. Most notably, calls to `inject()` are disallowed after a class instance was created, in methods (including lifecycle hooks): + +```typescript +@Component({ ... }) +export class CarComponent { + ngOnInit() { + // ERROR: too late, the component instance was already created + const engine = inject(Engine); + engine.start(); + } +} +``` + +## Debugging the error + +Work backwards from the stack trace of the error to identify a place where the disallowed call to `inject()` is located. + +To fix the error move the [`inject`](api/core/inject) call to an allowed place (usually a class constructor or a field initializer). + +**NOTE:** If you are running in a test context, `TestBed.runInInjectionContext` will enable `inject()` to succeed. + +```typescript +TestBed.runInInjectionContext(() => { + // ... +}); +``` diff --git a/adev-es/src/content/reference/errors/NG0203.md b/adev-es/src/content/reference/errors/NG0203.md index a0df691..9430542 100644 --- a/adev-es/src/content/reference/errors/NG0203.md +++ b/adev-es/src/content/reference/errors/NG0203.md @@ -1,57 +1,56 @@ # `inject()` must be called from an injection context -You see this error when you try to use the [`inject`](api/core/inject) function outside of the allowed [injection context](guide/di/dependency-injection-context). The injection context is available during the class creation and initialization. It is also available to functions -used with `runInInjectionContext`. +Ves este error cuando intentas usar la función [`inject`](api/core/inject) fuera del [contexto de inyección](guide/di/dependency-injection-context) permitido. El contexto de inyección está disponible durante la creación e inicialización de la clase. También está disponible para funciones usadas con `runInInjectionContext`. -In practice the `inject()` calls are allowed in a constructor, a constructor parameter and a field initializer: +En la práctica, las llamadas a `inject()` están permitidas en un constructor, en un parámetro del constructor y en un inicializador de campo: ```typescript @Injectable({providedIn: 'root'}) export class Car { radio: Radio|undefined; - // OK: field initializer + // OK: inicializador de campo spareTyre = inject(Tyre); constructor() { - // OK: constructor body + // OK: cuerpo del constructor this.radio = inject(Radio); } } ``` -It is also legal to call [`inject`](api/core/inject) from a provider's factory: +También es válido llamar a [`inject`](api/core/inject) desde la fábrica de un proveedor: ```typescript providers: [ {provide: Car, useFactory: () => { - // OK: a class factory + // OK: fábrica de una clase const engine = inject(Engine); return new Car(engine); }} ] ``` -Calls to the [`inject`](api/core/inject) function outside of the class creation or `runInInjectionContext` will result in error. Most notably, calls to `inject()` are disallowed after a class instance was created, in methods (including lifecycle hooks): +Las llamadas a la función [`inject`](api/core/inject) fuera de la creación de la clase o de `runInInjectionContext` resultarán en error. En particular, las llamadas a `inject()` no están permitidas después de que se crea la instancia de la clase, en métodos (incluyendo hooks de ciclo de vida): ```typescript @Component({ ... }) export class CarComponent { ngOnInit() { - // ERROR: too late, the component instance was already created + // ERROR: demasiado tarde, la instancia del componente ya fue creada const engine = inject(Engine); engine.start(); } } ``` -## Debugging the error +## Depurando el error -Work backwards from the stack trace of the error to identify a place where the disallowed call to `inject()` is located. +Trabaja hacia atrás desde la traza del error para identificar el lugar donde se encuentra la llamada no permitida a `inject()`. -To fix the error move the [`inject`](api/core/inject) call to an allowed place (usually a class constructor or a field initializer). +Para corregir el error, mueve la llamada a [`inject`](api/core/inject) a un lugar permitido (generalmente un constructor de clase o un inicializador de campo). -**NOTE:** If you are running in a test context, `TestBed.runInInjectionContext` will enable `inject()` to succeed. +**NOTA:** Si estás ejecutando en un contexto de prueba, `TestBed.runInInjectionContext` permitirá que `inject()` tenga éxito. ```typescript TestBed.runInInjectionContext(() => { diff --git a/adev-es/src/content/reference/errors/NG0209.en.md b/adev-es/src/content/reference/errors/NG0209.en.md new file mode 100644 index 0000000..5a9b861 --- /dev/null +++ b/adev-es/src/content/reference/errors/NG0209.en.md @@ -0,0 +1,5 @@ +# Invalid multi provider + +The Angular runtime will throw this error when it injects a token intended to be used with `multi: true` but +a non-Array was found instead. For example, `ENVIRONMENT_INITIALIZER` should be provided +like `{provide: ENVIRONMENT_INITIALIZER, multi: true, useValue: () => {...}}`. diff --git a/adev-es/src/content/reference/errors/NG0209.md b/adev-es/src/content/reference/errors/NG0209.md index 5a9b861..3dc1819 100644 --- a/adev-es/src/content/reference/errors/NG0209.md +++ b/adev-es/src/content/reference/errors/NG0209.md @@ -1,5 +1,3 @@ # Invalid multi provider -The Angular runtime will throw this error when it injects a token intended to be used with `multi: true` but -a non-Array was found instead. For example, `ENVIRONMENT_INITIALIZER` should be provided -like `{provide: ENVIRONMENT_INITIALIZER, multi: true, useValue: () => {...}}`. +El tiempo de ejecución de Angular lanzará este error cuando inyecte un token destinado a usarse con `multi: true` pero se encuentre un valor que no sea un Array. Por ejemplo, `ENVIRONMENT_INITIALIZER` debe proporcionarse así: `{provide: ENVIRONMENT_INITIALIZER, multi: true, useValue: () => {...}}`. diff --git a/adev-es/src/content/reference/errors/NG02200.en.md b/adev-es/src/content/reference/errors/NG02200.en.md new file mode 100644 index 0000000..79d9866 --- /dev/null +++ b/adev-es/src/content/reference/errors/NG02200.en.md @@ -0,0 +1,8 @@ +# Missing Iterable Differ + +`NgFor` could not find an iterable differ for the value passed in. Make sure it's an iterable, like an `Array`. + +## Debugging the error + +When using ngFor in a template, you must use some type of Iterable, like `Array`, `Set`, `Map`, etc. +If you're trying to iterate over the keys in an object, you should look at the [KeyValue pipe](/api/common/KeyValuePipe) instead. diff --git a/adev-es/src/content/reference/errors/NG02200.md b/adev-es/src/content/reference/errors/NG02200.md index 79d9866..4b58e94 100644 --- a/adev-es/src/content/reference/errors/NG02200.md +++ b/adev-es/src/content/reference/errors/NG02200.md @@ -1,8 +1,8 @@ # Missing Iterable Differ -`NgFor` could not find an iterable differ for the value passed in. Make sure it's an iterable, like an `Array`. +`NgFor` no pudo encontrar un diferenciador iterable para el valor pasado. Asegúrate de que sea un iterable, como un `Array`. -## Debugging the error +## Depurando el error -When using ngFor in a template, you must use some type of Iterable, like `Array`, `Set`, `Map`, etc. -If you're trying to iterate over the keys in an object, you should look at the [KeyValue pipe](/api/common/KeyValuePipe) instead. +Al usar ngFor en una plantilla, debes usar algún tipo de Iterable, como `Array`, `Set`, `Map`, etc. +Si estás intentando iterar sobre las claves de un objeto, deberías mirar el [pipe KeyValue](/api/common/KeyValuePipe) en su lugar. diff --git a/adev-es/src/content/reference/errors/NG02800.en.md b/adev-es/src/content/reference/errors/NG02800.en.md new file mode 100644 index 0000000..d364d6f --- /dev/null +++ b/adev-es/src/content/reference/errors/NG02800.en.md @@ -0,0 +1,11 @@ +# JSONP support in HttpClient configuration + +Angular produces this error when you attempt a `JSONP` request without providing the necessary support for it in the `HttpClient` configuration. +To enable `JSONP` support, you can do one of the following: + +- add the `withJsonpSupport()` as an argument during the `provideHttpClient` function call (e.g. `provideHttpClient(withJsonpSupport())`) when `bootstrapApplication` is useddocs +- import the `HttpClientJsonpModule` in your root AppModule, when NgModule-based bootstrap is used. + +## Debugging the error + +Make sure that the JSONP support is added into your application either by calling the `withJsonpSupport` function (when `provideHttpClient` is used) or importing the `HttpClientJsonpModule` module as described above. diff --git a/adev-es/src/content/reference/errors/NG02800.md b/adev-es/src/content/reference/errors/NG02800.md index d364d6f..0453605 100644 --- a/adev-es/src/content/reference/errors/NG02800.md +++ b/adev-es/src/content/reference/errors/NG02800.md @@ -1,11 +1,11 @@ # JSONP support in HttpClient configuration -Angular produces this error when you attempt a `JSONP` request without providing the necessary support for it in the `HttpClient` configuration. -To enable `JSONP` support, you can do one of the following: +Angular produce este error cuando intentas hacer una petición `JSONP` sin proporcionar el soporte necesario para ello en la configuración de `HttpClient`. +Para habilitar el soporte `JSONP`, puedes hacer una de las siguientes cosas: -- add the `withJsonpSupport()` as an argument during the `provideHttpClient` function call (e.g. `provideHttpClient(withJsonpSupport())`) when `bootstrapApplication` is useddocs -- import the `HttpClientJsonpModule` in your root AppModule, when NgModule-based bootstrap is used. +- agregar `withJsonpSupport()` como argumento durante la llamada a la función `provideHttpClient` (por ejemplo, `provideHttpClient(withJsonpSupport())`) cuando se usa `bootstrapApplication` +- importar el `HttpClientJsonpModule` en tu AppModule raíz, cuando se usa el bootstrap basado en NgModule. -## Debugging the error +## Depurando el error -Make sure that the JSONP support is added into your application either by calling the `withJsonpSupport` function (when `provideHttpClient` is used) or importing the `HttpClientJsonpModule` module as described above. +Asegúrate de que el soporte JSONP esté agregado a tu aplicación ya sea llamando a la función `withJsonpSupport` (cuando se usa `provideHttpClient`) o importando el módulo `HttpClientJsonpModule` como se describió anteriormente. diff --git a/adev-es/src/content/reference/errors/NG02802.en.md b/adev-es/src/content/reference/errors/NG02802.en.md new file mode 100644 index 0000000..fefbab6 --- /dev/null +++ b/adev-es/src/content/reference/errors/NG02802.en.md @@ -0,0 +1,41 @@ +# Headers not transferred by HttpTransferCache + +Angular produces this warning when code attempts to access an HTTP header that was not transferred from the server to the client by the `HttpTransferCache`. + +By default, `HttpTransferCache` does not transfer any headers to avoid potential security issues or unnecessary data transfer. When a header is accessed on the client that wasn't included, Angular logs this warning to help you identify missing headers. + +## Fixing the error + +To include specific headers in the transfer cache, use the `includeHeaders` option. + +### At the request level + +Add the `transferCache` parameter to your HTTP request: + +```typescript +this.http.get('/api/data', { + transferCache: { + includeHeaders: ['cache-control', 'etag'] + } +}); +``` + +### At the application level + +Configure `includeHeaders` when providing the transfer cache: + +```typescript +provideClientHydration( + withHttpTransferCache({ + includeHeaders: ['cache-control', 'etag'] + }) +); +``` + +Only include headers that are necessary for your application logic. Be cautious with sensitive headers. + +## Debugging the error + +The warning message includes the header name and the request URL. Check your code for where this header is being accessed and determine if it needs to be included in the transfer cache. + +If the header is not needed on the client, consider refactoring your code to avoid accessing it. diff --git a/adev-es/src/content/reference/errors/NG02802.md b/adev-es/src/content/reference/errors/NG02802.md index fefbab6..8a6fd04 100644 --- a/adev-es/src/content/reference/errors/NG02802.md +++ b/adev-es/src/content/reference/errors/NG02802.md @@ -1,16 +1,16 @@ # Headers not transferred by HttpTransferCache -Angular produces this warning when code attempts to access an HTTP header that was not transferred from the server to the client by the `HttpTransferCache`. +Angular produce esta advertencia cuando el código intenta acceder a un encabezado HTTP que no fue transferido del servidor al cliente por el `HttpTransferCache`. -By default, `HttpTransferCache` does not transfer any headers to avoid potential security issues or unnecessary data transfer. When a header is accessed on the client that wasn't included, Angular logs this warning to help you identify missing headers. +Por defecto, `HttpTransferCache` no transfiere ningún encabezado para evitar posibles problemas de seguridad o transferencia de datos innecesaria. Cuando se accede a un encabezado en el cliente que no fue incluido, Angular registra esta advertencia para ayudarte a identificar los encabezados faltantes. -## Fixing the error +## Corrigiendo el error -To include specific headers in the transfer cache, use the `includeHeaders` option. +Para incluir encabezados específicos en la caché de transferencia, usa la opción `includeHeaders`. -### At the request level +### A nivel de petición -Add the `transferCache` parameter to your HTTP request: +Agrega el parámetro `transferCache` a tu petición HTTP: ```typescript this.http.get('/api/data', { @@ -20,9 +20,9 @@ this.http.get('/api/data', { }); ``` -### At the application level +### A nivel de aplicación -Configure `includeHeaders` when providing the transfer cache: +Configura `includeHeaders` al proporcionar la caché de transferencia: ```typescript provideClientHydration( @@ -32,10 +32,10 @@ provideClientHydration( ); ``` -Only include headers that are necessary for your application logic. Be cautious with sensitive headers. +Solo incluye encabezados que sean necesarios para la lógica de tu aplicación. Ten cuidado con los encabezados sensibles. -## Debugging the error +## Depurando el error -The warning message includes the header name and the request URL. Check your code for where this header is being accessed and determine if it needs to be included in the transfer cache. +El mensaje de advertencia incluye el nombre del encabezado y la URL de la petición. Verifica en tu código dónde se accede a este encabezado y determina si necesita incluirse en la caché de transferencia. -If the header is not needed on the client, consider refactoring your code to avoid accessing it. +Si el encabezado no se necesita en el cliente, considera refactorizar tu código para evitar acceder a él. diff --git a/adev-es/src/content/reference/errors/NG0300.en.md b/adev-es/src/content/reference/errors/NG0300.en.md new file mode 100644 index 0000000..0c802ac --- /dev/null +++ b/adev-es/src/content/reference/errors/NG0300.en.md @@ -0,0 +1,51 @@ +# Selector Collision + + + +Two or more [components](guide/components) use the same element selector. Because there can only be a single component associated with an element, selectors must be unique strings to prevent ambiguity for Angular. + +This error occurs at runtime when you apply two selectors to a single node, each of which matches a different component, or when you apply a single selector to a node and it matches more than one component. + +```ts +import {Component} from '@angular/core'; + +@Component({ + selector: '[stroked-button]', + templateUrl: './stroked-button.component.html', +}) +export class StrokedBtnComponent {} + +@Component({ + selector: '[raised-button]', + templateUrl: './raised-button.component.html', +}) +export class RaisedBtnComponent {} + +@Component({ + selector: 'app-root', + template: ` + + + + +`, +}) +export class AppComponent {} +``` + +## Debugging the error + +Use the element name from the error message to search for places where you're using the same selector declaration in your codebase: + +```ts + +@Component({ + selector: 'YOUR_STRING', +… +}) + +``` + +Ensure that each component has a unique CSS selector. This will guarantee that Angular renders the component you expect. + +If you're having trouble finding multiple components with this selector tag name, check for components from imported component libraries, such as Angular Material. Make sure you're following the [best practices](style-guide#component-selectors) for your selectors to prevent collisions. diff --git a/adev-es/src/content/reference/errors/NG0300.md b/adev-es/src/content/reference/errors/NG0300.md index 0c802ac..1b4aceb 100644 --- a/adev-es/src/content/reference/errors/NG0300.md +++ b/adev-es/src/content/reference/errors/NG0300.md @@ -2,9 +2,9 @@ -Two or more [components](guide/components) use the same element selector. Because there can only be a single component associated with an element, selectors must be unique strings to prevent ambiguity for Angular. +Dos o más [componentes](guide/components) usan el mismo selector de elemento. Dado que solo puede haber un componente asociado a un elemento, los selectores deben ser cadenas únicas para evitar ambigüedades en Angular. -This error occurs at runtime when you apply two selectors to a single node, each of which matches a different component, or when you apply a single selector to a node and it matches more than one component. +Este error ocurre en tiempo de ejecución cuando aplicas dos selectores a un solo nodo, cada uno de los cuales coincide con un componente diferente, o cuando aplicas un único selector a un nodo y coincide con más de un componente. ```ts import {Component} from '@angular/core'; @@ -25,7 +25,7 @@ export class RaisedBtnComponent {} selector: 'app-root', template: ` - + `, @@ -33,9 +33,9 @@ export class RaisedBtnComponent {} export class AppComponent {} ``` -## Debugging the error +## Depurando el error -Use the element name from the error message to search for places where you're using the same selector declaration in your codebase: +Usa el nombre del elemento del mensaje de error para buscar los lugares donde estás usando la misma declaración de selector en tu base de código: ```ts @@ -46,6 +46,6 @@ Use the element name from the error message to search for places where you're us ``` -Ensure that each component has a unique CSS selector. This will guarantee that Angular renders the component you expect. +Asegúrate de que cada componente tenga un selector CSS único. Esto garantizará que Angular renderice el componente que esperas. -If you're having trouble finding multiple components with this selector tag name, check for components from imported component libraries, such as Angular Material. Make sure you're following the [best practices](style-guide#component-selectors) for your selectors to prevent collisions. +Si tienes dificultades para encontrar múltiples componentes con este nombre de selector, verifica los componentes de las librerías de componentes importadas, como Angular Material. Asegúrate de seguir las [mejores prácticas](style-guide#component-selectors) para tus selectores a fin de prevenir colisiones. diff --git a/adev-es/src/content/reference/errors/NG0301.en.md b/adev-es/src/content/reference/errors/NG0301.en.md new file mode 100644 index 0000000..6b4048e --- /dev/null +++ b/adev-es/src/content/reference/errors/NG0301.en.md @@ -0,0 +1,27 @@ +# Export Not Found + + + +Angular can't find a directive with `{{ PLACEHOLDER }}` export name. The export name is specified in the `exportAs` property of the directive decorator. This is common when using FormsModule or Material modules in templates and you've forgotten to import the corresponding modules. + +HELPFUL: This is the runtime equivalent of a common compiler error [NG8003: No directive found with export](errors/NG8003). + +## Debugging the error + +Use the export name to trace the templates or modules using this export. + +Ensure that all dependencies are properly imported and declared in your NgModules. For example, if the export not found is `ngForm`, we need to import `FormsModule` and declare it in the list of imports in `*.module.ts` to resolve the error. + +```ts + +import { FormsModule } from '@angular/forms'; + +@NgModule({ +… +imports: [ +FormsModule, +… + +``` + +If you recently added an import, you may need to restart your server to see these changes. diff --git a/adev-es/src/content/reference/errors/NG0301.md b/adev-es/src/content/reference/errors/NG0301.md index 6b4048e..bd46c27 100644 --- a/adev-es/src/content/reference/errors/NG0301.md +++ b/adev-es/src/content/reference/errors/NG0301.md @@ -2,15 +2,15 @@ -Angular can't find a directive with `{{ PLACEHOLDER }}` export name. The export name is specified in the `exportAs` property of the directive decorator. This is common when using FormsModule or Material modules in templates and you've forgotten to import the corresponding modules. +Angular no puede encontrar una directiva con el nombre de exportación `{{ PLACEHOLDER }}`. El nombre de exportación se especifica en la propiedad `exportAs` del decorador de la directiva. Esto es común cuando se usan FormsModule o módulos de Material en las plantillas y se ha olvidado importar los módulos correspondientes. -HELPFUL: This is the runtime equivalent of a common compiler error [NG8003: No directive found with export](errors/NG8003). +ÚTIL: Este es el equivalente en tiempo de ejecución de un error de compilador común [NG8003: No se encontró ninguna directiva con exportación](errors/NG8003). -## Debugging the error +## Depurando el error -Use the export name to trace the templates or modules using this export. +Usa el nombre de exportación para rastrear las plantillas o módulos que usan esta exportación. -Ensure that all dependencies are properly imported and declared in your NgModules. For example, if the export not found is `ngForm`, we need to import `FormsModule` and declare it in the list of imports in `*.module.ts` to resolve the error. +Asegúrate de que todas las dependencias estén correctamente importadas y declaradas en tus NgModules. Por ejemplo, si la exportación no encontrada es `ngForm`, necesitas importar `FormsModule` y declararlo en la lista de importaciones en `*.module.ts` para resolver el error. ```ts @@ -24,4 +24,4 @@ FormsModule, ``` -If you recently added an import, you may need to restart your server to see these changes. +Si recientemente agregaste una importación, es posible que necesites reiniciar tu servidor para ver estos cambios. diff --git a/adev-es/src/content/reference/errors/NG0302.en.md b/adev-es/src/content/reference/errors/NG0302.en.md new file mode 100644 index 0000000..451b2b6 --- /dev/null +++ b/adev-es/src/content/reference/errors/NG0302.en.md @@ -0,0 +1,23 @@ +# Pipe Not Found + + + +Angular can't find a pipe with this name. + +The [pipe](guide/templates/pipes) referenced in the template has not been named or declared properly. + +To use the pipe: + +- Ensure the name used in a template matches the name defined in the pipe decorator. +- Add the pipe to your component's `imports` array or, if the pipe sets `standalone: false`, add the `NgModule` to which the pipe belongs. + +## Debugging the error + +Use the pipe name to trace where the pipe is declared and used. + +To resolve this error: + +- If the pipe is local to the `NgModule`, give it a unique name in the pipe's decorator and declared it in the `NgModule`. +- If the pipe is standalone or is declared in another `NgModule`, add it to the `imports` field of the standalone component or the current `NgModule`. + +If you recently added an import or declaration, you may need to restart your server to see these changes. diff --git a/adev-es/src/content/reference/errors/NG0302.md b/adev-es/src/content/reference/errors/NG0302.md index 451b2b6..f9bade5 100644 --- a/adev-es/src/content/reference/errors/NG0302.md +++ b/adev-es/src/content/reference/errors/NG0302.md @@ -2,22 +2,22 @@ -Angular can't find a pipe with this name. +Angular no puede encontrar un pipe con este nombre. -The [pipe](guide/templates/pipes) referenced in the template has not been named or declared properly. +El [pipe](guide/templates/pipes) referenciado en la plantilla no ha sido nombrado o declarado correctamente. -To use the pipe: +Para usar el pipe: -- Ensure the name used in a template matches the name defined in the pipe decorator. -- Add the pipe to your component's `imports` array or, if the pipe sets `standalone: false`, add the `NgModule` to which the pipe belongs. +- Asegúrate de que el nombre usado en la plantilla coincida con el nombre definido en el decorador del pipe. +- Agrega el pipe al array `imports` de tu componente o, si el pipe tiene `standalone: false`, agrega el `NgModule` al que pertenece el pipe. -## Debugging the error +## Depurando el error -Use the pipe name to trace where the pipe is declared and used. +Usa el nombre del pipe para rastrear dónde está declarado y usado. -To resolve this error: +Para resolver este error: -- If the pipe is local to the `NgModule`, give it a unique name in the pipe's decorator and declared it in the `NgModule`. -- If the pipe is standalone or is declared in another `NgModule`, add it to the `imports` field of the standalone component or the current `NgModule`. +- Si el pipe es local al `NgModule`, dale un nombre único en el decorador del pipe y decláralo en el `NgModule`. +- Si el pipe es standalone o está declarado en otro `NgModule`, agrégalo al campo `imports` del componente standalone o del `NgModule` actual. -If you recently added an import or declaration, you may need to restart your server to see these changes. +Si recientemente agregaste una importación o declaración, es posible que necesites reiniciar tu servidor para ver estos cambios. diff --git a/adev-es/src/content/reference/errors/NG0401.en.md b/adev-es/src/content/reference/errors/NG0401.en.md new file mode 100644 index 0000000..af7037a --- /dev/null +++ b/adev-es/src/content/reference/errors/NG0401.en.md @@ -0,0 +1,18 @@ +# Missing Platform + +Angular requires a platform to be initialized. This error is thrown when `bootstrapApplication` is used on the server without providing a `BootstrapContext`. + +When using server-side rendering, `bootstrapApplication` requires a `BootstrapContext` to be passed as an argument. + +## Debugging the error + +To resolve this error, ensure that your `main.server.ts` file correctly passes a `BootstrapContext` to the `bootstrapApplication` function. + +```typescript +import { bootstrapApplication, BootstrapContext } from '@angular/platform-browser'; +import { App } from './app/app'; +import { config } from './app/app.config.server'; + +const bootstrap = (context: BootstrapContext) => bootstrapApplication(App, config, context); +export default bootstrap; +``` diff --git a/adev-es/src/content/reference/errors/NG0401.md b/adev-es/src/content/reference/errors/NG0401.md index af7037a..54b9531 100644 --- a/adev-es/src/content/reference/errors/NG0401.md +++ b/adev-es/src/content/reference/errors/NG0401.md @@ -1,12 +1,12 @@ # Missing Platform -Angular requires a platform to be initialized. This error is thrown when `bootstrapApplication` is used on the server without providing a `BootstrapContext`. +Angular requiere que se inicialice una plataforma. Este error se lanza cuando `bootstrapApplication` se usa en el servidor sin proporcionar un `BootstrapContext`. -When using server-side rendering, `bootstrapApplication` requires a `BootstrapContext` to be passed as an argument. +Al usar renderización del lado del servidor, `bootstrapApplication` requiere que se pase un `BootstrapContext` como argumento. -## Debugging the error +## Depurando el error -To resolve this error, ensure that your `main.server.ts` file correctly passes a `BootstrapContext` to the `bootstrapApplication` function. +Para resolver este error, asegúrate de que tu archivo `main.server.ts` pase correctamente un `BootstrapContext` a la función `bootstrapApplication`. ```typescript import { bootstrapApplication, BootstrapContext } from '@angular/platform-browser'; diff --git a/adev-es/src/content/reference/errors/NG0403.en.md b/adev-es/src/content/reference/errors/NG0403.en.md new file mode 100644 index 0000000..a78c1d9 --- /dev/null +++ b/adev-es/src/content/reference/errors/NG0403.en.md @@ -0,0 +1,41 @@ +# Bootstrapped NgModule doesn't specify which component to initialize + +This error means that an NgModule that was used for bootstrapping an application is missing key information for Angular to proceed with the bootstrap process. + +The error happens when the NgModule `bootstrap` property is missing (or is an empty array) in the `@NgModule` annotation and there is no `ngDoBootstrap` lifecycle hook defined on that NgModule class. + +More information about the bootstrapping process can be found in [this guide](guide/ngmodules/bootstrapping). + +The following examples will trigger the error. + +```typescript +@NgModule({ + declarations: [AppComponent], + imports: [BrowserModule, AppRoutingModule], + providers: [], +}) +export class AppModule {} + +// The `AppModule` is used for bootstrapping, but the `@NgModule.bootstrap` field is missing. +platformBrowser().bootstrapModule(AppModule); +``` + +```typescript +@NgModule({ + declarations: [AppComponent], + imports: [BrowserModule, AppRoutingModule], + providers: [], + bootstrap: [], +}) +export class AppModule {} + +// The `AppModule` is used for bootstrapping, but the `@NgModule.bootstrap` field contains an empty array. +platformBrowser().bootstrapModule(AppModule); +``` + +## Debugging the error + +Please make sure that the NgModule that is used for bootstrapping is set up correctly: + +- either the `bootstrap` property exists (and contains a non-empty array) in the `@NgModule` annotation +- or the `ngDoBootstrap` method exists on the NgModule class diff --git a/adev-es/src/content/reference/errors/NG0403.md b/adev-es/src/content/reference/errors/NG0403.md index a78c1d9..0967a0d 100644 --- a/adev-es/src/content/reference/errors/NG0403.md +++ b/adev-es/src/content/reference/errors/NG0403.md @@ -1,12 +1,12 @@ # Bootstrapped NgModule doesn't specify which component to initialize -This error means that an NgModule that was used for bootstrapping an application is missing key information for Angular to proceed with the bootstrap process. +Este error significa que un NgModule que se usó para el bootstrap de una aplicación carece de información clave para que Angular proceda con el proceso de bootstrap. -The error happens when the NgModule `bootstrap` property is missing (or is an empty array) in the `@NgModule` annotation and there is no `ngDoBootstrap` lifecycle hook defined on that NgModule class. +El error ocurre cuando la propiedad `bootstrap` del NgModule está ausente (o es un array vacío) en la anotación `@NgModule` y no hay un hook de ciclo de vida `ngDoBootstrap` definido en esa clase NgModule. -More information about the bootstrapping process can be found in [this guide](guide/ngmodules/bootstrapping). +Puedes encontrar más información sobre el proceso de bootstrap en [esta guía](guide/ngmodules/bootstrapping). -The following examples will trigger the error. +Los siguientes ejemplos activarán el error. ```typescript @NgModule({ @@ -16,7 +16,7 @@ The following examples will trigger the error. }) export class AppModule {} -// The `AppModule` is used for bootstrapping, but the `@NgModule.bootstrap` field is missing. +// El `AppModule` se usa para el bootstrap, pero el campo `@NgModule.bootstrap` está ausente. platformBrowser().bootstrapModule(AppModule); ``` @@ -29,13 +29,13 @@ platformBrowser().bootstrapModule(AppModule); }) export class AppModule {} -// The `AppModule` is used for bootstrapping, but the `@NgModule.bootstrap` field contains an empty array. +// El `AppModule` se usa para el bootstrap, pero el campo `@NgModule.bootstrap` contiene un array vacío. platformBrowser().bootstrapModule(AppModule); ``` -## Debugging the error +## Depurando el error -Please make sure that the NgModule that is used for bootstrapping is set up correctly: +Asegúrate de que el NgModule que se usa para el bootstrap esté configurado correctamente: -- either the `bootstrap` property exists (and contains a non-empty array) in the `@NgModule` annotation -- or the `ngDoBootstrap` method exists on the NgModule class +- ya sea que la propiedad `bootstrap` exista (y contenga un array no vacío) en la anotación `@NgModule` +- o que el método `ngDoBootstrap` exista en la clase NgModule diff --git a/adev-es/src/content/reference/errors/NG0500.en.md b/adev-es/src/content/reference/errors/NG0500.en.md new file mode 100644 index 0000000..3c5d6b0 --- /dev/null +++ b/adev-es/src/content/reference/errors/NG0500.en.md @@ -0,0 +1,41 @@ +# Hydration Node Mismatch + +This error means that during the hydration process, Angular expected a DOM structure as rendered and annotated during server-side rendering. However, on the client, the DOM tree was different than the server rendered DOM tree. + +This error typically happens due to direct DOM manipulation using native browser APIs that alter the DOM structure outside of what Angular produced. It will also occur if you use `innerHTML` or `outerHTML` to set HTML content, which similarly alters the DOM structure outside of what Angular produced. You can resolve this by refactoring the component to use native Angular APIs instead of native APIs. If that's not possible, you can add the `ngSkipHydration` attribute to your component's host node, which will disable hydration for the component and its children. `ngSkipHydration` should only be used as a last resort and should be considered a bug that needs to be fixed. + +More information about hydration can be found in [this guide](guide/hydration). + +The following example will trigger the error. + +```typescript +@Component({ + selector: 'app-example', + template: '
world
', +}) +export class ExampleComponent { + hostElement = inject(ElementRef).nativeElement; + + ngOnInit() { + // Create a new

element with the `Hello` text inside + const newNode = document.createElement('p'); + newNode.innerHTML = 'Hello'; + + // Insert the

before the first element. Since Angular has no information + // about the

element, it will be looking for the

element at the first + // element position instead. As a result, a hydration mismatch error would be + // thrown. Instead, update component's template to create the

element. + this.hostElement.insertBefore(newNode, this.hostElement.firstChild); + } +} +``` + +## Debugging the error + +The error message in the developer console should contain information on a specific part of the application's DOM structure that is causing the problem. Review that part of the application for hydration-related errors, such as direct DOM manipulation using native APIs. + +Check that your template has valid HTML structure. See more information in the [hydration guide](guide/hydration#valid-html-structure). + +You can add the `ngSkipHydration` attribute to your component host node as a possible workaround. + +If your application works in development environment, but you see hydration errors in production builds, make sure that the generated HTML that is delivered to a browser contains comment nodes produced by Angular during the rendering on the server. Those comment nodes are used by Angular runtime as anchors for view containers (with and without hydration) and hydration process expects them to be present at their original locations. If you have a custom logic to remove comment nodes from the HTML generated by the server-side rendering or you've configured your CDN to remove them before serving the content - disable the comment nodes removal and check if hydration errors are gone. diff --git a/adev-es/src/content/reference/errors/NG0500.md b/adev-es/src/content/reference/errors/NG0500.md index 3c5d6b0..ac04669 100644 --- a/adev-es/src/content/reference/errors/NG0500.md +++ b/adev-es/src/content/reference/errors/NG0500.md @@ -1,12 +1,12 @@ # Hydration Node Mismatch -This error means that during the hydration process, Angular expected a DOM structure as rendered and annotated during server-side rendering. However, on the client, the DOM tree was different than the server rendered DOM tree. +Este error significa que durante el proceso de hidratación, Angular esperaba una estructura DOM tal como fue renderizada y anotada durante la renderización del lado del servidor. Sin embargo, en el cliente, el árbol DOM era diferente al árbol DOM renderizado por el servidor. -This error typically happens due to direct DOM manipulation using native browser APIs that alter the DOM structure outside of what Angular produced. It will also occur if you use `innerHTML` or `outerHTML` to set HTML content, which similarly alters the DOM structure outside of what Angular produced. You can resolve this by refactoring the component to use native Angular APIs instead of native APIs. If that's not possible, you can add the `ngSkipHydration` attribute to your component's host node, which will disable hydration for the component and its children. `ngSkipHydration` should only be used as a last resort and should be considered a bug that needs to be fixed. +Este error ocurre típicamente debido a la manipulación directa del DOM usando APIs nativas del navegador que alteran la estructura DOM fuera de lo que Angular produjo. También ocurrirá si usas `innerHTML` u `outerHTML` para establecer contenido HTML, lo que altera igualmente la estructura DOM fuera de lo que Angular produjo. Puedes resolver esto refactorizando el componente para usar APIs nativas de Angular en lugar de APIs nativas. Si eso no es posible, puedes agregar el atributo `ngSkipHydration` al nodo host de tu componente, lo que deshabilitará la hidratación para el componente y sus hijos. `ngSkipHydration` solo debe usarse como último recurso y debe considerarse un error que necesita corregirse. -More information about hydration can be found in [this guide](guide/hydration). +Puedes encontrar más información sobre la hidratación en [esta guía](guide/hydration). -The following example will trigger the error. +El siguiente ejemplo activará el error. ```typescript @Component({ @@ -17,25 +17,25 @@ export class ExampleComponent { hostElement = inject(ElementRef).nativeElement; ngOnInit() { - // Create a new

element with the `Hello` text inside + // Crea un nuevo elemento

con el texto `Hello` dentro const newNode = document.createElement('p'); newNode.innerHTML = 'Hello'; - // Insert the

before the first element. Since Angular has no information - // about the

element, it will be looking for the

element at the first - // element position instead. As a result, a hydration mismatch error would be - // thrown. Instead, update component's template to create the

element. + // Inserta el

antes del primer elemento. Como Angular no tiene información + // sobre el elemento

, buscará el elemento

en la primera + // posición del elemento. Como resultado, se lanzará un error de discordancia de hidratación. + // En su lugar, actualiza la plantilla del componente para crear el elemento

. this.hostElement.insertBefore(newNode, this.hostElement.firstChild); } } ``` -## Debugging the error +## Depurando el error -The error message in the developer console should contain information on a specific part of the application's DOM structure that is causing the problem. Review that part of the application for hydration-related errors, such as direct DOM manipulation using native APIs. +El mensaje de error en la consola del desarrollador debe contener información sobre una parte específica de la estructura DOM de la aplicación que está causando el problema. Revisa esa parte de la aplicación en busca de errores relacionados con la hidratación, como la manipulación directa del DOM usando APIs nativas. -Check that your template has valid HTML structure. See more information in the [hydration guide](guide/hydration#valid-html-structure). +Verifica que tu plantilla tenga una estructura HTML válida. Consulta más información en la [guía de hidratación](guide/hydration#valid-html-structure). -You can add the `ngSkipHydration` attribute to your component host node as a possible workaround. +Puedes agregar el atributo `ngSkipHydration` al nodo host de tu componente como posible solución alternativa. -If your application works in development environment, but you see hydration errors in production builds, make sure that the generated HTML that is delivered to a browser contains comment nodes produced by Angular during the rendering on the server. Those comment nodes are used by Angular runtime as anchors for view containers (with and without hydration) and hydration process expects them to be present at their original locations. If you have a custom logic to remove comment nodes from the HTML generated by the server-side rendering or you've configured your CDN to remove them before serving the content - disable the comment nodes removal and check if hydration errors are gone. +Si tu aplicación funciona en el entorno de desarrollo, pero ves errores de hidratación en las compilaciones de producción, asegúrate de que el HTML generado que se entrega al navegador contenga nodos de comentarios producidos por Angular durante la renderización en el servidor. Esos nodos de comentarios son usados por el tiempo de ejecución de Angular como anclajes para los contenedores de vista (con y sin hidratación) y el proceso de hidratación espera que estén en sus ubicaciones originales. Si tienes lógica personalizada para eliminar nodos de comentarios del HTML generado por la renderización del lado del servidor, o has configurado tu CDN para eliminarlos antes de servir el contenido, deshabilita la eliminación de nodos de comentarios y verifica si los errores de hidratación desaparecen. diff --git a/adev-es/src/content/reference/errors/NG5000.md b/adev-es/src/content/reference/errors/NG05000.en.md similarity index 100% rename from adev-es/src/content/reference/errors/NG5000.md rename to adev-es/src/content/reference/errors/NG05000.en.md diff --git a/adev-es/src/content/reference/errors/NG05000.md b/adev-es/src/content/reference/errors/NG05000.md index 6e7f135..7f2efc8 100644 --- a/adev-es/src/content/reference/errors/NG05000.md +++ b/adev-es/src/content/reference/errors/NG05000.md @@ -1,11 +1,11 @@ # Hydration with unsupported Zone.js instance -This warning means that the hydration was enabled for an application that was configured to use an unsupported version of Zone.js: either a custom or a "noop" one (see more info [here](api/core/BootstrapOptions#ngZone)). +Esta advertencia significa que la hidratación estaba habilitada para una aplicación configurada para usar una versión no compatible de Zone.js: ya sea una personalizada o una "noop" (consulta más información [aquí](api/core/BootstrapOptions#ngZone)). -Hydration relies on a signal from Zone.js when it becomes stable inside an application, so that Angular can start the serialization process on the server or post-hydration cleanup on the client (to remove DOM nodes that remained unclaimed). +La hidratación depende de una señal de Zone.js cuando se vuelve estable dentro de una aplicación, para que Angular pueda iniciar el proceso de serialización en el servidor o la limpieza posterior a la hidratación en el cliente (para eliminar los nodos DOM que quedaron sin reclamar). -Providing a custom or a "noop" Zone.js implementation may lead to a different timing of the "stable" event, thus triggering the serialization or the cleanup too early or too late. This is not yet a fully supported configuration. +Proporcionar una implementación personalizada o "noop" de Zone.js puede llevar a una temporización diferente del evento "stable", lo que activa la serialización o la limpieza demasiado pronto o demasiado tarde. Esta configuración aún no está completamente soportada. -If you use a custom Zone.js implementation, make sure that the "onStable" event is emitted at the right time and does not result in incorrect application behavior with hydration. +Si usas una implementación personalizada de Zone.js, asegúrate de que el evento "onStable" se emita en el momento correcto y no resulte en un comportamiento incorrecto de la aplicación con la hidratación. -More information about hydration can be found in the [hydration guide](guide/hydration). +Puedes encontrar más información sobre la hidratación en la [guía de hidratación](guide/hydration). diff --git a/adev-es/src/content/reference/errors/NG0501.en.md b/adev-es/src/content/reference/errors/NG0501.en.md new file mode 100644 index 0000000..d490466 --- /dev/null +++ b/adev-es/src/content/reference/errors/NG0501.en.md @@ -0,0 +1,7 @@ +# Hydration Missing Siblings + +This error is similar to the [error NG0500](errors/NG0500), but it indicates that Angular hydration process expected more siblings present in the DOM structure at a particular location. Please refer to the [error NG0500](errors/NG0500) page for additional information. + +## Debugging the error + +See the [error NG0500](errors/NG0500) for more information on how to debug this error. diff --git a/adev-es/src/content/reference/errors/NG0501.md b/adev-es/src/content/reference/errors/NG0501.md index d490466..481d68e 100644 --- a/adev-es/src/content/reference/errors/NG0501.md +++ b/adev-es/src/content/reference/errors/NG0501.md @@ -1,7 +1,7 @@ # Hydration Missing Siblings -This error is similar to the [error NG0500](errors/NG0500), but it indicates that Angular hydration process expected more siblings present in the DOM structure at a particular location. Please refer to the [error NG0500](errors/NG0500) page for additional information. +Este error es similar al [error NG0500](errors/NG0500), pero indica que el proceso de hidratación de Angular esperaba más hermanos presentes en la estructura DOM en una ubicación particular. Consulta la página del [error NG0500](errors/NG0500) para obtener información adicional. -## Debugging the error +## Depurando el error -See the [error NG0500](errors/NG0500) for more information on how to debug this error. +Consulta el [error NG0500](errors/NG0500) para más información sobre cómo depurar este error. diff --git a/adev-es/src/content/reference/errors/NG0502.en.md b/adev-es/src/content/reference/errors/NG0502.en.md new file mode 100644 index 0000000..a0ba1df --- /dev/null +++ b/adev-es/src/content/reference/errors/NG0502.en.md @@ -0,0 +1,7 @@ +# Hydration Missing Node + +This error is similar to the [error NG0500](errors/NG0500), but it indicates that Angular hydration process expected a node to be present in the DOM structure at a particular location and none was found. Please refer to the [error NG0500](errors/NG0500) page for additional information. + +## Debugging the error + +See the [error NG0500](errors/NG0500) for more information on how to debug this error. diff --git a/adev-es/src/content/reference/errors/NG0502.md b/adev-es/src/content/reference/errors/NG0502.md index a0ba1df..806d172 100644 --- a/adev-es/src/content/reference/errors/NG0502.md +++ b/adev-es/src/content/reference/errors/NG0502.md @@ -1,7 +1,7 @@ # Hydration Missing Node -This error is similar to the [error NG0500](errors/NG0500), but it indicates that Angular hydration process expected a node to be present in the DOM structure at a particular location and none was found. Please refer to the [error NG0500](errors/NG0500) page for additional information. +Este error es similar al [error NG0500](errors/NG0500), pero indica que el proceso de hidratación de Angular esperaba que hubiera un nodo presente en la estructura DOM en una ubicación particular y no se encontró ninguno. Consulta la página del [error NG0500](errors/NG0500) para obtener información adicional. -## Debugging the error +## Depurando el error -See the [error NG0500](errors/NG0500) for more information on how to debug this error. +Consulta el [error NG0500](errors/NG0500) para más información sobre cómo depurar este error. diff --git a/adev-es/src/content/reference/errors/NG0503.en.md b/adev-es/src/content/reference/errors/NG0503.en.md new file mode 100644 index 0000000..950821a --- /dev/null +++ b/adev-es/src/content/reference/errors/NG0503.en.md @@ -0,0 +1,45 @@ +# Hydration Unsupported Projection of DOM Nodes + +This error means that during the server-side serialization process, Angular encountered nodes that were created outside of Angular's context (i.e. using native DOM APIs) and found those nodes were provided as projectable nodes. They were likely provided using `ViewContainerRef.createComponent` or `createComponent` APIs. Angular hydration does not support this use case. + +More information about hydration can be found in [this guide](guide/hydration). + +The following examples will trigger the error. + +```typescript +@Component({ + selector: 'dynamic', + template: ` + +`, +}) +class DynamicComponent { +} + +@Component({ + selector: 'app', + template: `

`, +}) +class SimpleComponent { + @ViewChild('target', {read: ViewContainerRef}) vcr!: ViewContainerRef; + envInjector = inject(EnvironmentInjector); + + ngAfterViewInit() { + const div = document.createElement('div'); + const p = document.createElement('p'); + // In this test we create DOM nodes outside of Angular context + // (i.e. not using Angular APIs) and try to content-project them. + // This is an unsupported pattern and an exception will be thrown. + const compRef = createComponent(DynamicComponent, { + environmentInjector: this.envInjector, + projectableNodes: [[div, p]] + }); + } +} +``` + +## Debugging the error + +The error message in the developer console should contain information on a specific part of the application's DOM structure that is causing the problem. Review that part of the application for hydration-related errors, such as direct DOM manipulation using native APIs. + +You can add the `ngSkipHydration` attribute to your component host node as a possible workaround. diff --git a/adev-es/src/content/reference/errors/NG0503.md b/adev-es/src/content/reference/errors/NG0503.md index 950821a..99b0984 100644 --- a/adev-es/src/content/reference/errors/NG0503.md +++ b/adev-es/src/content/reference/errors/NG0503.md @@ -1,10 +1,10 @@ # Hydration Unsupported Projection of DOM Nodes -This error means that during the server-side serialization process, Angular encountered nodes that were created outside of Angular's context (i.e. using native DOM APIs) and found those nodes were provided as projectable nodes. They were likely provided using `ViewContainerRef.createComponent` or `createComponent` APIs. Angular hydration does not support this use case. +Este error significa que durante el proceso de serialización del lado del servidor, Angular encontró nodos que fueron creados fuera del contexto de Angular (es decir, usando APIs nativas del DOM) y detectó que esos nodos se proporcionaban como nodos proyectables. Probablemente se proporcionaron usando las APIs `ViewContainerRef.createComponent` o `createComponent`. La hidratación de Angular no admite este caso de uso. -More information about hydration can be found in [this guide](guide/hydration). +Puedes encontrar más información sobre la hidratación en [esta guía](guide/hydration). -The following examples will trigger the error. +Los siguientes ejemplos activarán el error. ```typescript @Component({ @@ -27,9 +27,9 @@ class SimpleComponent { ngAfterViewInit() { const div = document.createElement('div'); const p = document.createElement('p'); - // In this test we create DOM nodes outside of Angular context - // (i.e. not using Angular APIs) and try to content-project them. - // This is an unsupported pattern and an exception will be thrown. + // En esta prueba creamos nodos DOM fuera del contexto de Angular + // (es decir, sin usar APIs de Angular) e intentamos proyectarlos como contenido. + // Este es un patrón no compatible y se lanzará una excepción. const compRef = createComponent(DynamicComponent, { environmentInjector: this.envInjector, projectableNodes: [[div, p]] @@ -38,8 +38,8 @@ class SimpleComponent { } ``` -## Debugging the error +## Depurando el error -The error message in the developer console should contain information on a specific part of the application's DOM structure that is causing the problem. Review that part of the application for hydration-related errors, such as direct DOM manipulation using native APIs. +El mensaje de error en la consola del desarrollador debe contener información sobre una parte específica de la estructura DOM de la aplicación que está causando el problema. Revisa esa parte de la aplicación en busca de errores relacionados con la hidratación, como la manipulación directa del DOM usando APIs nativas. -You can add the `ngSkipHydration` attribute to your component host node as a possible workaround. +Puedes agregar el atributo `ngSkipHydration` al nodo host de tu componente como posible solución alternativa. diff --git a/adev-es/src/content/reference/errors/NG0504.en.md b/adev-es/src/content/reference/errors/NG0504.en.md new file mode 100644 index 0000000..b45b1c3 --- /dev/null +++ b/adev-es/src/content/reference/errors/NG0504.en.md @@ -0,0 +1,50 @@ +# Skip hydration flag is applied to an invalid node + +This error occurs when the `ngSkipHydration` attribute was added to an inappropriate DOM node. The `ngSkipHydration` attribute can only be applied to component host nodes either directly in the template or via a host binding. It cannot be applied to other DOM nodes and will have no effect if done so other than causing this error. + +More information about hydration can be found in [this guide](guide/hydration). + +The following examples will trigger the error. + +## Example 1 + +In this example, the `ngSkipHydration` attribute is applied to a `
` using host bindings of a directive. Since the `
` doesn't act as a component host node, Angular will throw an error. + +```typescript +@Directive({ + selector: '[dir]', + host: {ngSkipHydration: 'true'}, +}) +class Dir { +} + +@Component({ + selector: 'app', + imports: [Dir], + template: ` +
+ `, +}) +class SimpleComponent { +} +``` + +## Example 2 + +In this example, the `ngSkipHydration` is applied to a `
` as an attribute via a template. +Since the `
` doesn't act as a component host node, Angular will throw an error. + +```typescript +@Component({ + selector: 'app', + template: ` +
+ `, +}) +class SimpleComponent { +} +``` + +## Debugging the error + +Remove the `ngSkipHydration` attribute from any invalid DOM nodes. Alternatively, move the `ngSkipHydration` attribute to the component host node either in a template or via a host binding. diff --git a/adev-es/src/content/reference/errors/NG0504.md b/adev-es/src/content/reference/errors/NG0504.md index b45b1c3..10cfa86 100644 --- a/adev-es/src/content/reference/errors/NG0504.md +++ b/adev-es/src/content/reference/errors/NG0504.md @@ -1,14 +1,14 @@ # Skip hydration flag is applied to an invalid node -This error occurs when the `ngSkipHydration` attribute was added to an inappropriate DOM node. The `ngSkipHydration` attribute can only be applied to component host nodes either directly in the template or via a host binding. It cannot be applied to other DOM nodes and will have no effect if done so other than causing this error. +Este error ocurre cuando el atributo `ngSkipHydration` se agregó a un nodo DOM inapropiado. El atributo `ngSkipHydration` solo puede aplicarse a nodos host de componentes, ya sea directamente en la plantilla o mediante un host binding. No puede aplicarse a otros nodos DOM y no tendrá ningún efecto si se hace así, salvo causar este error. -More information about hydration can be found in [this guide](guide/hydration). +Puedes encontrar más información sobre la hidratación en [esta guía](guide/hydration). -The following examples will trigger the error. +Los siguientes ejemplos activarán el error. -## Example 1 +## Ejemplo 1 -In this example, the `ngSkipHydration` attribute is applied to a `
` using host bindings of a directive. Since the `
` doesn't act as a component host node, Angular will throw an error. +En este ejemplo, el atributo `ngSkipHydration` se aplica a un `
` usando host bindings de una directiva. Dado que el `
` no actúa como un nodo host de componente, Angular lanzará un error. ```typescript @Directive({ @@ -29,10 +29,10 @@ class SimpleComponent { } ``` -## Example 2 +## Ejemplo 2 -In this example, the `ngSkipHydration` is applied to a `
` as an attribute via a template. -Since the `
` doesn't act as a component host node, Angular will throw an error. +En este ejemplo, `ngSkipHydration` se aplica a un `
` como atributo mediante una plantilla. +Dado que el `
` no actúa como un nodo host de componente, Angular lanzará un error. ```typescript @Component({ @@ -45,6 +45,6 @@ class SimpleComponent { } ``` -## Debugging the error +## Depurando el error -Remove the `ngSkipHydration` attribute from any invalid DOM nodes. Alternatively, move the `ngSkipHydration` attribute to the component host node either in a template or via a host binding. +Elimina el atributo `ngSkipHydration` de cualquier nodo DOM inválido. Alternativamente, mueve el atributo `ngSkipHydration` al nodo host del componente, ya sea en una plantilla o mediante un host binding. diff --git a/adev-es/src/content/reference/errors/NG0505.en.md b/adev-es/src/content/reference/errors/NG0505.en.md new file mode 100644 index 0000000..c8a645a --- /dev/null +++ b/adev-es/src/content/reference/errors/NG0505.en.md @@ -0,0 +1,24 @@ +# No hydration info in server response + +This error occurs when hydration is enabled on the client, but the server response +doesn't contain special serialized information about the application that hydration +logic relies on. + +This can happen when the `provideClientHydration()` function is included in the client +part of the application configuration, but is missing in the server part of the configuration. + +In applications with the default project structure (generated by the `ng new`), +the `provideClientHydration()` call is added either into the `providers` array of +the main `AppModule` (which is imported into the server module) or into a set of +providers that are included into both client and server configurations. + +If you have a custom setup where client and server configuration are independent +and do not share common set of providers, make sure that the `provideClientHydration()` +is also included into the set of providers used to bootstrap an application on the server. + +More information about hydration can be found in [this guide](guide/hydration). + +## Debugging the error + +Verify that the `provideClientHydration()` call is included into a set of providers +that is used to bootstrap an application on the server. diff --git a/adev-es/src/content/reference/errors/NG0505.md b/adev-es/src/content/reference/errors/NG0505.md index c8a645a..94631e8 100644 --- a/adev-es/src/content/reference/errors/NG0505.md +++ b/adev-es/src/content/reference/errors/NG0505.md @@ -1,24 +1,15 @@ # No hydration info in server response -This error occurs when hydration is enabled on the client, but the server response -doesn't contain special serialized information about the application that hydration -logic relies on. +Este error ocurre cuando la hidratación está habilitada en el cliente, pero la respuesta del servidor no contiene la información especial serializada sobre la aplicación en la que se basa la lógica de hidratación. -This can happen when the `provideClientHydration()` function is included in the client -part of the application configuration, but is missing in the server part of the configuration. +Esto puede suceder cuando la función `provideClientHydration()` está incluida en la parte del cliente de la configuración de la aplicación, pero está ausente en la parte del servidor de la configuración. -In applications with the default project structure (generated by the `ng new`), -the `provideClientHydration()` call is added either into the `providers` array of -the main `AppModule` (which is imported into the server module) or into a set of -providers that are included into both client and server configurations. +En aplicaciones con la estructura de proyecto predeterminada (generada por `ng new`), la llamada a `provideClientHydration()` se agrega ya sea en el array `providers` del `AppModule` principal (que se importa en el módulo del servidor) o en un conjunto de proveedores que se incluyen tanto en las configuraciones del cliente como del servidor. -If you have a custom setup where client and server configuration are independent -and do not share common set of providers, make sure that the `provideClientHydration()` -is also included into the set of providers used to bootstrap an application on the server. +Si tienes una configuración personalizada donde las configuraciones del cliente y el servidor son independientes y no comparten un conjunto común de proveedores, asegúrate de que `provideClientHydration()` también esté incluido en el conjunto de proveedores usados para hacer el bootstrap de la aplicación en el servidor. -More information about hydration can be found in [this guide](guide/hydration). +Puedes encontrar más información sobre la hidratación en [esta guía](guide/hydration). -## Debugging the error +## Depurando el error -Verify that the `provideClientHydration()` call is included into a set of providers -that is used to bootstrap an application on the server. +Verifica que la llamada a `provideClientHydration()` esté incluida en el conjunto de proveedores que se usa para hacer el bootstrap de la aplicación en el servidor. diff --git a/adev-es/src/content/reference/errors/NG0506.en.md b/adev-es/src/content/reference/errors/NG0506.en.md new file mode 100644 index 0000000..9c3760c --- /dev/null +++ b/adev-es/src/content/reference/errors/NG0506.en.md @@ -0,0 +1,80 @@ +# Application remains unstable + +This warning only appears in the browser during the hydration process when it's enabled on the client but the application remains unstable for an extended period of time (over 10 seconds). + +Typically that happens when there are some pending microtasks or macrotasks on a page. + +Angular Hydration relies on a signal from `ApplicationRef.isStable` when it becomes stable inside an application: + +- during the server-side rendering (SSR) to start the serialization process +- in a browser this signal is used to start the post-hydration cleanup to remove DOM nodes that remained unclaimed + +This warning is displayed when `ApplicationRef.isStable` does not emit `true` within 10 seconds. If this behavior is intentional and your application stabilizes later, you could choose to ignore this warning. + +## Applications that use zone.js + +Applications that use zone.js may have various factors contributing to delays in stability. These may include pending HTTP requests, timers (`setInterval`, `setTimeout`) or some logic that continuously invokes `requestAnimationFrame`. + +### Macrotasks + +Macrotasks include functions like `setInterval`, `setTimeout`, `requestAnimationFrame`, etc. +If one of these functions is called during the initialization phase of the application or in bootstrapped components, it may delay the moment when the application becomes stable. + +```typescript +@Component({ + selector: 'app', + template: ``, +}) +class SimpleComponent { + constructor() { + setInterval(() => { ... }, 1000) + + // or + + setTimeout(() => { ... }, 10_000) + } +} +``` + +If these functions must be called during the initialization phase, invoking them outside the Angular zone resolves the problem: + +```typescript +class SimpleComponent { + constructor() { + const ngZone = inject(NgZone); + + ngZone.runOutsideAngular(() => { + setInterval(() => {}, 1000); + }); + } +} +``` + +### Third-party libraries + +Some third-party libraries can also produce long-running asynchronous tasks, which may delay application stability. The recommendation is to invoke relevant library code outside of the zone as described above. + +### Running code after an application becomes stable + +You can run a code that sets up asynchronous tasks once an application becomes stable: + +```typescript +class SimpleComponent { + constructor() { + const applicationRef = inject(ApplicationRef); + + applicationRef.isStable.pipe( first((isStable) => isStable) ).subscribe(() => { + // Note that we don't need to use `runOutsideAngular` because `isStable` + // emits events outside of the Angular zone when it's truthy (falsy values + // are emitted inside the Angular zone). + setTimeout(() => { ... }); + }); + } +} +``` + +## Zoneless applications + +In zoneless scenarios, stability might be delayed by an application code inside of an `effect` running in an infinite loop (potentially because signals used in effect functions keep changing) or a pending HTTP request. + +Developers may also explicitly contribute to indicating the application's stability by using the [`PendingTasks`](/api/core/PendingTasks) service. If you use the mentioned APIs in your application, make sure you invoke a function to mark the task as completed. diff --git a/adev-es/src/content/reference/errors/NG0506.md b/adev-es/src/content/reference/errors/NG0506.md index 9c3760c..dd4b165 100644 --- a/adev-es/src/content/reference/errors/NG0506.md +++ b/adev-es/src/content/reference/errors/NG0506.md @@ -1,24 +1,24 @@ # Application remains unstable -This warning only appears in the browser during the hydration process when it's enabled on the client but the application remains unstable for an extended period of time (over 10 seconds). +Esta advertencia solo aparece en el navegador durante el proceso de hidratación cuando está habilitado en el cliente, pero la aplicación permanece inestable durante un período prolongado (más de 10 segundos). -Typically that happens when there are some pending microtasks or macrotasks on a page. +Típicamente esto ocurre cuando hay algunas microtareas o macrotareas pendientes en la página. -Angular Hydration relies on a signal from `ApplicationRef.isStable` when it becomes stable inside an application: +La hidratación de Angular depende de una señal de `ApplicationRef.isStable` cuando se vuelve estable dentro de una aplicación: -- during the server-side rendering (SSR) to start the serialization process -- in a browser this signal is used to start the post-hydration cleanup to remove DOM nodes that remained unclaimed +- durante la renderización del lado del servidor (SSR) para iniciar el proceso de serialización +- en el navegador, esta señal se usa para iniciar la limpieza posterior a la hidratación y eliminar los nodos DOM que quedaron sin reclamar -This warning is displayed when `ApplicationRef.isStable` does not emit `true` within 10 seconds. If this behavior is intentional and your application stabilizes later, you could choose to ignore this warning. +Esta advertencia se muestra cuando `ApplicationRef.isStable` no emite `true` dentro de 10 segundos. Si este comportamiento es intencional y tu aplicación se estabiliza más tarde, puedes optar por ignorar esta advertencia. -## Applications that use zone.js +## Aplicaciones que usan zone.js -Applications that use zone.js may have various factors contributing to delays in stability. These may include pending HTTP requests, timers (`setInterval`, `setTimeout`) or some logic that continuously invokes `requestAnimationFrame`. +Las aplicaciones que usan zone.js pueden tener varios factores que contribuyen a retrasos en la estabilidad. Estos pueden incluir peticiones HTTP pendientes, temporizadores (`setInterval`, `setTimeout`) o alguna lógica que invoca continuamente `requestAnimationFrame`. -### Macrotasks +### Macrotareas -Macrotasks include functions like `setInterval`, `setTimeout`, `requestAnimationFrame`, etc. -If one of these functions is called during the initialization phase of the application or in bootstrapped components, it may delay the moment when the application becomes stable. +Las macrotareas incluyen funciones como `setInterval`, `setTimeout`, `requestAnimationFrame`, etc. +Si alguna de estas funciones se llama durante la fase de inicialización de la aplicación o en los componentes en bootstrap, puede retrasar el momento en que la aplicación se vuelve estable. ```typescript @Component({ @@ -29,14 +29,14 @@ class SimpleComponent { constructor() { setInterval(() => { ... }, 1000) - // or + // o setTimeout(() => { ... }, 10_000) } } ``` -If these functions must be called during the initialization phase, invoking them outside the Angular zone resolves the problem: +Si estas funciones deben llamarse durante la fase de inicialización, invocarlas fuera de la zona de Angular resuelve el problema: ```typescript class SimpleComponent { @@ -50,13 +50,13 @@ class SimpleComponent { } ``` -### Third-party libraries +### Librerías de terceros -Some third-party libraries can also produce long-running asynchronous tasks, which may delay application stability. The recommendation is to invoke relevant library code outside of the zone as described above. +Algunas librerías de terceros también pueden producir tareas asíncronas de larga duración, lo que puede retrasar la estabilidad de la aplicación. La recomendación es invocar el código relevante de la librería fuera de la zona como se describió anteriormente. -### Running code after an application becomes stable +### Ejecutar código después de que una aplicación se vuelva estable -You can run a code that sets up asynchronous tasks once an application becomes stable: +Puedes ejecutar código que configure tareas asíncronas una vez que la aplicación se vuelva estable: ```typescript class SimpleComponent { @@ -64,17 +64,17 @@ class SimpleComponent { const applicationRef = inject(ApplicationRef); applicationRef.isStable.pipe( first((isStable) => isStable) ).subscribe(() => { - // Note that we don't need to use `runOutsideAngular` because `isStable` - // emits events outside of the Angular zone when it's truthy (falsy values - // are emitted inside the Angular zone). + // Ten en cuenta que no necesitamos usar `runOutsideAngular` porque `isStable` + // emite eventos fuera de la zona de Angular cuando es verdadero (los valores falsos + // se emiten dentro de la zona de Angular). setTimeout(() => { ... }); }); } } ``` -## Zoneless applications +## Aplicaciones sin zonas (zoneless) -In zoneless scenarios, stability might be delayed by an application code inside of an `effect` running in an infinite loop (potentially because signals used in effect functions keep changing) or a pending HTTP request. +En escenarios sin zonas, la estabilidad puede retrasarse por código de la aplicación dentro de un `effect` que se ejecuta en un bucle infinito (potencialmente porque los signals usados en las funciones del efecto siguen cambiando) o por una petición HTTP pendiente. -Developers may also explicitly contribute to indicating the application's stability by using the [`PendingTasks`](/api/core/PendingTasks) service. If you use the mentioned APIs in your application, make sure you invoke a function to mark the task as completed. +Los desarrolladores también pueden contribuir explícitamente a indicar la estabilidad de la aplicación usando el servicio [`PendingTasks`](/api/core/PendingTasks). Si usas las APIs mencionadas en tu aplicación, asegúrate de invocar la función para marcar la tarea como completada. diff --git a/adev-es/src/content/reference/errors/NG0507.en.md b/adev-es/src/content/reference/errors/NG0507.en.md new file mode 100644 index 0000000..6ee4fc1 --- /dev/null +++ b/adev-es/src/content/reference/errors/NG0507.en.md @@ -0,0 +1,10 @@ +# HTML content was altered after server-side rendering + +Angular throws this error when it detects that the content generated by server-side rendering (SSR) was altered after the rendering. The process of hydration relies on the content to be untouched after SSR, which also includes whitespaces and comment nodes. Those whitespaces and comment nodes must be retained in the HTML generated by the SSR process. Learn more in the Hydration guide. + +## Debugging the error + +Typically this happens in the following cases: + +Some CDN providers have a built-in feature to remove whitespaces and comment nodes from HTML as an optimization. Please verify if there is such an option in CDN configuration and turn it off. +If you use custom post-processing of HTML generated by SSR (as a build step), make sure that this process doesn't remove whitespaces and comment nodes. diff --git a/adev-es/src/content/reference/errors/NG0507.md b/adev-es/src/content/reference/errors/NG0507.md index 6ee4fc1..a668a30 100644 --- a/adev-es/src/content/reference/errors/NG0507.md +++ b/adev-es/src/content/reference/errors/NG0507.md @@ -1,10 +1,10 @@ # HTML content was altered after server-side rendering -Angular throws this error when it detects that the content generated by server-side rendering (SSR) was altered after the rendering. The process of hydration relies on the content to be untouched after SSR, which also includes whitespaces and comment nodes. Those whitespaces and comment nodes must be retained in the HTML generated by the SSR process. Learn more in the Hydration guide. +Angular lanza este error cuando detecta que el contenido generado por la renderización del lado del servidor (SSR) fue alterado después del renderizado. El proceso de hidratación depende de que el contenido no se modifique después del SSR, lo que incluye los espacios en blanco y los nodos de comentarios. Esos espacios en blanco y nodos de comentarios deben conservarse en el HTML generado por el proceso de SSR. Aprende más en la guía de Hidratación. -## Debugging the error +## Depurando el error -Typically this happens in the following cases: +Típicamente esto sucede en los siguientes casos: -Some CDN providers have a built-in feature to remove whitespaces and comment nodes from HTML as an optimization. Please verify if there is such an option in CDN configuration and turn it off. -If you use custom post-processing of HTML generated by SSR (as a build step), make sure that this process doesn't remove whitespaces and comment nodes. +Algunos proveedores de CDN tienen una función integrada para eliminar espacios en blanco y nodos de comentarios del HTML como optimización. Verifica si existe tal opción en la configuración de CDN y desactívala. +Si usas post-procesamiento personalizado del HTML generado por SSR (como paso de compilación), asegúrate de que este proceso no elimine los espacios en blanco y los nodos de comentarios. diff --git a/adev-es/src/content/reference/errors/NG05104.en.md b/adev-es/src/content/reference/errors/NG05104.en.md new file mode 100644 index 0000000..a651faa --- /dev/null +++ b/adev-es/src/content/reference/errors/NG05104.en.md @@ -0,0 +1,31 @@ +# Root element was not found + +Bootstrapped components are defined in the `bootstrap` property of an `@NgModule` decorator or as the first parameter of `bootstrapApplication` for standalone components. + +This error happens when Angular tries to bootstrap one of these components but cannot find its corresponding node in the DOM. + +## Debugging the error + +This issue occurs when the selector mismatches the tag + +```typescript +@Component({ + selector: 'my-app', + ... +}) +export class AppComponent {} +``` + +```angular-html + + + +``` + +Replace the tag with the correct one: + +```angular-html + + + +``` diff --git a/adev-es/src/content/reference/errors/NG05104.md b/adev-es/src/content/reference/errors/NG05104.md index a651faa..7c2340f 100644 --- a/adev-es/src/content/reference/errors/NG05104.md +++ b/adev-es/src/content/reference/errors/NG05104.md @@ -1,12 +1,12 @@ # Root element was not found -Bootstrapped components are defined in the `bootstrap` property of an `@NgModule` decorator or as the first parameter of `bootstrapApplication` for standalone components. +Los componentes en bootstrap se definen en la propiedad `bootstrap` de un decorador `@NgModule` o como el primer parámetro de `bootstrapApplication` para componentes standalone. -This error happens when Angular tries to bootstrap one of these components but cannot find its corresponding node in the DOM. +Este error ocurre cuando Angular intenta hacer el bootstrap de uno de estos componentes pero no puede encontrar su nodo correspondiente en el DOM. -## Debugging the error +## Depurando el error -This issue occurs when the selector mismatches the tag +Este problema ocurre cuando el selector no coincide con la etiqueta ```typescript @Component({ @@ -18,11 +18,11 @@ export class AppComponent {} ```angular-html - + ``` -Replace the tag with the correct one: +Reemplaza la etiqueta con la correcta: ```angular-html diff --git a/adev-es/src/content/reference/errors/NG0602.en.md b/adev-es/src/content/reference/errors/NG0602.en.md new file mode 100644 index 0000000..e20cea5 --- /dev/null +++ b/adev-es/src/content/reference/errors/NG0602.en.md @@ -0,0 +1,62 @@ +# Disallowed function call inside reactive context + +A function that is not allowed to run inside a reactive context was called from within a reactive context. + +For example, an `effect` cannot be scheduled from within a `computed` or an actively executing effect. +Avoid calling functions like `effect` as part of template expressions, as those execute in their own reactive context. + +Computed expressions are expected to be pure. +Pure means that expression do not trigger any side effects. +Side effects are operations like scheduling `afterNextRender`/`afterEveryRender`, creating a new `effect`, or subscribing to observables. + +Some operations are explicitly banned inside reactive contexts in order to avoid common pitfalls. +As an example, using `afterNextRender`/`afterEveryRender` inside a `computed` will schedule new render hooks every time the computed expression evaluates. +This is likely not intended and could degrade application performance. + +### Fixing the error + +This error guide is non-exhaustive. +It captures a few common scenarios and how to address the error. + +#### `afterNextRender`/`afterEveryRender` + +Move the call for `afterNextRender`/`afterEveryRender` outside of the reactive context. + +A good place to schedule the after render hook is in the component's class constructor. +Alternatively, use `untracked` to leave the reactive context and explicitly opt-out of this error. + +#### `effect` + +Move the call for `effect` outside of the reactive context. + +A good place to schedule an effect is in a `@Component`'s class constructor. + +#### `toSignal` + +Move the call for `toSignal` outside of the reactive context. + +```typescript +result = computed(() => { + const dataSignal = toSignal(dataObservable$); + return doSomething(dataSignal()); +}); +``` + +can be refactored into: + +```typescript +dataSignal = toSignal(dataObservable$); +result = computed(() => doSomething(dataSignal())); +``` + +Alternatively, if this is not possible, consider manually subscribing to the observable. + +As a last resort, use `untracked` to leave the reactive context. +Be careful as leaving the reactive context can result in signal reads to be ignored inside `untracked`. + +@debugging + +The error message mentions the function that was unexpectedly called. +Look for this function call in your application code. + +Alternatively, the stack trace in your browser will show where the function was invoked and where it's located. diff --git a/adev-es/src/content/reference/errors/NG0602.md b/adev-es/src/content/reference/errors/NG0602.md index e20cea5..6abbd05 100644 --- a/adev-es/src/content/reference/errors/NG0602.md +++ b/adev-es/src/content/reference/errors/NG0602.md @@ -1,39 +1,39 @@ # Disallowed function call inside reactive context -A function that is not allowed to run inside a reactive context was called from within a reactive context. +Se llamó a una función que no está permitida ejecutarse dentro de un contexto reactivo desde dentro de un contexto reactivo. -For example, an `effect` cannot be scheduled from within a `computed` or an actively executing effect. -Avoid calling functions like `effect` as part of template expressions, as those execute in their own reactive context. +Por ejemplo, un `effect` no puede programarse desde dentro de un `computed` o un efecto en ejecución activa. +Evita llamar a funciones como `effect` como parte de expresiones de plantilla, ya que estas se ejecutan en su propio contexto reactivo. -Computed expressions are expected to be pure. -Pure means that expression do not trigger any side effects. -Side effects are operations like scheduling `afterNextRender`/`afterEveryRender`, creating a new `effect`, or subscribing to observables. +Se espera que las expresiones computed sean puras. +Puro significa que las expresiones no disparan ningún efecto secundario. +Los efectos secundarios son operaciones como programar `afterNextRender`/`afterEveryRender`, crear un nuevo `effect`, o suscribirse a observables. -Some operations are explicitly banned inside reactive contexts in order to avoid common pitfalls. -As an example, using `afterNextRender`/`afterEveryRender` inside a `computed` will schedule new render hooks every time the computed expression evaluates. -This is likely not intended and could degrade application performance. +Algunas operaciones están explícitamente prohibidas dentro de los contextos reactivos para evitar errores comunes. +Por ejemplo, usar `afterNextRender`/`afterEveryRender` dentro de un `computed` programará nuevos hooks de renderizado cada vez que la expresión computed se evalúe. +Esto probablemente no sea intencional y podría degradar el rendimiento de la aplicación. -### Fixing the error +### Corrigiendo el error -This error guide is non-exhaustive. -It captures a few common scenarios and how to address the error. +Esta guía de error no es exhaustiva. +Captura algunos escenarios comunes y cómo abordar el error. #### `afterNextRender`/`afterEveryRender` -Move the call for `afterNextRender`/`afterEveryRender` outside of the reactive context. +Mueve la llamada a `afterNextRender`/`afterEveryRender` fuera del contexto reactivo. -A good place to schedule the after render hook is in the component's class constructor. -Alternatively, use `untracked` to leave the reactive context and explicitly opt-out of this error. +Un buen lugar para programar el hook de after render es en el constructor de la clase del componente. +Alternativamente, usa `untracked` para salir del contexto reactivo y desactivar explícitamente este error. #### `effect` -Move the call for `effect` outside of the reactive context. +Mueve la llamada a `effect` fuera del contexto reactivo. -A good place to schedule an effect is in a `@Component`'s class constructor. +Un buen lugar para programar un efecto es en el constructor de la clase de un `@Component`. #### `toSignal` -Move the call for `toSignal` outside of the reactive context. +Mueve la llamada a `toSignal` fuera del contexto reactivo. ```typescript result = computed(() => { @@ -42,21 +42,21 @@ result = computed(() => { }); ``` -can be refactored into: +puede refactorizarse a: ```typescript dataSignal = toSignal(dataObservable$); result = computed(() => doSomething(dataSignal())); ``` -Alternatively, if this is not possible, consider manually subscribing to the observable. +Alternativamente, si esto no es posible, considera suscribirse manualmente al observable. -As a last resort, use `untracked` to leave the reactive context. -Be careful as leaving the reactive context can result in signal reads to be ignored inside `untracked`. +Como último recurso, usa `untracked` para salir del contexto reactivo. +Ten cuidado, ya que salir del contexto reactivo puede resultar en que las lecturas de signals se ignoren dentro de `untracked`. @debugging -The error message mentions the function that was unexpectedly called. -Look for this function call in your application code. +El mensaje de error menciona la función que fue llamada inesperadamente. +Busca esta llamada de función en el código de tu aplicación. -Alternatively, the stack trace in your browser will show where the function was invoked and where it's located. +Alternativamente, la traza de la pila en tu navegador mostrará dónde se invocó la función y dónde está ubicada. diff --git a/adev-es/src/content/reference/errors/NG0750.en.md b/adev-es/src/content/reference/errors/NG0750.en.md new file mode 100644 index 0000000..a398929 --- /dev/null +++ b/adev-es/src/content/reference/errors/NG0750.en.md @@ -0,0 +1,7 @@ +# @defer dependencies failed to load + +This error occurs when loading dependencies for a `@defer` block fails (typically due to poor network conditions) and no `@error` block has been configured to handle the failure state. Having no `@error` block in this scenario may create a poor user experience. + +## Debugging the error + +Verify that you added `@error` blocks to your `@defer` blocks to handle failure states. diff --git a/adev-es/src/content/reference/errors/NG0750.md b/adev-es/src/content/reference/errors/NG0750.md index a398929..0b8f491 100644 --- a/adev-es/src/content/reference/errors/NG0750.md +++ b/adev-es/src/content/reference/errors/NG0750.md @@ -1,7 +1,7 @@ # @defer dependencies failed to load -This error occurs when loading dependencies for a `@defer` block fails (typically due to poor network conditions) and no `@error` block has been configured to handle the failure state. Having no `@error` block in this scenario may create a poor user experience. +Este error ocurre cuando la carga de dependencias para un bloque `@defer` falla (típicamente debido a malas condiciones de red) y no se ha configurado un bloque `@error` para manejar el estado de fallo. No tener un bloque `@error` en este escenario puede crear una mala experiencia de usuario. -## Debugging the error +## Depurando el error -Verify that you added `@error` blocks to your `@defer` blocks to handle failure states. +Verifica que hayas agregado bloques `@error` a tus bloques `@defer` para manejar los estados de fallo. diff --git a/adev-es/src/content/reference/errors/NG0751.en.md b/adev-es/src/content/reference/errors/NG0751.en.md new file mode 100644 index 0000000..08e52de --- /dev/null +++ b/adev-es/src/content/reference/errors/NG0751.en.md @@ -0,0 +1,13 @@ +# @defer behavior when HMR is enabled + +Hot Module Replacement (HMR) is a technique used by development servers to avoid reloading the entire page when only part of an application is changed. + +When the HMR is enabled in Angular, all `@defer` block dependencies are loaded +eagerly, instead of waiting for configured trigger conditions (both for client-only and incremental hydration triggers). This is needed +for the HMR to function properly, replacing components in an application at runtime +without the need to reload the entire page. NOTE: the actual rendering of defer +blocks respects trigger conditions in the HMR mode. + +If you want to test `@defer` block behavior in development mode and ensure that +the necessary dependencies are loaded when a triggering condition is met, you can +disable the HMR mode as described in [`this document`](/tools/cli/build-system-migration#hot-module-replacement). diff --git a/adev-es/src/content/reference/errors/NG0751.md b/adev-es/src/content/reference/errors/NG0751.md index 08e52de..8124928 100644 --- a/adev-es/src/content/reference/errors/NG0751.md +++ b/adev-es/src/content/reference/errors/NG0751.md @@ -1,13 +1,7 @@ # @defer behavior when HMR is enabled -Hot Module Replacement (HMR) is a technique used by development servers to avoid reloading the entire page when only part of an application is changed. +Hot Module Replacement (HMR) es una técnica utilizada por los servidores de desarrollo para evitar recargar la página completa cuando solo se cambia una parte de la aplicación. -When the HMR is enabled in Angular, all `@defer` block dependencies are loaded -eagerly, instead of waiting for configured trigger conditions (both for client-only and incremental hydration triggers). This is needed -for the HMR to function properly, replacing components in an application at runtime -without the need to reload the entire page. NOTE: the actual rendering of defer -blocks respects trigger conditions in the HMR mode. +Cuando HMR está habilitado en Angular, todas las dependencias de los bloques `@defer` se cargan de forma eager, en lugar de esperar las condiciones de trigger configuradas (tanto para triggers solo del cliente como para triggers de hidratación incremental). Esto es necesario para que HMR funcione correctamente, reemplazando componentes en una aplicación en tiempo de ejecución sin necesidad de recargar la página completa. NOTA: el renderizado real de los bloques defer respeta las condiciones de trigger en el modo HMR. -If you want to test `@defer` block behavior in development mode and ensure that -the necessary dependencies are loaded when a triggering condition is met, you can -disable the HMR mode as described in [`this document`](/tools/cli/build-system-migration#hot-module-replacement). +Si quieres probar el comportamiento de los bloques `@defer` en modo de desarrollo y asegurarte de que las dependencias necesarias se carguen cuando se cumple una condición de trigger, puedes deshabilitar el modo HMR como se describe en [`este documento`](/tools/cli/build-system-migration#hot-module-replacement). diff --git a/adev-es/src/content/reference/errors/NG0910.en.md b/adev-es/src/content/reference/errors/NG0910.en.md new file mode 100644 index 0000000..8345f7c --- /dev/null +++ b/adev-es/src/content/reference/errors/NG0910.en.md @@ -0,0 +1,61 @@ +# Unsafe bindings on an iframe element + +You see this error when Angular detects an attribute binding or a property binding on an ` +``` + +or when it's an attribute bindings: + +```angular-html + +``` + +Also, the error is thrown when a similar pattern is used in Directive's host bindings: + +```typescript +@Directive({ + selector: 'iframe', + host: { + '[sandbox]': `'allow-scripts'`, + '[attr.sandbox]': `'allow-scripts'`, + } +}) +class IframeDirective {} +``` + +## Debugging the error + +The error message includes the name of the component with the template where +an ` +``` + +If you need to have different values for these attributes (depending on various conditions), +you can use an `*ngIf` or an `*ngSwitch` on an ` + + +``` diff --git a/adev-es/src/content/reference/errors/NG0910.md b/adev-es/src/content/reference/errors/NG0910.md index 8345f7c..c1f32de 100644 --- a/adev-es/src/content/reference/errors/NG0910.md +++ b/adev-es/src/content/reference/errors/NG0910.md @@ -1,6 +1,6 @@ # Unsafe bindings on an iframe element -You see this error when Angular detects an attribute binding or a property binding on an ` ``` -or when it's an attribute bindings: +o cuando es un enlace de atributo: ```angular-html ``` -Also, the error is thrown when a similar pattern is used in Directive's host bindings: +También se lanza el error cuando se usa un patrón similar en los host bindings de una directiva: ```typescript @Directive({ @@ -40,19 +39,18 @@ Also, the error is thrown when a similar pattern is used in Directive's host bin class IframeDirective {} ``` -## Debugging the error +## Depurando el error -The error message includes the name of the component with the template where -an ` ``` -If you need to have different values for these attributes (depending on various conditions), -you can use an `*ngIf` or an `*ngSwitch` on an ` diff --git a/adev-es/src/content/reference/errors/NG0912.en.md b/adev-es/src/content/reference/errors/NG0912.en.md new file mode 100644 index 0000000..24ca46a --- /dev/null +++ b/adev-es/src/content/reference/errors/NG0912.en.md @@ -0,0 +1,55 @@ +# Component ID generation collision + +When creating components, Angular generates a unique component ID for each component. This is generated using the Angular component metadata, including but not limited: selectors, the number of host bindings, class property names, view and content queries. When two components metadata are identical (often times sharing the same selector), an ID generation collision will occur. + +Component IDs are used in Angular internally: + +- for extra annotations of DOM nodes for style encapsulation +- during [hydration](guide/hydration) to restore an application state after [server-side rendering](guide/ssr). + +To avoid issues that might be caused by the component ID collision, it's recommended to resolve them as described below. + +## Example of a Component ID collision + +```typescript +@Component({ + selector: 'my-component', + template: 'complex-template', +}) +class SomeComponent {} + +@Component({ + selector: 'my-component', + template: 'empty-template', +}) +class SomeMockedComponent {} +``` + +Having these two components defined will trigger an ID generation collision and during development a warning will be displayed. + +## Debugging the error + +The warning message includes the class name of the two components whose IDs are colliding. + +The problem can be resolved using one of the solutions below: + +1. Change the selector of one of the two components. For example by using a pseudo-selector with no effect like `:not()` and a different tag name. + +```typescript +@Component({ + selector: 'my-component:not(p)', + template: 'empty-template', +}) +class SomeMockedComponent {} +``` + +1. Add an extra host attribute to one of the components. + +```typescript +@Component({ + selector: 'my-component', + template: 'complex-template', + host: {'some-binding': 'some-value'}, +}) +class SomeComponent {} +``` diff --git a/adev-es/src/content/reference/errors/NG0912.md b/adev-es/src/content/reference/errors/NG0912.md index 24ca46a..eedbed3 100644 --- a/adev-es/src/content/reference/errors/NG0912.md +++ b/adev-es/src/content/reference/errors/NG0912.md @@ -1,15 +1,15 @@ # Component ID generation collision -When creating components, Angular generates a unique component ID for each component. This is generated using the Angular component metadata, including but not limited: selectors, the number of host bindings, class property names, view and content queries. When two components metadata are identical (often times sharing the same selector), an ID generation collision will occur. +Al crear componentes, Angular genera un ID de componente único para cada uno. Este se genera usando los metadatos del componente de Angular, incluyendo pero no limitado a: selectores, el número de host bindings, nombres de propiedades de clase, consultas de vista y de contenido. Cuando los metadatos de dos componentes son idénticos (frecuentemente cuando comparten el mismo selector), ocurrirá una colisión en la generación de ID. -Component IDs are used in Angular internally: +Los IDs de componente son usados internamente por Angular: -- for extra annotations of DOM nodes for style encapsulation -- during [hydration](guide/hydration) to restore an application state after [server-side rendering](guide/ssr). +- para anotaciones adicionales de nodos DOM para la encapsulación de estilos +- durante la [hidratación](guide/hydration) para restaurar el estado de una aplicación después de la [renderización del lado del servidor](guide/ssr). -To avoid issues that might be caused by the component ID collision, it's recommended to resolve them as described below. +Para evitar problemas que podrían ser causados por la colisión de ID de componente, se recomienda resolverlos como se describe a continuación. -## Example of a Component ID collision +## Ejemplo de colisión de ID de componente ```typescript @Component({ @@ -25,15 +25,15 @@ class SomeComponent {} class SomeMockedComponent {} ``` -Having these two components defined will trigger an ID generation collision and during development a warning will be displayed. +Tener estos dos componentes definidos activará una colisión en la generación de ID y durante el desarrollo se mostrará una advertencia. -## Debugging the error +## Depurando el error -The warning message includes the class name of the two components whose IDs are colliding. +El mensaje de advertencia incluye el nombre de clase de los dos componentes cuyos IDs están colisionando. -The problem can be resolved using one of the solutions below: +El problema puede resolverse usando una de las siguientes soluciones: -1. Change the selector of one of the two components. For example by using a pseudo-selector with no effect like `:not()` and a different tag name. +1. Cambia el selector de uno de los dos componentes. Por ejemplo, usando un pseudo-selector sin efecto como `:not()` y un nombre de etiqueta diferente. ```typescript @Component({ @@ -43,7 +43,7 @@ The problem can be resolved using one of the solutions below: class SomeMockedComponent {} ``` -1. Add an extra host attribute to one of the components. +1. Agrega un atributo host adicional a uno de los componentes. ```typescript @Component({ diff --git a/adev-es/src/content/reference/errors/NG0913.en.md b/adev-es/src/content/reference/errors/NG0913.en.md new file mode 100644 index 0000000..b118de4 --- /dev/null +++ b/adev-es/src/content/reference/errors/NG0913.en.md @@ -0,0 +1,39 @@ +# Runtime Performance Warnings + +### Oversized images + +When images are loaded, the **intrinsic size** of the downloaded file is checked against the actual size of the image on the page. The actual size is calculated using the **rendered size** of the image with CSS applied, multiplied by the [pixel device ratio](https://web.dev/codelab-density-descriptors/#pixel-density). If the downloaded image is much larger (more than 1200px too large in either dimension), this warning is triggered. Downloading oversized images can slow down page loading and have a negative effect on [Core Web Vitals](https://web.dev/vitals/). + +### Lazy-loaded LCP element + +The largest contentful element on a page during load is considered the "LCP Element", which relates to [Largest Contentful Paint](https://web.dev/lcp/), one of the Core Web Vitals. Lazy loading an LCP element will have a strong negative effect on page performance. With this strategy, the browser has to complete layout calculations to determine whether the element is in the viewport before starting the image download. As a result, a warning is triggered when Angular detects that the LCP element has been given the `loading="lazy"` attribute. + +@debugging +Use the image URL provided in the console warning to find the `` element in question. + +### Ways to fix oversized images + +- Use a smaller source image +- Add a [`srcset`](https://web.dev/learn/design/responsive-images/#responsive-images-with-srcset) if multiple sizes are needed for different layouts. +- Switch to use Angular's built-in image directive ([`NgOptimizedImage`](https://angular.dev/api/common/NgOptimizedImage)), which generates [srcsets automatically](https://angular.dev/guide/image-optimization#request-images-at-the-correct-size-with-automatic-srcset). + +### Ways to fix lazy-loaded LCP element + +- Change the `loading` attribute to a different value such as `"eager"`. +- Switch to use Angular's built-in image directive ([`NgOptimizedImage`](https://angular.dev/api/common/NgOptimizedImage)), which allows for easily [prioritizing LCP images](https://angular.dev/guide/image-optimization#mark-images-as-priority). + +### Disabling Image Performance Warnings + +Both warnings can be disabled individually, site-wide, using a provider at the root of your application: + +```typescript +providers: [ + { + provide: IMAGE_CONFIG, + useValue: { + disableImageSizeWarning: true, + disableImageLazyLoadWarning: true + } + }, +], +``` diff --git a/adev-es/src/content/reference/errors/NG0913.md b/adev-es/src/content/reference/errors/NG0913.md index b118de4..a053ec5 100644 --- a/adev-es/src/content/reference/errors/NG0913.md +++ b/adev-es/src/content/reference/errors/NG0913.md @@ -1,30 +1,30 @@ # Runtime Performance Warnings -### Oversized images +### Imágenes de tamaño excesivo -When images are loaded, the **intrinsic size** of the downloaded file is checked against the actual size of the image on the page. The actual size is calculated using the **rendered size** of the image with CSS applied, multiplied by the [pixel device ratio](https://web.dev/codelab-density-descriptors/#pixel-density). If the downloaded image is much larger (more than 1200px too large in either dimension), this warning is triggered. Downloading oversized images can slow down page loading and have a negative effect on [Core Web Vitals](https://web.dev/vitals/). +Cuando se cargan imágenes, el **tamaño intrínseco** del archivo descargado se compara con el tamaño real de la imagen en la página. El tamaño real se calcula usando el **tamaño renderizado** de la imagen con CSS aplicado, multiplicado por la [relación de píxeles del dispositivo](https://web.dev/codelab-density-descriptors/#pixel-density). Si la imagen descargada es mucho más grande (más de 1200px demasiado grande en cualquier dimensión), se activa esta advertencia. Descargar imágenes de tamaño excesivo puede ralentizar la carga de la página y tener un efecto negativo en los [Core Web Vitals](https://web.dev/vitals/). -### Lazy-loaded LCP element +### Elemento LCP cargado de forma diferida -The largest contentful element on a page during load is considered the "LCP Element", which relates to [Largest Contentful Paint](https://web.dev/lcp/), one of the Core Web Vitals. Lazy loading an LCP element will have a strong negative effect on page performance. With this strategy, the browser has to complete layout calculations to determine whether the element is in the viewport before starting the image download. As a result, a warning is triggered when Angular detects that the LCP element has been given the `loading="lazy"` attribute. +El elemento de contenido más grande en una página durante la carga se considera el "Elemento LCP", que se relaciona con [Largest Contentful Paint](https://web.dev/lcp/), uno de los Core Web Vitals. Cargar de forma diferida un elemento LCP tendrá un fuerte efecto negativo en el rendimiento de la página. Con esta estrategia, el navegador tiene que completar los cálculos de diseño para determinar si el elemento está en el viewport antes de comenzar la descarga de la imagen. Como resultado, se activa una advertencia cuando Angular detecta que el elemento LCP tiene el atributo `loading="lazy"`. @debugging -Use the image URL provided in the console warning to find the `` element in question. +Usa la URL de la imagen proporcionada en la advertencia de la consola para encontrar el elemento `` en cuestión. -### Ways to fix oversized images +### Formas de corregir imágenes de tamaño excesivo -- Use a smaller source image -- Add a [`srcset`](https://web.dev/learn/design/responsive-images/#responsive-images-with-srcset) if multiple sizes are needed for different layouts. -- Switch to use Angular's built-in image directive ([`NgOptimizedImage`](https://angular.dev/api/common/NgOptimizedImage)), which generates [srcsets automatically](https://angular.dev/guide/image-optimization#request-images-at-the-correct-size-with-automatic-srcset). +- Usa una imagen de origen más pequeña +- Agrega un [`srcset`](https://web.dev/learn/design/responsive-images/#responsive-images-with-srcset) si se necesitan múltiples tamaños para diferentes diseños. +- Cambia a usar la directiva de imagen integrada de Angular ([`NgOptimizedImage`](https://angular.dev/api/common/NgOptimizedImage)), que genera [srcsets automáticamente](https://angular.dev/guide/image-optimization#request-images-at-the-correct-size-with-automatic-srcset). -### Ways to fix lazy-loaded LCP element +### Formas de corregir el elemento LCP cargado de forma diferida -- Change the `loading` attribute to a different value such as `"eager"`. -- Switch to use Angular's built-in image directive ([`NgOptimizedImage`](https://angular.dev/api/common/NgOptimizedImage)), which allows for easily [prioritizing LCP images](https://angular.dev/guide/image-optimization#mark-images-as-priority). +- Cambia el atributo `loading` a un valor diferente como `"eager"`. +- Cambia a usar la directiva de imagen integrada de Angular ([`NgOptimizedImage`](https://angular.dev/api/common/NgOptimizedImage)), que permite [priorizar fácilmente las imágenes LCP](https://angular.dev/guide/image-optimization#mark-images-as-priority). -### Disabling Image Performance Warnings +### Desactivar las advertencias de rendimiento de imágenes -Both warnings can be disabled individually, site-wide, using a provider at the root of your application: +Ambas advertencias pueden desactivarse individualmente, en todo el sitio, usando un proveedor en la raíz de tu aplicación: ```typescript providers: [ diff --git a/adev-es/src/content/reference/errors/NG0950.en.md b/adev-es/src/content/reference/errors/NG0950.en.md new file mode 100644 index 0000000..fb8a7ef --- /dev/null +++ b/adev-es/src/content/reference/errors/NG0950.en.md @@ -0,0 +1,15 @@ +# Required input is accessed before a value is set. + +A required input was accessed but no value was bound. + +This can happen when a required input is accessed too early in your directive or component. +This is commonly happening when the input is read as part of class construction. + +Inputs are guaranteed to be available in the `ngOnInit` lifecycle hook and afterwards. + +## Fixing the error + +Access the required input in reactive contexts. +For example, in the template itself, inside a `computed`, or inside an effect. + +Alternatively, access the input inside the `ngOnInit` lifecycle hook, or later. diff --git a/adev-es/src/content/reference/errors/NG0950.md b/adev-es/src/content/reference/errors/NG0950.md index fb8a7ef..64f0b1e 100644 --- a/adev-es/src/content/reference/errors/NG0950.md +++ b/adev-es/src/content/reference/errors/NG0950.md @@ -1,15 +1,15 @@ # Required input is accessed before a value is set. -A required input was accessed but no value was bound. +Se accedió a una entrada requerida pero no se vinculó ningún valor. -This can happen when a required input is accessed too early in your directive or component. -This is commonly happening when the input is read as part of class construction. +Esto puede suceder cuando se accede a una entrada requerida demasiado pronto en tu directiva o componente. +Comúnmente ocurre cuando la entrada se lee como parte de la construcción de la clase. -Inputs are guaranteed to be available in the `ngOnInit` lifecycle hook and afterwards. +Las entradas tienen garantía de estar disponibles en el hook de ciclo de vida `ngOnInit` y posteriores. -## Fixing the error +## Corrigiendo el error -Access the required input in reactive contexts. -For example, in the template itself, inside a `computed`, or inside an effect. +Accede a la entrada requerida en contextos reactivos. +Por ejemplo, en la plantilla misma, dentro de un `computed`, o dentro de un efecto. -Alternatively, access the input inside the `ngOnInit` lifecycle hook, or later. +Alternativamente, accede a la entrada dentro del hook de ciclo de vida `ngOnInit`, o más tarde. diff --git a/adev-es/src/content/reference/errors/NG0951.en.md b/adev-es/src/content/reference/errors/NG0951.en.md new file mode 100644 index 0000000..88fa09b --- /dev/null +++ b/adev-es/src/content/reference/errors/NG0951.en.md @@ -0,0 +1,22 @@ +# Child query result is required but no value is available. + +Required child query (`contentChild.required` or `viewChild.required`) result was accessed before query results were calculated or query has no matches. + +This can happen in two distinct situations: + +- query results were accessed before a given query could collect results; +- a query was executed but didn't match any nodes and has no results as a consequence. + +Content queries and view queries each calculate their results at different points in time: + +- `contentChild` results are available after a _host_ view (template where a directive declaring a query is used) is created; +- `viewChild` results are available after a template of a component declaring a query is created. + +Accessing query results before they're available results in the error described on this page. Most notably, query results are _never_ available in a constructor of the component or directive declaring a query. + +## Fixing the error + +`contentChild` query results can be accessed in the `AfterContentChecked` lifecycle hook, or later. +`viewChild` query results can be accessed in the `AfterViewChecked` lifecycle hook, or later. + +Make sure that a required query matches at least one node and has results at all. You can verify this by accessing query results in the lifecycle hooks listed above. diff --git a/adev-es/src/content/reference/errors/NG0951.md b/adev-es/src/content/reference/errors/NG0951.md index 88fa09b..6f296a5 100644 --- a/adev-es/src/content/reference/errors/NG0951.md +++ b/adev-es/src/content/reference/errors/NG0951.md @@ -1,22 +1,22 @@ # Child query result is required but no value is available. -Required child query (`contentChild.required` or `viewChild.required`) result was accessed before query results were calculated or query has no matches. +El resultado de una consulta hija requerida (`contentChild.required` o `viewChild.required`) fue accedido antes de que los resultados de la consulta se calcularan, o la consulta no tiene coincidencias. -This can happen in two distinct situations: +Esto puede suceder en dos situaciones distintas: -- query results were accessed before a given query could collect results; -- a query was executed but didn't match any nodes and has no results as a consequence. +- se accedió a los resultados de la consulta antes de que la consulta pudiera recopilar resultados; +- una consulta se ejecutó pero no coincidió con ningún nodo y, en consecuencia, no tiene resultados. -Content queries and view queries each calculate their results at different points in time: +Las consultas de contenido y las consultas de vista calculan sus resultados en diferentes momentos: -- `contentChild` results are available after a _host_ view (template where a directive declaring a query is used) is created; -- `viewChild` results are available after a template of a component declaring a query is created. +- los resultados de `contentChild` están disponibles después de que se crea la vista _host_ (plantilla donde se usa la directiva que declara la consulta); +- los resultados de `viewChild` están disponibles después de que se crea la plantilla del componente que declara la consulta. -Accessing query results before they're available results in the error described on this page. Most notably, query results are _never_ available in a constructor of the component or directive declaring a query. +Acceder a los resultados de la consulta antes de que estén disponibles genera el error descrito en esta página. En particular, los resultados de la consulta _nunca_ están disponibles en el constructor del componente o directiva que declara la consulta. -## Fixing the error +## Corrigiendo el error -`contentChild` query results can be accessed in the `AfterContentChecked` lifecycle hook, or later. -`viewChild` query results can be accessed in the `AfterViewChecked` lifecycle hook, or later. +Los resultados de la consulta `contentChild` se pueden acceder en el hook de ciclo de vida `AfterContentChecked`, o más tarde. +Los resultados de la consulta `viewChild` se pueden acceder en el hook de ciclo de vida `AfterViewChecked`, o más tarde. -Make sure that a required query matches at least one node and has results at all. You can verify this by accessing query results in the lifecycle hooks listed above. +Asegúrate de que una consulta requerida coincida con al menos un nodo y tenga resultados. Puedes verificarlo accediendo a los resultados de la consulta en los hooks de ciclo de vida listados anteriormente. diff --git a/adev-es/src/content/reference/errors/NG0955.en.md b/adev-es/src/content/reference/errors/NG0955.en.md new file mode 100644 index 0000000..c74dae0 --- /dev/null +++ b/adev-es/src/content/reference/errors/NG0955.en.md @@ -0,0 +1,31 @@ +# Track expression resulted in duplicated keys for a given collection. + +A track expression specified in the `@for` loop evaluated to duplicated keys for a given collection, ex.: + +```typescript +@Component({ + template: `@for (item of items; track item.value) {{{item.value}}}`, +}) +class TestComponent { + items = [{key: 1, value: 'a'}, {key: 2, value: 'b'}, {key: 3, value: 'a'}]; +} +``` + +In the provided example the `item.key` tracking expression will find two duplicate keys `a` (at index 0 and 2). + +Duplicate keys are problematic from the correctness point of view: since the `@for` loop can't uniquely identify items it might choose DOM nodes corresponding to _another_ item (with the same key) when performing DOM moves or destroy. + +There is also performance penalty associated with duplicated keys - internally Angular must use more sophisticated and slower data structures while repeating over collections with duplicated keys. + +## Fixing the error + +Change the tracking expression such that it uniquely identifies an item in a collection. In the discussed example the correct track expression would use the unique `key` property (`item.key`): + +```typescript +@Component({ + template: `@for (item of items; track item.key) {{{item.value}}}`, +}) +class TestComponent { + items = [{key: 1, value: 'a'}, {key: 2, value: 'b'}, {key: 3, value: 'a'}]; +} +``` diff --git a/adev-es/src/content/reference/errors/NG0955.md b/adev-es/src/content/reference/errors/NG0955.md index c74dae0..785f397 100644 --- a/adev-es/src/content/reference/errors/NG0955.md +++ b/adev-es/src/content/reference/errors/NG0955.md @@ -1,6 +1,6 @@ # Track expression resulted in duplicated keys for a given collection. -A track expression specified in the `@for` loop evaluated to duplicated keys for a given collection, ex.: +Una expresión de seguimiento especificada en el bucle `@for` evaluó claves duplicadas para una colección dada, por ejemplo: ```typescript @Component({ @@ -11,15 +11,15 @@ class TestComponent { } ``` -In the provided example the `item.key` tracking expression will find two duplicate keys `a` (at index 0 and 2). +En el ejemplo proporcionado, la expresión de seguimiento `item.key` encontrará dos claves duplicadas `a` (en los índices 0 y 2). -Duplicate keys are problematic from the correctness point of view: since the `@for` loop can't uniquely identify items it might choose DOM nodes corresponding to _another_ item (with the same key) when performing DOM moves or destroy. +Las claves duplicadas son problemáticas desde el punto de vista de la corrección: dado que el bucle `@for` no puede identificar de forma única los elementos, podría elegir nodos DOM correspondientes a _otro_ elemento (con la misma clave) al realizar movimientos o eliminaciones en el DOM. -There is also performance penalty associated with duplicated keys - internally Angular must use more sophisticated and slower data structures while repeating over collections with duplicated keys. +También hay una penalización de rendimiento asociada con las claves duplicadas: internamente Angular debe usar estructuras de datos más sofisticadas y lentas al iterar sobre colecciones con claves duplicadas. -## Fixing the error +## Corrigiendo el error -Change the tracking expression such that it uniquely identifies an item in a collection. In the discussed example the correct track expression would use the unique `key` property (`item.key`): +Cambia la expresión de seguimiento para que identifique de forma única un elemento en una colección. En el ejemplo discutido, la expresión de seguimiento correcta usaría la propiedad `key` única (`item.key`): ```typescript @Component({ diff --git a/adev-es/src/content/reference/errors/NG0956.en.md b/adev-es/src/content/reference/errors/NG0956.en.md new file mode 100644 index 0000000..3d1faad --- /dev/null +++ b/adev-es/src/content/reference/errors/NG0956.en.md @@ -0,0 +1,57 @@ +# Tracking expression caused re-creation of the DOM structure. + +The identity track expression specified in the `@for` loop caused re-creation of the DOM corresponding to _all_ items. This is a very expensive operation that commonly occurs when working with immutable data structures. For example: + +```typescript +@Component({ + template: ` + +
    + @for (todo of todos; track todo) { +
  • {{todo.task}}
  • + } +
+ `, +}) +export class App { + todos = [ + { id: 0, task: 'understand trackBy', done: false }, + { id: 1, task: 'use proper tracking expression', done: false }, + ]; + + toggleAllDone() { + this.todos = this.todos.map(todo => ({ ...todo, done: true })); + } +} +``` + +In the provided example, the entire list with all the views (DOM nodes, Angular directives, components, queries, etc.) are re-created (!) after toggling the "done" status of items. Here, a relatively inexpensive binding update to the `done` property would suffice. + +Apart from having a high performance penalty, re-creating the DOM tree results in loss of state in the DOM elements (ex.: focus, text selection, sites loaded in an iframe, etc.). + +## Fixing the error + +Change the tracking expression such that it uniquely identifies an item in a collection, regardless of its object identity. In the discussed example, the correct track expression would use the unique `id` property (`item.id`): + +```typescript +@Component({ + template: ` + +
    + @for (todo of todos; track todo.id) { +
  • {{todo.task}}
  • + } +
+ `, +}) +export class App { + todos = [ + { id: 0, task: 'understand trackBy', done: false }, + { id: 1, task: 'use proper tracking expression', done: false }, + ]; + + toggleAllDone() { + this.todos = this.todos.map(todo => ({ ...todo, done: true })); + } +} +``` diff --git a/adev-es/src/content/reference/errors/NG0956.md b/adev-es/src/content/reference/errors/NG0956.md index 3d1faad..0886097 100644 --- a/adev-es/src/content/reference/errors/NG0956.md +++ b/adev-es/src/content/reference/errors/NG0956.md @@ -1,6 +1,6 @@ # Tracking expression caused re-creation of the DOM structure. -The identity track expression specified in the `@for` loop caused re-creation of the DOM corresponding to _all_ items. This is a very expensive operation that commonly occurs when working with immutable data structures. For example: +La expresión de seguimiento de identidad especificada en el bucle `@for` causó la recreación del DOM correspondiente a _todos_ los elementos. Esta es una operación muy costosa que ocurre comúnmente cuando se trabaja con estructuras de datos inmutables. Por ejemplo: ```typescript @Component({ @@ -25,13 +25,13 @@ export class App { } ``` -In the provided example, the entire list with all the views (DOM nodes, Angular directives, components, queries, etc.) are re-created (!) after toggling the "done" status of items. Here, a relatively inexpensive binding update to the `done` property would suffice. +En el ejemplo proporcionado, la lista completa con todas las vistas (nodos DOM, directivas de Angular, componentes, consultas, etc.) se recrean (!) después de cambiar el estado "done" de los elementos. Aquí, una actualización de enlace relativamente económica a la propiedad `done` sería suficiente. -Apart from having a high performance penalty, re-creating the DOM tree results in loss of state in the DOM elements (ex.: focus, text selection, sites loaded in an iframe, etc.). +Además de tener una alta penalización de rendimiento, recrear el árbol DOM resulta en la pérdida del estado en los elementos DOM (por ejemplo: foco, selección de texto, sitios cargados en un iframe, etc.). -## Fixing the error +## Corrigiendo el error -Change the tracking expression such that it uniquely identifies an item in a collection, regardless of its object identity. In the discussed example, the correct track expression would use the unique `id` property (`item.id`): +Cambia la expresión de seguimiento para que identifique de forma única un elemento en una colección, independientemente de su identidad de objeto. En el ejemplo discutido, la expresión de seguimiento correcta usaría la propiedad `id` única (`item.id`): ```typescript @Component({ diff --git a/adev-es/src/content/reference/errors/NG1001.en.md b/adev-es/src/content/reference/errors/NG1001.en.md new file mode 100644 index 0000000..8ef38d6 --- /dev/null +++ b/adev-es/src/content/reference/errors/NG1001.en.md @@ -0,0 +1,31 @@ +# Argument Not Literal + +To make the metadata extraction in the Angular compiler faster, the decorators `@NgModule`, `@Pipe`, `@Component`, `@Directive`, and `@Injectable` accept only object literals as arguments. + +This is an [intentional change in Ivy](https://github.com/angular/angular/issues/30840#issuecomment-498869540), which enforces stricter argument requirements for decorators than View Engine. +Ivy requires this approach because it compiles decorators by moving the expressions into other locations in the class output. + +## Debugging the error + +Move all declarations: + +```ts +const moduleDefinition = {…} + +@NgModule(moduleDefinition) +export class AppModule { + constructor() {} +} + +``` + +into the decorator: + +```ts + +@NgModule({…}) +export class AppModule { + constructor() {} +} + +``` diff --git a/adev-es/src/content/reference/errors/NG1001.md b/adev-es/src/content/reference/errors/NG1001.md index 8ef38d6..7a1bd88 100644 --- a/adev-es/src/content/reference/errors/NG1001.md +++ b/adev-es/src/content/reference/errors/NG1001.md @@ -1,13 +1,13 @@ # Argument Not Literal -To make the metadata extraction in the Angular compiler faster, the decorators `@NgModule`, `@Pipe`, `@Component`, `@Directive`, and `@Injectable` accept only object literals as arguments. +Para hacer más rápida la extracción de metadatos en el compilador de Angular, los decoradores `@NgModule`, `@Pipe`, `@Component`, `@Directive` e `@Injectable` solo aceptan literales de objeto como argumentos. -This is an [intentional change in Ivy](https://github.com/angular/angular/issues/30840#issuecomment-498869540), which enforces stricter argument requirements for decorators than View Engine. -Ivy requires this approach because it compiles decorators by moving the expressions into other locations in the class output. +Este es un [cambio intencional en Ivy](https://github.com/angular/angular/issues/30840#issuecomment-498869540), que impone requisitos de argumento más estrictos para los decoradores que View Engine. +Ivy requiere este enfoque porque compila los decoradores moviendo las expresiones a otras ubicaciones en la salida de la clase. -## Debugging the error +## Depurando el error -Move all declarations: +Mueve todas las declaraciones: ```ts const moduleDefinition = {…} @@ -19,7 +19,7 @@ export class AppModule { ``` -into the decorator: +dentro del decorador: ```ts diff --git a/adev-es/src/content/reference/errors/NG2003.en.md b/adev-es/src/content/reference/errors/NG2003.en.md new file mode 100644 index 0000000..5feda3c --- /dev/null +++ b/adev-es/src/content/reference/errors/NG2003.en.md @@ -0,0 +1,10 @@ +# Missing Token + +There is no injection token for a constructor parameter at compile time. [InjectionTokens](api/core/InjectionToken) are tokens that can be used in a Dependency Injection Provider. + +## Debugging the error + +Look at the parameter that throws the error, and all uses of the class. +This error is commonly thrown when a constructor defines parameters with primitive types such as `string`, `number`, `boolean`, and `Object`. + +Use the `@Injectable` method or `@Inject` decorator from `@angular/core` to ensure that the type you are injecting is reified \(has a runtime representation\). Make sure to add a provider to this decorator so that you do not throw [NG0201: No Provider Found](errors/NG0201). diff --git a/adev-es/src/content/reference/errors/NG2003.md b/adev-es/src/content/reference/errors/NG2003.md index 5feda3c..6ca6928 100644 --- a/adev-es/src/content/reference/errors/NG2003.md +++ b/adev-es/src/content/reference/errors/NG2003.md @@ -1,10 +1,10 @@ # Missing Token -There is no injection token for a constructor parameter at compile time. [InjectionTokens](api/core/InjectionToken) are tokens that can be used in a Dependency Injection Provider. +No hay un token de inyección para un parámetro del constructor en tiempo de compilación. Los [InjectionTokens](api/core/InjectionToken) son tokens que se pueden usar en un proveedor de Inyección de Dependencias. -## Debugging the error +## Depurando el error -Look at the parameter that throws the error, and all uses of the class. -This error is commonly thrown when a constructor defines parameters with primitive types such as `string`, `number`, `boolean`, and `Object`. +Observa el parámetro que lanza el error y todos los usos de la clase. +Este error comúnmente se lanza cuando un constructor define parámetros con tipos primitivos como `string`, `number`, `boolean` y `Object`. -Use the `@Injectable` method or `@Inject` decorator from `@angular/core` to ensure that the type you are injecting is reified \(has a runtime representation\). Make sure to add a provider to this decorator so that you do not throw [NG0201: No Provider Found](errors/NG0201). +Usa el método `@Injectable` o el decorador `@Inject` de `@angular/core` para asegurarte de que el tipo que estás inyectando sea reificado \(tenga una representación en tiempo de ejecución\). Asegúrate de agregar un proveedor a este decorador para no lanzar [NG0201: No se encontró proveedor](errors/NG0201). diff --git a/adev-es/src/content/reference/errors/NG2009.en.md b/adev-es/src/content/reference/errors/NG2009.en.md new file mode 100644 index 0000000..68ff806 --- /dev/null +++ b/adev-es/src/content/reference/errors/NG2009.en.md @@ -0,0 +1,34 @@ +# Invalid Shadow DOM selector + +The selector of a component using `ViewEncapsulation.ShadowDom` doesn't match the custom element tag name requirements. + +In order for a tag name to be considered a valid custom element name, it has to: + +- Be in lower case. +- Contain a hyphen. +- Start with a letter \(a-z\). + +## Debugging the error + +Rename your component's selector so that it matches the requirements. + +**Before:** + +```ts +@Component({ + selector: 'comp', + encapsulation: ViewEncapsulation.ShadowDom +… +}) + +``` + +**After:** + +```ts +@Component({ + selector: 'app-comp', + encapsulation: ViewEncapsulation.ShadowDom +… +}) +``` diff --git a/adev-es/src/content/reference/errors/NG2009.md b/adev-es/src/content/reference/errors/NG2009.md index 68ff806..ce282f2 100644 --- a/adev-es/src/content/reference/errors/NG2009.md +++ b/adev-es/src/content/reference/errors/NG2009.md @@ -1,18 +1,18 @@ # Invalid Shadow DOM selector -The selector of a component using `ViewEncapsulation.ShadowDom` doesn't match the custom element tag name requirements. +El selector de un componente que usa `ViewEncapsulation.ShadowDom` no cumple los requisitos del nombre de etiqueta de elemento personalizado. -In order for a tag name to be considered a valid custom element name, it has to: +Para que un nombre de etiqueta se considere un nombre de elemento personalizado válido, debe: -- Be in lower case. -- Contain a hyphen. -- Start with a letter \(a-z\). +- Estar en minúsculas. +- Contener un guión. +- Comenzar con una letra \(a-z\). -## Debugging the error +## Depurando el error -Rename your component's selector so that it matches the requirements. +Renombra el selector de tu componente para que cumpla los requisitos. -**Before:** +**Antes:** ```ts @Component({ @@ -23,7 +23,7 @@ Rename your component's selector so that it matches the requirements. ``` -**After:** +**Después:** ```ts @Component({ diff --git a/adev-es/src/content/reference/errors/NG3003.en.md b/adev-es/src/content/reference/errors/NG3003.en.md new file mode 100644 index 0000000..3a1593c --- /dev/null +++ b/adev-es/src/content/reference/errors/NG3003.en.md @@ -0,0 +1,72 @@ +# Import Cycle Detected + +A component, directive, or pipe that is referenced by this component would require the compiler to add an import that would lead to a cycle of imports. +For example, consider a scenario where a `ParentComponent` references a `ChildComponent` in its template: + + +import {Component} from '@angular/core'; +import {ChildComponent} from './child.component'; + +@Component({ +selector: 'app-parent', +imports: [ChildComponent], +template: '', +}) +export class ParentComponent {} + + + +import {Component, inject} from '@angular/core'; +import {ParentComponent} from './parent.component'; + +@Component({ +selector: 'app-child', +template: 'The child!', +}) +export class ChildComponent { +private parent = inject(ParentComponent); +} + + +There is already an import from `child.component.ts` to `parent.component.ts` since the `ChildComponent` references the `ParentComponent` in its constructor. + +HELPFUL: The parent component's template contains ``. +The generated code for this template must therefore contain a reference to the `ChildComponent` class. +In order to make this reference, the compiler would have to add an import from `parent.component.ts` to `child.component.ts`, which would cause an import cycle: + + + +parent.component.ts -> child.component.ts -> parent.component.ts + + + +## Remote Scoping + +If you are using NgModules, to avoid adding imports that create cycles, additional code is added to the `NgModule` class where the component that wires up the dependencies is declared. + +This is known as "remote scoping". + +## Libraries + +Unfortunately, "remote scoping" code is side-effectful —which prevents tree shaking— and cannot be used in libraries. +So when building libraries using the `"compilationMode": "partial"` setting, any component that would require a cyclic import will cause this `NG3003` compiler error to be raised. + +## Debugging the error + +The cycle that would be generated is shown as part of the error message. +For example: + + + +The component ChildComponent is used in the template but importing it would create a cycle: +/parent.component.ts -> /child.component.ts -> /parent.component.ts + + + +Use this to identify how the referenced component, pipe, or directive has a dependency back to the component being compiled. +Here are some ideas for fixing the problem: + +- Try to rearrange your dependencies to avoid the cycle. + For example, using an intermediate interface that is stored in an independent file that can be imported to both dependent files without causing an import cycle. +- Move the classes that reference each other into the same file, to avoid any imports between them. +- Convert import statements to type-only imports \(using `import type` syntax\) if the imported declarations are only used as types, as type-only imports do not contribute to cycles. diff --git a/adev-es/src/content/reference/errors/NG3003.md b/adev-es/src/content/reference/errors/NG3003.md index 3a1593c..7b5bf57 100644 --- a/adev-es/src/content/reference/errors/NG3003.md +++ b/adev-es/src/content/reference/errors/NG3003.md @@ -1,7 +1,7 @@ # Import Cycle Detected -A component, directive, or pipe that is referenced by this component would require the compiler to add an import that would lead to a cycle of imports. -For example, consider a scenario where a `ParentComponent` references a `ChildComponent` in its template: +Un componente, directiva o pipe que es referenciado por este componente requeriría que el compilador agregue una importación que llevaría a un ciclo de importaciones. +Por ejemplo, considera un escenario donde un `ParentComponent` referencia un `ChildComponent` en su plantilla: import {Component} from '@angular/core'; @@ -28,11 +28,11 @@ private parent = inject(ParentComponent); } -There is already an import from `child.component.ts` to `parent.component.ts` since the `ChildComponent` references the `ParentComponent` in its constructor. +Ya existe una importación de `child.component.ts` a `parent.component.ts` dado que el `ChildComponent` referencia al `ParentComponent` en su constructor. -HELPFUL: The parent component's template contains ``. -The generated code for this template must therefore contain a reference to the `ChildComponent` class. -In order to make this reference, the compiler would have to add an import from `parent.component.ts` to `child.component.ts`, which would cause an import cycle: +ÚTIL: La plantilla del componente padre contiene ``. +El código generado para esta plantilla debe contener una referencia a la clase `ChildComponent`. +Para hacer esta referencia, el compilador tendría que agregar una importación de `parent.component.ts` a `child.component.ts`, lo que causaría un ciclo de importación: @@ -40,21 +40,21 @@ parent.component.ts -> child.component.ts -> parent.component.ts -## Remote Scoping +## Alcance remoto -If you are using NgModules, to avoid adding imports that create cycles, additional code is added to the `NgModule` class where the component that wires up the dependencies is declared. +Si estás usando NgModules, para evitar agregar importaciones que creen ciclos, se agrega código adicional a la clase `NgModule` donde se declara el componente que conecta las dependencias. -This is known as "remote scoping". +Esto se conoce como "alcance remoto" (remote scoping). -## Libraries +## Librerías -Unfortunately, "remote scoping" code is side-effectful —which prevents tree shaking— and cannot be used in libraries. -So when building libraries using the `"compilationMode": "partial"` setting, any component that would require a cyclic import will cause this `NG3003` compiler error to be raised. +Desafortunadamente, el código de "alcance remoto" tiene efectos secundarios, lo que impide el tree-shaking, y no puede usarse en librerías. +Por tanto, al construir librerías usando la configuración `"compilationMode": "partial"`, cualquier componente que requiera una importación cíclica causará que se lance este error del compilador `NG3003`. -## Debugging the error +## Depurando el error -The cycle that would be generated is shown as part of the error message. -For example: +El ciclo que se generaría se muestra como parte del mensaje de error. +Por ejemplo: @@ -63,10 +63,10 @@ The component ChildComponent is used in the template but importing it would crea -Use this to identify how the referenced component, pipe, or directive has a dependency back to the component being compiled. -Here are some ideas for fixing the problem: +Usa esto para identificar cómo el componente, pipe o directiva referenciado tiene una dependencia de regreso al componente que se está compilando. +Aquí hay algunas ideas para corregir el problema: -- Try to rearrange your dependencies to avoid the cycle. - For example, using an intermediate interface that is stored in an independent file that can be imported to both dependent files without causing an import cycle. -- Move the classes that reference each other into the same file, to avoid any imports between them. -- Convert import statements to type-only imports \(using `import type` syntax\) if the imported declarations are only used as types, as type-only imports do not contribute to cycles. +- Intenta reorganizar tus dependencias para evitar el ciclo. + Por ejemplo, usando una interfaz intermedia que se almacene en un archivo independiente que pueda importarse a ambos archivos dependientes sin causar un ciclo de importación. +- Mueve las clases que se referencian mutuamente al mismo archivo, para evitar cualquier importación entre ellas. +- Convierte las declaraciones de importación a importaciones solo de tipo \(usando la sintaxis `import type`\) si las declaraciones importadas solo se usan como tipos, ya que las importaciones solo de tipo no contribuyen a los ciclos. diff --git a/adev-es/src/content/reference/errors/NG6100.en.md b/adev-es/src/content/reference/errors/NG6100.en.md new file mode 100644 index 0000000..5d97685 --- /dev/null +++ b/adev-es/src/content/reference/errors/NG6100.en.md @@ -0,0 +1,24 @@ +# NgModule.id Set to module.id anti-pattern + +Using `module.id` as an NgModule `id` is a common anti-pattern and is likely not serving a useful purpose in your code. + +NgModules can be declared with an `id`: + +```typescript +@NgModule({ + id: 'my_module' +}) +export class MyModule {} +``` + +Declaring an `id` makes the NgModule available for lookup via the `getNgModuleById()` operation. This functionality is rarely used, mainly in very specific bundling scenarios when lazily loading NgModules without obtaining direct references to them. In most Angular code, ES dynamic `import()` (`import('./path/to/module')`) should be used instead, as this provides a direct reference to the NgModule being loaded without the need for a global registration side effect. + +If you are not using `getNgModuleById`, you do not need to provide `id`s for your NgModules. Providing one has a significant drawback: it makes the NgModule non-tree-shakable, which can have an impact on your bundle size. + +In particular, the pattern of specifying `id: module.id` results from a misunderstanding of `@NgModule.id`. In earlier versions of Angular, it was sometimes necessary to include the property `moduleId: module.id` in `@Component` metadata. + +Using `module.id` for `@NgModule.id` likely results from confusion between `@Component.moduleId` and `@NgModule.id`. `module.id` would not typically be useful for `getNgModuleById()` operations as the `id` needs to be a well-known string, and `module.id` is usually opaque to consumers. + +## Debugging the error + +You can remove the `id: module.id` declaration from your NgModules. The compiler ignores this declaration and issues this warning instead. diff --git a/adev-es/src/content/reference/errors/NG6100.md b/adev-es/src/content/reference/errors/NG6100.md index 5d97685..4e6ac93 100644 --- a/adev-es/src/content/reference/errors/NG6100.md +++ b/adev-es/src/content/reference/errors/NG6100.md @@ -1,8 +1,8 @@ # NgModule.id Set to module.id anti-pattern -Using `module.id` as an NgModule `id` is a common anti-pattern and is likely not serving a useful purpose in your code. +Usar `module.id` como `id` de NgModule es un anti-patrón común y probablemente no esté cumpliendo un propósito útil en tu código. -NgModules can be declared with an `id`: +Los NgModules pueden declararse con un `id`: ```typescript @NgModule({ @@ -11,14 +11,14 @@ NgModules can be declared with an `id`: export class MyModule {} ``` -Declaring an `id` makes the NgModule available for lookup via the `getNgModuleById()` operation. This functionality is rarely used, mainly in very specific bundling scenarios when lazily loading NgModules without obtaining direct references to them. In most Angular code, ES dynamic `import()` (`import('./path/to/module')`) should be used instead, as this provides a direct reference to the NgModule being loaded without the need for a global registration side effect. +Declarar un `id` hace que el NgModule esté disponible para búsqueda mediante la operación `getNgModuleById()`. Esta funcionalidad raramente se usa, principalmente en escenarios de empaquetado muy específicos cuando se cargan NgModules de forma diferida sin obtener referencias directas a ellos. En la mayoría del código Angular, se debe usar el `import()` dinámico de ES (`import('./path/to/module')`) en su lugar, ya que esto proporciona una referencia directa al NgModule que se está cargando sin necesidad de un efecto secundario de registro global. -If you are not using `getNgModuleById`, you do not need to provide `id`s for your NgModules. Providing one has a significant drawback: it makes the NgModule non-tree-shakable, which can have an impact on your bundle size. +Si no estás usando `getNgModuleById`, no necesitas proporcionar `id`s para tus NgModules. Proporcionar uno tiene un inconveniente significativo: hace que el NgModule no sea eliminable por tree-shaking, lo que puede tener un impacto en el tamaño de tu bundle. -In particular, the pattern of specifying `id: module.id` results from a misunderstanding of `@NgModule.id`. In earlier versions of Angular, it was sometimes necessary to include the property `moduleId: module.id` in `@Component` metadata. +En particular, el patrón de especificar `id: module.id` resulta de un malentendido de `@NgModule.id`. En versiones anteriores de Angular, a veces era necesario incluir la propiedad `moduleId: module.id` en los metadatos de `@Component`. -Using `module.id` for `@NgModule.id` likely results from confusion between `@Component.moduleId` and `@NgModule.id`. `module.id` would not typically be useful for `getNgModuleById()` operations as the `id` needs to be a well-known string, and `module.id` is usually opaque to consumers. +Usar `module.id` para `@NgModule.id` probablemente resulta de la confusión entre `@Component.moduleId` y `@NgModule.id`. `module.id` normalmente no sería útil para las operaciones `getNgModuleById()` ya que el `id` debe ser una cadena bien conocida, y `module.id` generalmente es opaco para los consumidores. -## Debugging the error +## Depurando el error -You can remove the `id: module.id` declaration from your NgModules. The compiler ignores this declaration and issues this warning instead. +Puedes eliminar la declaración `id: module.id` de tus NgModules. El compilador ignora esta declaración y emite esta advertencia en su lugar. diff --git a/adev-es/src/content/reference/errors/NG8001.en.md b/adev-es/src/content/reference/errors/NG8001.en.md new file mode 100644 index 0000000..e35bce8 --- /dev/null +++ b/adev-es/src/content/reference/errors/NG8001.en.md @@ -0,0 +1,17 @@ +# Invalid Element + +One or more elements cannot be resolved during compilation because the element is not defined by the HTML spec, or there is no component or directive with such element selector. + +HELPFUL: This is the compiler equivalent of a common runtime error `NG0304: '${tagName}' is not a known element: ...`. + +## Debugging the error + +Use the element name in the error to find the file(s) where the element is being used. + +Check that the name and selector are correct. + +Make sure that the component is correctly imported inside your NgModule or standalone component, by checking its presence in the `imports` field. If the component is declared in an NgModule (meaning that it is not standalone) make sure that it is exported correctly from it, by checking its presence in the `exports` field. + +When using custom elements or web components, ensure that you add [`CUSTOM_ELEMENTS_SCHEMA`](api/core/CUSTOM_ELEMENTS_SCHEMA) to the application module. + +If this does not resolve the error, check the imported libraries for any recent changes to the exports and properties you are using, and restart your server. diff --git a/adev-es/src/content/reference/errors/NG8001.md b/adev-es/src/content/reference/errors/NG8001.md index e35bce8..0dea8b2 100644 --- a/adev-es/src/content/reference/errors/NG8001.md +++ b/adev-es/src/content/reference/errors/NG8001.md @@ -1,17 +1,17 @@ # Invalid Element -One or more elements cannot be resolved during compilation because the element is not defined by the HTML spec, or there is no component or directive with such element selector. +Uno o más elementos no pueden resolverse durante la compilación porque el elemento no está definido por la especificación HTML, o no hay ningún componente o directiva con ese selector de elemento. -HELPFUL: This is the compiler equivalent of a common runtime error `NG0304: '${tagName}' is not a known element: ...`. +ÚTIL: Este es el equivalente en el compilador de un error de tiempo de ejecución común `NG0304: '${tagName}' is not a known element: ...`. -## Debugging the error +## Depurando el error -Use the element name in the error to find the file(s) where the element is being used. +Usa el nombre del elemento del error para encontrar el o los archivos donde se está usando el elemento. -Check that the name and selector are correct. +Verifica que el nombre y el selector sean correctos. -Make sure that the component is correctly imported inside your NgModule or standalone component, by checking its presence in the `imports` field. If the component is declared in an NgModule (meaning that it is not standalone) make sure that it is exported correctly from it, by checking its presence in the `exports` field. +Asegúrate de que el componente esté correctamente importado dentro de tu NgModule o componente standalone, verificando su presencia en el campo `imports`. Si el componente está declarado en un NgModule (lo que significa que no es standalone), asegúrate de que esté exportado correctamente desde él, verificando su presencia en el campo `exports`. -When using custom elements or web components, ensure that you add [`CUSTOM_ELEMENTS_SCHEMA`](api/core/CUSTOM_ELEMENTS_SCHEMA) to the application module. +Al usar elementos personalizados o web components, asegúrate de agregar [`CUSTOM_ELEMENTS_SCHEMA`](api/core/CUSTOM_ELEMENTS_SCHEMA) al módulo de la aplicación. -If this does not resolve the error, check the imported libraries for any recent changes to the exports and properties you are using, and restart your server. +Si esto no resuelve el error, verifica las librerías importadas para ver si hay cambios recientes en las exportaciones y propiedades que estás usando, y reinicia tu servidor. diff --git a/adev-es/src/content/reference/errors/NG8002.en.md b/adev-es/src/content/reference/errors/NG8002.en.md new file mode 100644 index 0000000..8ca21a4 --- /dev/null +++ b/adev-es/src/content/reference/errors/NG8002.en.md @@ -0,0 +1,18 @@ +# Invalid Attribute + + + +An attribute or property cannot be resolved during compilation. + +This error arises when attempting to bind to a property that does not exist. +Any property binding must correspond to either: + +- A native property on the HTML element, or +- An `input()`/`@Input()` property of a component or directive applied to the element. + +The runtime error for this is `NG0304: '${tagName}' is not a known element: …'`. + +## Debugging the error + +Look at documentation for the specific [binding syntax](guide/templates) used. This is usually a typo or incorrect import. +There may also be a missing direction with property selector 'name' or missing input. diff --git a/adev-es/src/content/reference/errors/NG8002.md b/adev-es/src/content/reference/errors/NG8002.md index 8ca21a4..1d39450 100644 --- a/adev-es/src/content/reference/errors/NG8002.md +++ b/adev-es/src/content/reference/errors/NG8002.md @@ -2,17 +2,17 @@ -An attribute or property cannot be resolved during compilation. +Un atributo o propiedad no puede resolverse durante la compilación. -This error arises when attempting to bind to a property that does not exist. -Any property binding must correspond to either: +Este error surge cuando se intenta vincular a una propiedad que no existe. +Cualquier enlace de propiedad debe corresponder a: -- A native property on the HTML element, or -- An `input()`/`@Input()` property of a component or directive applied to the element. +- Una propiedad nativa del elemento HTML, o +- Una propiedad `input()`/`@Input()` de un componente o directiva aplicado al elemento. -The runtime error for this is `NG0304: '${tagName}' is not a known element: …'`. +El error de tiempo de ejecución para esto es `NG0304: '${tagName}' is not a known element: …'`. -## Debugging the error +## Depurando el error -Look at documentation for the specific [binding syntax](guide/templates) used. This is usually a typo or incorrect import. -There may also be a missing direction with property selector 'name' or missing input. +Consulta la documentación de la [sintaxis de enlace](guide/templates) específica usada. Esto generalmente es un error tipográfico o una importación incorrecta. +También puede haber una directiva faltante con el selector de propiedad 'name' o una entrada faltante. diff --git a/adev-es/src/content/reference/errors/NG8003.en.md b/adev-es/src/content/reference/errors/NG8003.en.md new file mode 100644 index 0000000..f753b62 --- /dev/null +++ b/adev-es/src/content/reference/errors/NG8003.en.md @@ -0,0 +1,29 @@ +# Missing Reference Target + + + +Angular can't find a directive with `{{ PLACEHOLDER }}` export name. +This is common with a missing import or a missing [`exportAs`](api/core/Directive#exportAs) on a directive. + +HELPFUL: This is the compiler equivalent of a common runtime error [NG0301: Export Not Found](errors/NG0301). + +## Debugging the error + +Use the string name of the export not found to trace the templates or modules using this export. + +Ensure that all dependencies are properly imported and declared in our Modules. +For example, if the export not found is `ngForm`, we will need to import `FormsModule` and declare it in our list of imports in `*.module.ts` to resolve the missing export error. + +```ts + +import { FormsModule } from '@angular/forms'; + +@NgModule({ +… +imports: [ +FormsModule, +… + +``` + +If you recently added an import, you will need to restart your server to see these changes. diff --git a/adev-es/src/content/reference/errors/NG8003.md b/adev-es/src/content/reference/errors/NG8003.md index f753b62..446e948 100644 --- a/adev-es/src/content/reference/errors/NG8003.md +++ b/adev-es/src/content/reference/errors/NG8003.md @@ -2,17 +2,17 @@ -Angular can't find a directive with `{{ PLACEHOLDER }}` export name. -This is common with a missing import or a missing [`exportAs`](api/core/Directive#exportAs) on a directive. +Angular no puede encontrar una directiva con el nombre de exportación `{{ PLACEHOLDER }}`. +Esto es común cuando falta una importación o falta un [`exportAs`](api/core/Directive#exportAs) en una directiva. -HELPFUL: This is the compiler equivalent of a common runtime error [NG0301: Export Not Found](errors/NG0301). +ÚTIL: Este es el equivalente en el compilador de un error de tiempo de ejecución común [NG0301: Exportación no encontrada](errors/NG0301). -## Debugging the error +## Depurando el error -Use the string name of the export not found to trace the templates or modules using this export. +Usa el nombre de cadena de la exportación no encontrada para rastrear las plantillas o módulos que usan esta exportación. -Ensure that all dependencies are properly imported and declared in our Modules. -For example, if the export not found is `ngForm`, we will need to import `FormsModule` and declare it in our list of imports in `*.module.ts` to resolve the missing export error. +Asegúrate de que todas las dependencias estén correctamente importadas y declaradas en nuestros módulos. +Por ejemplo, si la exportación no encontrada es `ngForm`, necesitaremos importar `FormsModule` y declararlo en nuestra lista de importaciones en `*.module.ts` para resolver el error de exportación faltante. ```ts @@ -26,4 +26,4 @@ FormsModule, ``` -If you recently added an import, you will need to restart your server to see these changes. +Si recientemente agregaste una importación, necesitarás reiniciar tu servidor para ver estos cambios. diff --git a/adev-es/src/content/reference/errors/overview.en.md b/adev-es/src/content/reference/errors/overview.en.md new file mode 100644 index 0000000..00fb3db --- /dev/null +++ b/adev-es/src/content/reference/errors/overview.en.md @@ -0,0 +1,49 @@ +# Error Encyclopedia + +## Runtime errors + +| Code | Name | +| :-------- | :----------------------------------------------------------------------------------- | +| `NG0100` | [Expression Changed After Checked](errors/NG0100) | +| `NG0200` | [Circular Dependency in DI](errors/NG0200) | +| `NG0201` | [No Provider Found](errors/NG0201) | +| `NG0203` | [`inject()` must be called from an injection context](errors/NG0203) | +| `NG0209` | [Invalid multi provider](errors/NG0209) | +| `NG0300` | [Selector Collision](errors/NG0300) | +| `NG0301` | [Export Not Found](errors/NG0301) | +| `NG0302` | [Pipe Not Found](errors/NG0302) | +| `NG0401` | [Missing platform](errors/NG0401) | +| `NG0403` | [Bootstrapped NgModule doesn't specify which component to initialize](errors/NG0403) | +| `NG0500` | [Hydration Node Mismatch](errors/NG0500) | +| `NG0501` | [Hydration Missing Siblings](errors/NG0501) | +| `NG0502` | [Hydration Missing Node](errors/NG0502) | +| `NG0503` | [Hydration Unsupported Projection of DOM Nodes](errors/NG0503) | +| `NG0504` | [Skip hydration flag is applied to an invalid node](errors/NG0504) | +| `NG0505` | [No hydration info in server response](errors/NG0505) | +| `NG0506` | [NgZone remains unstable](errors/NG0506) | +| `NG0507` | [HTML content was altered after SSR](errors/NG0507) | +| `NG0750` | [@defer dependencies failed to load](errors/NG0750) | +| `NG0910` | [Unsafe bindings on an iframe element](errors/NG0910) | +| `NG0912` | [Component ID generation collision](errors/NG0912) | +| `NG0955` | [Track expression resulted in duplicated keys for a given collection](errors/NG0955) | +| `NG0956` | [Tracking expression caused re-creation of the DOM structure](errors/NG0956) | +| `NG01101` | [Wrong Async Validator Return Type](errors/NG01101) | +| `NG01203` | [Missing value accessor](errors/NG01203) | +| `NG02200` | [Missing Iterable Differ](errors/NG02200) | +| `NG02800` | [JSONP support in HttpClient configuration](errors/NG02800) | +| `NG02802` | [Headers not transferred by HttpTransferCache](errors/NG02802) | +| `NG05000` | [Hydration with unsupported Zone.js instance.](errors/NG05000) | +| `NG05104` | [Root element was not found.](errors/NG05104) | + +## Compiler errors + +| Code | Name | +| :------- | :--------------------------------------------------------- | +| `NG1001` | [Argument Not Literal](errors/NG1001) | +| `NG2003` | [Missing Token](errors/NG2003) | +| `NG2009` | [Invalid Shadow DOM selector](errors/NG2009) | +| `NG3003` | [Import Cycle Detected](errors/NG3003) | +| `NG6100` | [NgModule.id Set to module.id anti-pattern](errors/NG6100) | +| `NG8001` | [Invalid Element](errors/NG8001) | +| `NG8002` | [Invalid Attribute](errors/NG8002) | +| `NG8003` | [Missing Reference Target](errors/NG8003) | diff --git a/adev-es/src/content/reference/errors/overview.md b/adev-es/src/content/reference/errors/overview.md index 00fb3db..9d83fad 100644 --- a/adev-es/src/content/reference/errors/overview.md +++ b/adev-es/src/content/reference/errors/overview.md @@ -1,49 +1,49 @@ -# Error Encyclopedia +# Enciclopedia de Errores -## Runtime errors +## Errores en tiempo de ejecución -| Code | Name | -| :-------- | :----------------------------------------------------------------------------------- | -| `NG0100` | [Expression Changed After Checked](errors/NG0100) | -| `NG0200` | [Circular Dependency in DI](errors/NG0200) | -| `NG0201` | [No Provider Found](errors/NG0201) | -| `NG0203` | [`inject()` must be called from an injection context](errors/NG0203) | -| `NG0209` | [Invalid multi provider](errors/NG0209) | -| `NG0300` | [Selector Collision](errors/NG0300) | -| `NG0301` | [Export Not Found](errors/NG0301) | -| `NG0302` | [Pipe Not Found](errors/NG0302) | -| `NG0401` | [Missing platform](errors/NG0401) | -| `NG0403` | [Bootstrapped NgModule doesn't specify which component to initialize](errors/NG0403) | -| `NG0500` | [Hydration Node Mismatch](errors/NG0500) | -| `NG0501` | [Hydration Missing Siblings](errors/NG0501) | -| `NG0502` | [Hydration Missing Node](errors/NG0502) | -| `NG0503` | [Hydration Unsupported Projection of DOM Nodes](errors/NG0503) | -| `NG0504` | [Skip hydration flag is applied to an invalid node](errors/NG0504) | -| `NG0505` | [No hydration info in server response](errors/NG0505) | -| `NG0506` | [NgZone remains unstable](errors/NG0506) | -| `NG0507` | [HTML content was altered after SSR](errors/NG0507) | -| `NG0750` | [@defer dependencies failed to load](errors/NG0750) | -| `NG0910` | [Unsafe bindings on an iframe element](errors/NG0910) | -| `NG0912` | [Component ID generation collision](errors/NG0912) | -| `NG0955` | [Track expression resulted in duplicated keys for a given collection](errors/NG0955) | -| `NG0956` | [Tracking expression caused re-creation of the DOM structure](errors/NG0956) | -| `NG01101` | [Wrong Async Validator Return Type](errors/NG01101) | -| `NG01203` | [Missing value accessor](errors/NG01203) | -| `NG02200` | [Missing Iterable Differ](errors/NG02200) | -| `NG02800` | [JSONP support in HttpClient configuration](errors/NG02800) | -| `NG02802` | [Headers not transferred by HttpTransferCache](errors/NG02802) | -| `NG05000` | [Hydration with unsupported Zone.js instance.](errors/NG05000) | -| `NG05104` | [Root element was not found.](errors/NG05104) | +| Código | Nombre | +| :-------- | :------------------------------------------------------------------------------------------ | +| `NG0100` | [Expresión cambiada después de la verificación](errors/NG0100) | +| `NG0200` | [Dependencia circular en DI](errors/NG0200) | +| `NG0201` | [No se encontró proveedor](errors/NG0201) | +| `NG0203` | [`inject()` debe llamarse desde un contexto de inyección](errors/NG0203) | +| `NG0209` | [Proveedor múltiple inválido](errors/NG0209) | +| `NG0300` | [Colisión de selectores](errors/NG0300) | +| `NG0301` | [Exportación no encontrada](errors/NG0301) | +| `NG0302` | [Pipe no encontrado](errors/NG0302) | +| `NG0401` | [Plataforma faltante](errors/NG0401) | +| `NG0403` | [El NgModule en bootstrap no especifica qué componente inicializar](errors/NG0403) | +| `NG0500` | [Discordancia de nodo en hidratación](errors/NG0500) | +| `NG0501` | [Hidratación: hermanos faltantes](errors/NG0501) | +| `NG0502` | [Hidratación: nodo faltante](errors/NG0502) | +| `NG0503` | [Hidratación: proyección de nodos DOM no compatible](errors/NG0503) | +| `NG0504` | [La marca ngSkipHydration se aplica a un nodo inválido](errors/NG0504) | +| `NG0505` | [Sin información de hidratación en la respuesta del servidor](errors/NG0505) | +| `NG0506` | [NgZone permanece inestable](errors/NG0506) | +| `NG0507` | [El contenido HTML fue alterado después del SSR](errors/NG0507) | +| `NG0750` | [Las dependencias de @defer no se pudieron cargar](errors/NG0750) | +| `NG0910` | [Enlaces inseguros en un elemento iframe](errors/NG0910) | +| `NG0912` | [Colisión en la generación de ID de componente](errors/NG0912) | +| `NG0955` | [La expresión de seguimiento resultó en claves duplicadas para una colección](errors/NG0955)| +| `NG0956` | [La expresión de seguimiento causó la recreación de la estructura DOM](errors/NG0956) | +| `NG01101` | [Tipo de retorno incorrecto para validador asíncrono](errors/NG01101) | +| `NG01203` | [Accessor de valor faltante](errors/NG01203) | +| `NG02200` | [Diferenciador iterable faltante](errors/NG02200) | +| `NG02800` | [Soporte JSONP en la configuración de HttpClient](errors/NG02800) | +| `NG02802` | [Encabezados no transferidos por HttpTransferCache](errors/NG02802) | +| `NG05000` | [Hidratación con instancia de Zone.js no compatible](errors/NG05000) | +| `NG05104` | [No se encontró el elemento raíz](errors/NG05104) | -## Compiler errors +## Errores del compilador -| Code | Name | -| :------- | :--------------------------------------------------------- | -| `NG1001` | [Argument Not Literal](errors/NG1001) | -| `NG2003` | [Missing Token](errors/NG2003) | -| `NG2009` | [Invalid Shadow DOM selector](errors/NG2009) | -| `NG3003` | [Import Cycle Detected](errors/NG3003) | -| `NG6100` | [NgModule.id Set to module.id anti-pattern](errors/NG6100) | -| `NG8001` | [Invalid Element](errors/NG8001) | -| `NG8002` | [Invalid Attribute](errors/NG8002) | -| `NG8003` | [Missing Reference Target](errors/NG8003) | +| Código | Nombre | +| :------- | :--------------------------------------------------------------- | +| `NG1001` | [Argumento no literal](errors/NG1001) | +| `NG2003` | [Token faltante](errors/NG2003) | +| `NG2009` | [Selector de Shadow DOM inválido](errors/NG2009) | +| `NG3003` | [Ciclo de importación detectado](errors/NG3003) | +| `NG6100` | [NgModule.id establecido como module.id: anti-patrón](errors/NG6100) | +| `NG8001` | [Elemento inválido](errors/NG8001) | +| `NG8002` | [Atributo inválido](errors/NG8002) | +| `NG8003` | [Referencia de destino faltante](errors/NG8003) |