diff --git a/adev-es/src/content/reference/migrations/cleanup-unused-imports.en.md b/adev-es/src/content/reference/migrations/cleanup-unused-imports.en.md new file mode 100644 index 0000000..1f710af --- /dev/null +++ b/adev-es/src/content/reference/migrations/cleanup-unused-imports.en.md @@ -0,0 +1,36 @@ +# Clean up unused imports + +As of version 19, Angular reports when a component's `imports` array contains symbols that aren't used in its template. + +Running this schematic will clean up all unused imports within the project. + +Run the schematic using the following command: + +```shell +ng generate @angular/core:cleanup-unused-imports +``` + +#### Before + +```angular-ts +import {Component} from '@angular/core'; +import {UnusedDirective} from './unused'; + +@Component({ + template: 'Hello', + imports: [UnusedDirective], +}) +export class MyComp {} +``` + +#### After + +```angular-ts +import {Component} from '@angular/core'; + +@Component({ + template: 'Hello', + imports: [], +}) +export class MyComp {} +``` diff --git a/adev-es/src/content/reference/migrations/cleanup-unused-imports.md b/adev-es/src/content/reference/migrations/cleanup-unused-imports.md index 1f710af..fd9d352 100644 --- a/adev-es/src/content/reference/migrations/cleanup-unused-imports.md +++ b/adev-es/src/content/reference/migrations/cleanup-unused-imports.md @@ -1,16 +1,16 @@ -# Clean up unused imports +# Limpiar importaciones no utilizadas -As of version 19, Angular reports when a component's `imports` array contains symbols that aren't used in its template. +A partir de la versión 19, Angular reporta cuando el array `imports` de un componente contiene símbolos que no se usan en su plantilla. -Running this schematic will clean up all unused imports within the project. +Ejecutar este schematic limpiará todas las importaciones no utilizadas dentro del proyecto. -Run the schematic using the following command: +Ejecuta el schematic usando el siguiente comando: ```shell ng generate @angular/core:cleanup-unused-imports ``` -#### Before +#### Antes ```angular-ts import {Component} from '@angular/core'; @@ -23,7 +23,7 @@ import {UnusedDirective} from './unused'; export class MyComp {} ``` -#### After +#### Después ```angular-ts import {Component} from '@angular/core'; diff --git a/adev-es/src/content/reference/migrations/common-to-standalone.en.md b/adev-es/src/content/reference/migrations/common-to-standalone.en.md new file mode 100644 index 0000000..f0f59b0 --- /dev/null +++ b/adev-es/src/content/reference/migrations/common-to-standalone.en.md @@ -0,0 +1,59 @@ +# Convert CommonModule usage to standalone imports + +This migration helps projects remove imports of the `CommonModule` inside components by adding the minimal set of directive and pipe imports each template requires (for example, `NgIf`, `NgFor`, `AsyncPipe`, etc.). + +Run the schematic using the following command: + +```shell +ng generate @angular/core:common-to-standalone +``` + +## Options + +| Option | Details | +| :----- | :---------------------------------------------------------------------------------------------------------------------------- | +| `path` | The path (relative to project root) to migrate. Defaults to `./`. Use this to incrementally migrate a subset of your project. | + +## Example + +Before: + +```angular-ts +import { Component } from '@angular/core'; +import { CommonModule } from '@angular/common'; + +@Component({ + selector: 'app-example', + imports: [CommonModule], + template: ` +
+ {{ data | async | json }} +
+ ` +}) +export class ExampleComponent { + show = true; + data = Promise.resolve({ message: 'Hello' }); +} +``` + +After running the migration (component imports added, CommonModule removed): + +```angular-ts +import { Component } from '@angular/core'; +import { AsyncPipe, JsonPipe, NgIf } from '@angular/common'; + +@Component({ + selector: 'app-example', + imports: [AsyncPipe, JsonPipe, NgIf], + template: ` +
+ {{ data | async | json }} +
+ ` +}) +export class ExampleComponent { + show = true; + data = Promise.resolve({ message: 'Hello' }); +} +``` diff --git a/adev-es/src/content/reference/migrations/common-to-standalone.md b/adev-es/src/content/reference/migrations/common-to-standalone.md index f0f59b0..a17f1bc 100644 --- a/adev-es/src/content/reference/migrations/common-to-standalone.md +++ b/adev-es/src/content/reference/migrations/common-to-standalone.md @@ -1,22 +1,22 @@ -# Convert CommonModule usage to standalone imports +# Convertir el uso de CommonModule a importaciones standalone -This migration helps projects remove imports of the `CommonModule` inside components by adding the minimal set of directive and pipe imports each template requires (for example, `NgIf`, `NgFor`, `AsyncPipe`, etc.). +Esta migración ayuda a los proyectos a eliminar las importaciones de `CommonModule` dentro de los componentes agregando el conjunto mínimo de importaciones de directivas y pipes que cada plantilla requiere (por ejemplo, `NgIf`, `NgFor`, `AsyncPipe`, etc.). -Run the schematic using the following command: +Ejecuta el schematic usando el siguiente comando: ```shell ng generate @angular/core:common-to-standalone ``` -## Options +## Opciones -| Option | Details | -| :----- | :---------------------------------------------------------------------------------------------------------------------------- | -| `path` | The path (relative to project root) to migrate. Defaults to `./`. Use this to incrementally migrate a subset of your project. | +| Opción | Detalles | +| :----- | :----------------------------------------------------------------------------------------------------------------------------------------- | +| `path` | La ruta (relativa a la raíz del proyecto) a migrar. Por defecto es `./`. Úsala para migrar de forma incremental un subconjunto de tu proyecto. | -## Example +## Ejemplo -Before: +Antes: ```angular-ts import { Component } from '@angular/core'; @@ -37,7 +37,7 @@ export class ExampleComponent { } ``` -After running the migration (component imports added, CommonModule removed): +Después de ejecutar la migración (importaciones del componente agregadas, CommonModule eliminado): ```angular-ts import { Component } from '@angular/core'; diff --git a/adev-es/src/content/reference/migrations/control-flow.en.md b/adev-es/src/content/reference/migrations/control-flow.en.md new file mode 100644 index 0000000..58ef83b --- /dev/null +++ b/adev-es/src/content/reference/migrations/control-flow.en.md @@ -0,0 +1,11 @@ +# Migration to Control Flow syntax + +[Control flow syntax](guide/templates/control-flow) is available from Angular v17. The new syntax is baked into the template, so you don't need to import `CommonModule` anymore. + +This schematic migrates all existing code in your application to use new Control Flow Syntax. + +Run the schematic using the following command: + +```shell +ng generate @angular/core:control-flow +``` diff --git a/adev-es/src/content/reference/migrations/control-flow.md b/adev-es/src/content/reference/migrations/control-flow.md index 58ef83b..936df52 100644 --- a/adev-es/src/content/reference/migrations/control-flow.md +++ b/adev-es/src/content/reference/migrations/control-flow.md @@ -1,10 +1,10 @@ -# Migration to Control Flow syntax +# Migración a la sintaxis de flujo de control -[Control flow syntax](guide/templates/control-flow) is available from Angular v17. The new syntax is baked into the template, so you don't need to import `CommonModule` anymore. +La [sintaxis de flujo de control](guide/templates/control-flow) está disponible desde Angular v17. La nueva sintaxis está integrada en la plantilla, por lo que ya no necesitas importar `CommonModule`. -This schematic migrates all existing code in your application to use new Control Flow Syntax. +Este schematic migra todo el código existente en tu aplicación para usar la nueva sintaxis de flujo de control. -Run the schematic using the following command: +Ejecuta el schematic usando el siguiente comando: ```shell ng generate @angular/core:control-flow diff --git a/adev-es/src/content/reference/migrations/inject-function.en.md b/adev-es/src/content/reference/migrations/inject-function.en.md new file mode 100644 index 0000000..357b2a9 --- /dev/null +++ b/adev-es/src/content/reference/migrations/inject-function.en.md @@ -0,0 +1,137 @@ +# Migration to the `inject` function + +Angular's `inject` function offers more accurate types and better compatibility with standard decorators, compared to constructor-based injection. + +This schematic converts constructor-based injection in your classes to use the `inject` function instead. + +Run the schematic using the following command: + +```shell +ng generate @angular/core:inject +``` + +#### Before + +```typescript +import { Component, Inject, Optional } from '@angular/core'; +import { MyService } from './service'; +import { DI_TOKEN } from './token'; + +@Component() +export class MyComp { + constructor( + private service: MyService, + @Inject(DI_TOKEN) @Optional() readonly token: string + ) {} +} +``` + +#### After + +```typescript +import { Component, inject } from '@angular/core'; +import { MyService } from './service'; +import { DI_TOKEN } from './token'; + +@Component() +export class MyComp { + private service = inject(MyService); + readonly token = inject(DI_TOKEN, { optional: true }); +} +``` + +## Migration options + +The migration includes several options to customize its output. + +### `path` + +Determines which sub-path in your project should be migrated. Pass in `.` or leave it blank to +migrate the entire directory. + +### `migrateAbstractClasses` + +Angular doesn't validate that parameters of abstract classes are injectable. This means that the +migration can't reliably migrate them to `inject` without risking breakages which is why they're +disabled by default. Enable this option if you want abstract classes to be migrated, but note +that you may have to **fix some breakages manually**. + +### `backwardsCompatibleConstructors` + +By default the migration tries to clean up the code as much as it can, which includes deleting +parameters from the constructor, or even the entire constructor if it doesn't include any code. +In some cases this can lead to compilation errors when classes with Angular decorators inherit from +other classes with Angular decorators. If you enable this option, the migration will generate an +additional constructor signature to keep it backwards compatible, at the expense of more code. + +#### Before + +```typescript +import { Component } from '@angular/core'; +import { MyService } from './service'; + +@Component() +export class MyComp { + constructor(private service: MyService) {} +} +``` + +#### After + +```typescript +import { Component } from '@angular/core'; +import { MyService } from './service'; + +@Component() +export class MyComp { +private service = inject(MyService); + +/\*_ Inserted by Angular inject() migration for backwards compatibility _/ +constructor(...args: unknown[]); + +constructor() {} +} +``` + +### `nonNullableOptional` + +If injection fails for a parameter with the `@Optional` decorator, Angular returns `null` which +means that the real type of any `@Optional` parameter will be `| null`. However, because decorators +cannot influence their types, there is a lot of existing code whose type is incorrect. The type is +fixed in `inject()` which can cause new compilation errors to show up. If you enable this option, +the migration will produce a non-null assertion after the `inject()` call to match the old type, +at the expense of potentially hiding type errors. + +**NOTE:** non-null assertions won't be added to parameters that are already typed to be nullable, +because the code that depends on them likely already accounts for their nullability. + +#### Before + +```typescript +import { Component, Inject, Optional } from '@angular/core'; +import { TOKEN_ONE, TOKEN_TWO } from './token'; + +@Component() +export class MyComp { + constructor( + @Inject(TOKEN_ONE) @Optional() private tokenOne: number, + @Inject(TOKEN_TWO) @Optional() private tokenTwo: string | null + ) {} +} +``` + +#### After + +```typescript +import { Component, inject } from '@angular/core'; +import { TOKEN_ONE, TOKEN_TWO } from './token'; + +@Component() +export class MyComp { + // Note the `!` at the end. + private tokenOne = inject(TOKEN_ONE, { optional: true })!; + + // Does not have `!` at the end, because the type was already nullable. + private tokenTwo = inject(TOKEN_TWO, { optional: true }); +} +``` diff --git a/adev-es/src/content/reference/migrations/inject-function.md b/adev-es/src/content/reference/migrations/inject-function.md index 357b2a9..acf170f 100644 --- a/adev-es/src/content/reference/migrations/inject-function.md +++ b/adev-es/src/content/reference/migrations/inject-function.md @@ -1,16 +1,16 @@ -# Migration to the `inject` function +# Migración a la función `inject` -Angular's `inject` function offers more accurate types and better compatibility with standard decorators, compared to constructor-based injection. +La función `inject` de Angular ofrece tipos más precisos y mejor compatibilidad con los decoradores estándar, en comparación con la inyección basada en constructor. -This schematic converts constructor-based injection in your classes to use the `inject` function instead. +Este schematic convierte la inyección basada en constructor en tus clases para usar la función `inject` en su lugar. -Run the schematic using the following command: +Ejecuta el schematic usando el siguiente comando: ```shell ng generate @angular/core:inject ``` -#### Before +#### Antes ```typescript import { Component, Inject, Optional } from '@angular/core'; @@ -26,7 +26,7 @@ export class MyComp { } ``` -#### After +#### Después ```typescript import { Component, inject } from '@angular/core'; @@ -40,31 +40,31 @@ export class MyComp { } ``` -## Migration options +## Opciones de migración -The migration includes several options to customize its output. +La migración incluye varias opciones para personalizar su salida. ### `path` -Determines which sub-path in your project should be migrated. Pass in `.` or leave it blank to -migrate the entire directory. +Determina qué sub-ruta de tu proyecto debe migrarse. Pasa `.` o déjalo en blanco para +migrar todo el directorio. ### `migrateAbstractClasses` -Angular doesn't validate that parameters of abstract classes are injectable. This means that the -migration can't reliably migrate them to `inject` without risking breakages which is why they're -disabled by default. Enable this option if you want abstract classes to be migrated, but note -that you may have to **fix some breakages manually**. +Angular no valida que los parámetros de las clases abstractas sean inyectables. Esto significa que la +migración no puede migrarlos de forma confiable a `inject` sin arriesgarse a errores, razón por la que están +deshabilitados por defecto. Habilita esta opción si quieres que las clases abstractas sean migradas, pero ten en cuenta +que es posible que tengas que **corregir algunos errores manualmente**. ### `backwardsCompatibleConstructors` -By default the migration tries to clean up the code as much as it can, which includes deleting -parameters from the constructor, or even the entire constructor if it doesn't include any code. -In some cases this can lead to compilation errors when classes with Angular decorators inherit from -other classes with Angular decorators. If you enable this option, the migration will generate an -additional constructor signature to keep it backwards compatible, at the expense of more code. +Por defecto, la migración intenta limpiar el código tanto como sea posible, lo que incluye eliminar +parámetros del constructor, o incluso el constructor completo si no incluye ningún código. +En algunos casos esto puede provocar errores de compilación cuando clases con decoradores de Angular heredan de +otras clases con decoradores de Angular. Si habilitas esta opción, la migración generará una +firma de constructor adicional para mantener la compatibilidad con versiones anteriores, a expensas de más código. -#### Before +#### Antes ```typescript import { Component } from '@angular/core'; @@ -76,7 +76,7 @@ export class MyComp { } ``` -#### After +#### Después ```typescript import { Component } from '@angular/core'; @@ -86,7 +86,7 @@ import { MyService } from './service'; export class MyComp { private service = inject(MyService); -/\*_ Inserted by Angular inject() migration for backwards compatibility _/ +/\*_ Insertado por la migración inject() de Angular para compatibilidad con versiones anteriores _/ constructor(...args: unknown[]); constructor() {} @@ -95,17 +95,17 @@ constructor() {} ### `nonNullableOptional` -If injection fails for a parameter with the `@Optional` decorator, Angular returns `null` which -means that the real type of any `@Optional` parameter will be `| null`. However, because decorators -cannot influence their types, there is a lot of existing code whose type is incorrect. The type is -fixed in `inject()` which can cause new compilation errors to show up. If you enable this option, -the migration will produce a non-null assertion after the `inject()` call to match the old type, -at the expense of potentially hiding type errors. +Si la inyección falla para un parámetro con el decorador `@Optional()`, Angular devuelve `null`, lo que +significa que el tipo real de cualquier parámetro `@Optional()` será `| null`. Sin embargo, debido a que los decoradores +no pueden influir en sus tipos, hay mucho código existente cuyo tipo es incorrecto. El tipo se +corrige en `inject()`, lo que puede provocar que aparezcan nuevos errores de compilación. Si habilitas esta opción, +la migración producirá una aserción non-null después de la llamada a `inject()` para coincidir con el tipo anterior, +a expensas de potencialmente ocultar errores de tipo. -**NOTE:** non-null assertions won't be added to parameters that are already typed to be nullable, -because the code that depends on them likely already accounts for their nullability. +**NOTA:** las aserciones non-null no se agregarán a parámetros que ya estén tipados como anulables, +porque el código que depende de ellos probablemente ya tiene en cuenta su anulabilidad. -#### Before +#### Antes ```typescript import { Component, Inject, Optional } from '@angular/core'; @@ -120,7 +120,7 @@ export class MyComp { } ``` -#### After +#### Después ```typescript import { Component, inject } from '@angular/core'; @@ -128,10 +128,10 @@ import { TOKEN_ONE, TOKEN_TWO } from './token'; @Component() export class MyComp { - // Note the `!` at the end. + // Nota el `!` al final. private tokenOne = inject(TOKEN_ONE, { optional: true })!; - // Does not have `!` at the end, because the type was already nullable. + // No tiene `!` al final, porque el tipo ya era anulable. private tokenTwo = inject(TOKEN_TWO, { optional: true }); } ``` diff --git a/adev-es/src/content/reference/migrations/module-with-providers.en.md b/adev-es/src/content/reference/migrations/module-with-providers.en.md new file mode 100644 index 0000000..256c87a --- /dev/null +++ b/adev-es/src/content/reference/migrations/module-with-providers.en.md @@ -0,0 +1,72 @@ +# `ModuleWithProviders` Migration + +## What does this schematic do? + +Some Angular libraries, such as `@angular/router` and `@ngrx/store`, implement APIs that return a type called `ModuleWithProviders` \(typically via a method named `forRoot()`\). +This type represents an `NgModule` along with additional providers. +Angular version 9 deprecates use of `ModuleWithProviders` without an explicitly generic type, where the generic type refers to the type of the `NgModule`. + +This schematic will add a generic type to any `ModuleWithProviders` usages that are missing the generic. +In the example below, the type of the `NgModule` is `SomeModule`, so the schematic changes the type to be `ModuleWithProviders`. + +### Before + + + +@NgModule({…}) +export class MyModule { + static forRoot(config: SomeConfig): ModuleWithProviders { + return { + ngModule: SomeModule, + providers: [ + {provide: SomeConfig, useValue: config} + ] + }; + } +} + + + +### After + + + +@NgModule({…}) +export class MyModule { + static forRoot(config: SomeConfig): ModuleWithProviders { + return { + ngModule: SomeModule, + providers: [ + {provide: SomeConfig, useValue: config } + ] + }; + } +} + + + +In the rare case that the schematic can't determine the type of `ModuleWithProviders`, you may see the schematic print a TODO comment to update the code manually. + +## Why is this migration necessary? + +`ModuleWithProviders` has had the generic type since Angular version 7, but it has been optional. +This has compiled because the `metadata.json` files contained all the metadata. +With Ivy, `metadata.json` files are no longer required, so the framework cannot assume that one with the necessary types has been provided. +Instead, Ivy relies on the generic type for `ModuleWithProviders` to get the correct type information. + +For this reason, Angular version 9 deprecates `ModuleWithProviders` without a generic type. +A future version of Angular will remove the default generic type, making an explicit type required. + +## Should I add the generic type when I add new `ModuleWithProviders` to my app? + +Yes, any time your code references the `ModuleWithProviders` type, it should have a generic type that matches the actual `NgModule` that is returned \(for example, `ModuleWithProviders`\). + +## What should I do if the schematic prints a TODO comment? + +The schematic will print a TODO comment in the event that it cannot detect the correct generic for the `ModuleWithProviders` type. +In this case, you'll want to manually add the correct generic to `ModuleWithProviders`. +It should match the type of whichever `NgModule` is returned in the `ModuleWithProviders` object. + +## What does this mean for libraries? + +Libraries should add the generic type to any usages of the `ModuleWithProviders` type. diff --git a/adev-es/src/content/reference/migrations/module-with-providers.md b/adev-es/src/content/reference/migrations/module-with-providers.md index 256c87a..5630072 100644 --- a/adev-es/src/content/reference/migrations/module-with-providers.md +++ b/adev-es/src/content/reference/migrations/module-with-providers.md @@ -1,15 +1,15 @@ -# `ModuleWithProviders` Migration +# Migración de `ModuleWithProviders` -## What does this schematic do? +## ¿Qué hace este schematic? -Some Angular libraries, such as `@angular/router` and `@ngrx/store`, implement APIs that return a type called `ModuleWithProviders` \(typically via a method named `forRoot()`\). -This type represents an `NgModule` along with additional providers. -Angular version 9 deprecates use of `ModuleWithProviders` without an explicitly generic type, where the generic type refers to the type of the `NgModule`. +Algunas librerías de Angular, como `@angular/router` y `@ngrx/store`, implementan APIs que devuelven un tipo llamado `ModuleWithProviders` \(típicamente a través de un método llamado `forRoot()`\). +Este tipo representa un `NgModule` junto con proveedores adicionales. +La versión 9 de Angular depreca el uso de `ModuleWithProviders` sin un tipo genérico explícito, donde el tipo genérico hace referencia al tipo del `NgModule`. -This schematic will add a generic type to any `ModuleWithProviders` usages that are missing the generic. -In the example below, the type of the `NgModule` is `SomeModule`, so the schematic changes the type to be `ModuleWithProviders`. +Este schematic agregará un tipo genérico a cualquier uso de `ModuleWithProviders` al que le falte el genérico. +En el ejemplo a continuación, el tipo del `NgModule` es `SomeModule`, por lo que el schematic cambia el tipo a `ModuleWithProviders`. -### Before +### Antes @@ -27,7 +27,7 @@ export class MyModule { -### After +### Después @@ -45,28 +45,28 @@ export class MyModule { -In the rare case that the schematic can't determine the type of `ModuleWithProviders`, you may see the schematic print a TODO comment to update the code manually. +En el raro caso de que el schematic no pueda determinar el tipo de `ModuleWithProviders`, es posible que veas que el schematic imprime un comentario TODO para actualizar el código manualmente. -## Why is this migration necessary? +## ¿Por qué es necesaria esta migración? -`ModuleWithProviders` has had the generic type since Angular version 7, but it has been optional. -This has compiled because the `metadata.json` files contained all the metadata. -With Ivy, `metadata.json` files are no longer required, so the framework cannot assume that one with the necessary types has been provided. -Instead, Ivy relies on the generic type for `ModuleWithProviders` to get the correct type information. +`ModuleWithProviders` ha tenido el tipo genérico desde la versión 7 de Angular, pero ha sido opcional. +Esto se compilaba porque los archivos `metadata.json` contenían todos los metadatos. +Con Ivy, los archivos `metadata.json` ya no son necesarios, por lo que el framework no puede asumir que se ha proporcionado uno con los tipos necesarios. +En cambio, Ivy se basa en el tipo genérico para `ModuleWithProviders` para obtener la información de tipo correcta. -For this reason, Angular version 9 deprecates `ModuleWithProviders` without a generic type. -A future version of Angular will remove the default generic type, making an explicit type required. +Por esta razón, la versión 9 de Angular depreca `ModuleWithProviders` sin un tipo genérico. +Una versión futura de Angular eliminará el tipo genérico predeterminado, haciendo obligatorio un tipo explícito. -## Should I add the generic type when I add new `ModuleWithProviders` to my app? +## ¿Debo agregar el tipo genérico cuando agregue nuevos `ModuleWithProviders` a mi aplicación? -Yes, any time your code references the `ModuleWithProviders` type, it should have a generic type that matches the actual `NgModule` that is returned \(for example, `ModuleWithProviders`\). +Sí, cada vez que tu código haga referencia al tipo `ModuleWithProviders`, debe tener un tipo genérico que coincida con el `NgModule` real que se devuelve \(por ejemplo, `ModuleWithProviders`\). -## What should I do if the schematic prints a TODO comment? +## ¿Qué debo hacer si el schematic imprime un comentario TODO? -The schematic will print a TODO comment in the event that it cannot detect the correct generic for the `ModuleWithProviders` type. -In this case, you'll want to manually add the correct generic to `ModuleWithProviders`. -It should match the type of whichever `NgModule` is returned in the `ModuleWithProviders` object. +El schematic imprimirá un comentario TODO en caso de que no pueda detectar el genérico correcto para el tipo `ModuleWithProviders`. +En este caso, querrás agregar manualmente el genérico correcto a `ModuleWithProviders`. +Debe coincidir con el tipo del `NgModule` que se devuelve en el objeto `ModuleWithProviders`. -## What does this mean for libraries? +## ¿Qué significa esto para las librerías? -Libraries should add the generic type to any usages of the `ModuleWithProviders` type. +Las librerías deben agregar el tipo genérico a cualquier uso del tipo `ModuleWithProviders`. diff --git a/adev-es/src/content/reference/migrations/ngclass-to-class.en.md b/adev-es/src/content/reference/migrations/ngclass-to-class.en.md new file mode 100644 index 0000000..df282a8 --- /dev/null +++ b/adev-es/src/content/reference/migrations/ngclass-to-class.en.md @@ -0,0 +1,41 @@ +# Migration from NgClass to class bindings + +This schematic migrates NgClass directive usages to class bindings in your application. +It will only migrate usages that are considered safe to migrate. + +Run the schematic using the following command: + +```bash +ng generate @angular/core:ngclass-to-class +``` + +#### Before + +```html +
+``` + +#### After + +```html +
+``` + +## Configuration options + +The migration supports a few options for fine tuning the migration to your specific needs. + +### `--migrate-space-separated-key` + +By default, the migration avoids migrating usages of `NgClass` in which object literal keys contain space-separated class names. +When the --migrate-space-separated-key flag is enabled, a binding is created for each individual key. + +```html +
+``` + +to + +```html +
+``` diff --git a/adev-es/src/content/reference/migrations/ngclass-to-class.md b/adev-es/src/content/reference/migrations/ngclass-to-class.md index df282a8..08ace3f 100644 --- a/adev-es/src/content/reference/migrations/ngclass-to-class.md +++ b/adev-es/src/content/reference/migrations/ngclass-to-class.md @@ -1,40 +1,40 @@ -# Migration from NgClass to class bindings +# Migración de NgClass a enlaces de clase -This schematic migrates NgClass directive usages to class bindings in your application. -It will only migrate usages that are considered safe to migrate. +Este schematic migra los usos de la directiva NgClass a enlaces de clase en tu aplicación. +Solo migrará los usos que se consideren seguros de migrar. -Run the schematic using the following command: +Ejecuta el schematic usando el siguiente comando: ```bash ng generate @angular/core:ngclass-to-class ``` -#### Before +#### Antes ```html
``` -#### After +#### Después ```html
``` -## Configuration options +## Opciones de configuración -The migration supports a few options for fine tuning the migration to your specific needs. +La migración admite algunas opciones para ajustar la migración a tus necesidades específicas. ### `--migrate-space-separated-key` -By default, the migration avoids migrating usages of `NgClass` in which object literal keys contain space-separated class names. -When the --migrate-space-separated-key flag is enabled, a binding is created for each individual key. +Por defecto, la migración evita migrar los usos de `NgClass` en los que las claves de los literales de objeto contienen nombres de clase separados por espacios. +Cuando la bandera `--migrate-space-separated-key` está habilitada, se crea un enlace para cada clave individual. ```html
``` -to +a ```html
diff --git a/adev-es/src/content/reference/migrations/ngstyle-to-style.en.md b/adev-es/src/content/reference/migrations/ngstyle-to-style.en.md new file mode 100644 index 0000000..223055a --- /dev/null +++ b/adev-es/src/content/reference/migrations/ngstyle-to-style.en.md @@ -0,0 +1,42 @@ +# Migration from NgStyle to style bindings + +This schematic migrates NgStyle directive usages to style bindings in your application. +It will only migrate usages that are considered safe to migrate. + +Run the schematic using the following command: + +```bash +ng generate @angular/core:ngstyle-to-style +``` + +#### Before + +```html +
+``` + +#### After + +```html +
+``` + +## Configuration options + +The migration supports a few options for fine tuning the migration to your specific needs. + +### `--best-effort-mode` + +By default, the migration avoids migrating object references usages of `NgStyle` +When the `--best-effort-mode` flag is enabled, `ngStyle` instances binded to object references are also migrated. +This can be unsafe to migrate, for example if the binded object is mutated. + +```html +
+``` + +to + +```html +
+``` diff --git a/adev-es/src/content/reference/migrations/ngstyle-to-style.md b/adev-es/src/content/reference/migrations/ngstyle-to-style.md index 223055a..c7fb577 100644 --- a/adev-es/src/content/reference/migrations/ngstyle-to-style.md +++ b/adev-es/src/content/reference/migrations/ngstyle-to-style.md @@ -1,41 +1,41 @@ -# Migration from NgStyle to style bindings +# Migración de NgStyle a enlaces de estilo -This schematic migrates NgStyle directive usages to style bindings in your application. -It will only migrate usages that are considered safe to migrate. +Este schematic migra los usos de la directiva NgStyle a enlaces de estilo en tu aplicación. +Solo migrará los usos que se consideren seguros de migrar. -Run the schematic using the following command: +Ejecuta el schematic usando el siguiente comando: ```bash ng generate @angular/core:ngstyle-to-style ``` -#### Before +#### Antes ```html
``` -#### After +#### Después ```html
``` -## Configuration options +## Opciones de configuración -The migration supports a few options for fine tuning the migration to your specific needs. +La migración admite algunas opciones para ajustar la migración a tus necesidades específicas. ### `--best-effort-mode` -By default, the migration avoids migrating object references usages of `NgStyle` -When the `--best-effort-mode` flag is enabled, `ngStyle` instances binded to object references are also migrated. -This can be unsafe to migrate, for example if the binded object is mutated. +Por defecto, la migración evita migrar los usos de referencias de objetos de `NgStyle`. +Cuando la bandera `--best-effort-mode` está habilitada, las instancias de `ngStyle` vinculadas a referencias de objetos también se migran. +Esto puede ser inseguro de migrar, por ejemplo si el objeto vinculado es mutado. ```html
``` -to +a ```html
diff --git a/adev-es/src/content/reference/migrations/outputs.en.md b/adev-es/src/content/reference/migrations/outputs.en.md new file mode 100644 index 0000000..3bd6d99 --- /dev/null +++ b/adev-es/src/content/reference/migrations/outputs.en.md @@ -0,0 +1,96 @@ +# Migration to output function + +Angular introduced an improved API for outputs in v17.3 that is considered +production ready as of v19. This API mimics the `input()` API but is not based on Signals. +Read more about custom events output function and its benefits in the [dedicated guide](guide/components/outputs). + +To support existing projects that would like to use output function, the Angular team +provides an automated migration that converts `@Output` custom events to the new `output()` API. + +Run the schematic using the following command: + +```bash +ng generate @angular/core:output-migration +``` + +## What does the migration change? + +1. `@Output()` class members are updated to their `output()` equivalent. +2. Imports in the file of components or directives, at Typescript module level, are updated as well. +3. Migrates the APIs functions like `event.next()`, which use is not recommended, to `event.emit()` and removes `event.complete()` calls. + +**Before** + +```typescript +import {Component, Output, EventEmitter} from '@angular/core'; + +@Component({ + template: `` +}) +export class MyComponent { + @Output() someChange = new EventEmitter(); + + someMethod(value: string): void { + this.someChange.emit(value); + } +} +``` + +**After** + +```typescript +import {Component, output} from '@angular/core'; + +@Component({ + template: `` +}) +export class MyComponent { + readonly someChange = output(); + + someMethod(value: string): void { + this.someChange.emit(value); + } +} +``` + +## Configuration options + +The migration supports a few options for fine tuning the migration to your specific needs. + +### `--path` + +If not specified, the migration will ask you for a path and update your whole Angular CLI workspace. +You can limit the migration to a specific sub-directory using this option. + +### `--analysis-dir` + +In large projects you may use this option to reduce the amount of files being analyzed. +By default, the migration analyzes the whole workspace, regardless of the `--path` option, in +order to update all references affected by an `@Output()` migration. + +With this option, you can limit analysis to a sub-folder. Note that this means that any +references outside this directory are silently skipped, potentially breaking your build. + +Use these options as shown below: + +```bash +ng generate @angular/core:output-migration --path src/app/sub-folder +``` + +## Exceptions + +In some cases, the migration will not touch the code. +One of these exceptions is the case where the event is used with a `pipe()` method. +The following code won't be migrated: + +```typescript +export class MyDialogComponent { + @Output() close = new EventEmitter(); + doSome(): void { + this.close.complete(); + } + otherThing(): void { + this.close.pipe(); + } +} +``` diff --git a/adev-es/src/content/reference/migrations/outputs.md b/adev-es/src/content/reference/migrations/outputs.md index 3bd6d99..98d165a 100644 --- a/adev-es/src/content/reference/migrations/outputs.md +++ b/adev-es/src/content/reference/migrations/outputs.md @@ -1,25 +1,25 @@ -# Migration to output function +# Migración a la función output -Angular introduced an improved API for outputs in v17.3 that is considered -production ready as of v19. This API mimics the `input()` API but is not based on Signals. -Read more about custom events output function and its benefits in the [dedicated guide](guide/components/outputs). +Angular introdujo una API mejorada para salidas (outputs) en v17.3 que se considera +lista para producción desde v19. Esta API imita la API `input()` pero no está basada en Signals. +Lee más sobre la función output de eventos personalizados y sus beneficios en la [guía dedicada](guide/components/outputs). -To support existing projects that would like to use output function, the Angular team -provides an automated migration that converts `@Output` custom events to the new `output()` API. +Para apoyar a los proyectos existentes que deseen usar la función output, el equipo de Angular +proporciona una migración automatizada que convierte los eventos personalizados `@Output` a la nueva API `output()`. -Run the schematic using the following command: +Ejecuta el schematic usando el siguiente comando: ```bash ng generate @angular/core:output-migration ``` -## What does the migration change? +## ¿Qué cambia la migración? -1. `@Output()` class members are updated to their `output()` equivalent. -2. Imports in the file of components or directives, at Typescript module level, are updated as well. -3. Migrates the APIs functions like `event.next()`, which use is not recommended, to `event.emit()` and removes `event.complete()` calls. +1. Los miembros de clase `@Output()` se actualizan a su equivalente `output()`. +2. Las importaciones en el archivo de componentes o directivas, a nivel de módulo TypeScript, también se actualizan. +3. Migra las funciones de las APIs como `event.next()`, cuyo uso no se recomienda, a `event.emit()` y elimina las llamadas a `event.complete()`. -**Before** +**Antes** ```typescript import {Component, Output, EventEmitter} from '@angular/core'; @@ -36,7 +36,7 @@ export class MyComponent { } ``` -**After** +**Después** ```typescript import {Component, output} from '@angular/core'; @@ -53,35 +53,35 @@ export class MyComponent { } ``` -## Configuration options +## Opciones de configuración -The migration supports a few options for fine tuning the migration to your specific needs. +La migración admite algunas opciones para ajustar la migración a tus necesidades específicas. ### `--path` -If not specified, the migration will ask you for a path and update your whole Angular CLI workspace. -You can limit the migration to a specific sub-directory using this option. +Si no se especifica, la migración te pedirá una ruta y actualizará todo tu espacio de trabajo de Angular CLI. +Puedes limitar la migración a un subdirectorio específico usando esta opción. ### `--analysis-dir` -In large projects you may use this option to reduce the amount of files being analyzed. -By default, the migration analyzes the whole workspace, regardless of the `--path` option, in -order to update all references affected by an `@Output()` migration. +En proyectos grandes puedes usar esta opción para reducir la cantidad de archivos que se analizan. +Por defecto, la migración analiza todo el espacio de trabajo, independientemente de la opción `--path`, para +actualizar todas las referencias afectadas por una migración de `@Output()`. -With this option, you can limit analysis to a sub-folder. Note that this means that any -references outside this directory are silently skipped, potentially breaking your build. +Con esta opción, puedes limitar el análisis a una subcarpeta. Ten en cuenta que esto significa que cualquier +referencia fuera de este directorio se omite silenciosamente, lo que podría romper tu compilación. -Use these options as shown below: +Usa estas opciones como se muestra a continuación: ```bash ng generate @angular/core:output-migration --path src/app/sub-folder ``` -## Exceptions +## Excepciones -In some cases, the migration will not touch the code. -One of these exceptions is the case where the event is used with a `pipe()` method. -The following code won't be migrated: +En algunos casos, la migración no tocará el código. +Una de estas excepciones es el caso donde el evento se usa con el método `pipe()`. +El siguiente código no será migrado: ```typescript export class MyDialogComponent { diff --git a/adev-es/src/content/reference/migrations/overview.en.md b/adev-es/src/content/reference/migrations/overview.en.md new file mode 100644 index 0000000..026e27d --- /dev/null +++ b/adev-es/src/content/reference/migrations/overview.en.md @@ -0,0 +1,45 @@ +# Migrations + +Learn about how you can migrate your existing angular project to the latest features incrementally. + + + + Standalone components provide a simplified way to build Angular applications. Standalone components specify their dependencies directly instead of getting them through NgModules. + + + Built-in Control Flow Syntax allows you to use more ergonomic syntax which is close to JavaScript and has better type checking. It replaces the need to import `CommonModule` to use functionality like `*ngFor`, `*ngIf` and `*ngSwitch`. + + + Angular's `inject` function offers more accurate types and better compatibility with standard decorators, compared to constructor-based injection. + + + Convert eagerly loaded component routes to lazy loaded ones. This allows the build process to split production bundles into smaller chunks, to load less JavaScript at initial page load. + + + Convert existing `@Input` fields to the new signal input API that is now production ready. + + + Convert existing `@Output` custom events to the new output function that is now production ready. + + + Convert existing decorator query fields to the improved signal queries API. The API is now production ready. + + + Clean up unused imports in your project. + + + Convert component templates to use self-closing tags where possible. + + + Convert component templates to prefer class bindings over the `NgClass` directives when possible. + + + Convert component templates to prefer style bindings over the `NgStyle` directives when possible. + + + Convert `RouterTestingModule` usages to `RouterModule` in TestBed configurations and add `provideLocationMocks()` when appropriate. + + + Replace imports of the `CommonModule` with imports of the individual directives and pipes used in the templates when possible. + + diff --git a/adev-es/src/content/reference/migrations/overview.md b/adev-es/src/content/reference/migrations/overview.md index 026e27d..620d91d 100644 --- a/adev-es/src/content/reference/migrations/overview.md +++ b/adev-es/src/content/reference/migrations/overview.md @@ -1,45 +1,45 @@ -# Migrations +# Migraciones -Learn about how you can migrate your existing angular project to the latest features incrementally. +Aprende cómo puedes migrar tu proyecto Angular existente a las últimas características de forma incremental. - - Standalone components provide a simplified way to build Angular applications. Standalone components specify their dependencies directly instead of getting them through NgModules. + + Los componentes standalone ofrecen una forma simplificada de construir aplicaciones Angular. Los componentes standalone especifican sus dependencias directamente en lugar de obtenerlas a través de NgModules. - - Built-in Control Flow Syntax allows you to use more ergonomic syntax which is close to JavaScript and has better type checking. It replaces the need to import `CommonModule` to use functionality like `*ngFor`, `*ngIf` and `*ngSwitch`. + + La sintaxis de flujo de control integrada te permite usar una sintaxis más ergonómica que es cercana a JavaScript y tiene mejor verificación de tipos. Reemplaza la necesidad de importar `CommonModule` para usar funcionalidades como `*ngFor`, `*ngIf` y `*ngSwitch`. - - Angular's `inject` function offers more accurate types and better compatibility with standard decorators, compared to constructor-based injection. + + La función `inject` de Angular ofrece tipos más precisos y mejor compatibilidad con los decoradores estándar, en comparación con la inyección basada en constructor. - - Convert eagerly loaded component routes to lazy loaded ones. This allows the build process to split production bundles into smaller chunks, to load less JavaScript at initial page load. + + Convierte rutas de componentes cargadas de forma eager a rutas con lazy loading. Esto permite que el proceso de compilación divida los bundles de producción en fragmentos más pequeños, para cargar menos JavaScript en la carga inicial de la página. - - Convert existing `@Input` fields to the new signal input API that is now production ready. + + Convierte los campos `@Input` existentes a la nueva API de signal input que ya está lista para producción. - - Convert existing `@Output` custom events to the new output function that is now production ready. + + Convierte los eventos personalizados `@Output` existentes a la nueva función output que ya está lista para producción. - - Convert existing decorator query fields to the improved signal queries API. The API is now production ready. + + Convierte los campos de consulta de decoradores existentes a la API mejorada de signal queries. La API ya está lista para producción. - - Clean up unused imports in your project. + + Limpia las importaciones no utilizadas en tu proyecto. - - Convert component templates to use self-closing tags where possible. + + Convierte las plantillas de componentes para usar etiquetas auto-cerrables donde sea posible. - - Convert component templates to prefer class bindings over the `NgClass` directives when possible. + + Convierte las plantillas de componentes para preferir los enlaces de clase sobre las directivas `NgClass` cuando sea posible. - - Convert component templates to prefer style bindings over the `NgStyle` directives when possible. + + Convierte las plantillas de componentes para preferir los enlaces de estilo sobre las directivas `NgStyle` cuando sea posible. - - Convert `RouterTestingModule` usages to `RouterModule` in TestBed configurations and add `provideLocationMocks()` when appropriate. + + Convierte los usos de `RouterTestingModule` a `RouterModule` en configuraciones de TestBed y agrega `provideLocationMocks()` cuando sea apropiado. - - Replace imports of the `CommonModule` with imports of the individual directives and pipes used in the templates when possible. + + Reemplaza las importaciones de `CommonModule` con importaciones de las directivas y pipes individuales utilizados en las plantillas cuando sea posible. diff --git a/adev-es/src/content/reference/migrations/route-lazy-loading.en.md b/adev-es/src/content/reference/migrations/route-lazy-loading.en.md new file mode 100644 index 0000000..66db020 --- /dev/null +++ b/adev-es/src/content/reference/migrations/route-lazy-loading.en.md @@ -0,0 +1,71 @@ +# Migration to lazy-loaded routes + +This schematic helps developers to convert eagerly loaded component routes to lazy loaded routes. This allows the build process to split the production bundle into smaller chunks, to avoid big JS bundle that includes all routes, which negatively affects initial page load of an application. + +Run the schematic using the following command: + +```shell +ng generate @angular/core:route-lazy-loading +``` + +### `path` config option + +By default, migration will go over the entire application. If you want to apply this migration to a subset of the files, you can pass the path argument as shown below: + +```shell +ng generate @angular/core:route-lazy-loading --path src/app/sub-component +``` + +The value of the path parameter is a relative path within the project. + +### How does it work? + +The schematic will attempt to find all the places where the application routes as defined: + +- `RouterModule.forRoot` and `RouterModule.forChild` +- `Router.resetConfig` +- `provideRouter` +- `provideRoutes` +- variables of type `Routes` or `Route[]` (e.g. `const routes: Routes = [{...}]`) + +The migration will check all the components in the routes, check if they are standalone and eagerly loaded, and if so, it will convert them to lazy loaded routes. + +#### Before + +```typescript +// app.module.ts +import {HomeComponent} from './home/home.component'; + +@NgModule({ + imports: [ + RouterModule.forRoot([ + { + path: 'home', + // HomeComponent is standalone and eagerly loaded + component: HomeComponent, + }, + ]), + ], +}) +export class AppModule {} +``` + +#### After + +```typescript +// app.module.ts +@NgModule({ + imports: [ + RouterModule.forRoot([ + { + path: 'home', + // ↓ HomeComponent is now lazy loaded + loadComponent: () => import('./home/home.component').then(m => m.HomeComponent), + }, + ]), + ], +}) +export class AppModule {} +``` + +This migration will also collect information about all the components declared in NgModules and output the list of routes that use them (including corresponding location of the file). Consider making those components standalone and run this migration again. You can use an existing migration ([see](reference/migrations/standalone)) to convert those components to standalone. diff --git a/adev-es/src/content/reference/migrations/route-lazy-loading.md b/adev-es/src/content/reference/migrations/route-lazy-loading.md index 66db020..cdb035b 100644 --- a/adev-es/src/content/reference/migrations/route-lazy-loading.md +++ b/adev-es/src/content/reference/migrations/route-lazy-loading.md @@ -1,36 +1,36 @@ -# Migration to lazy-loaded routes +# Migración a rutas con lazy loading -This schematic helps developers to convert eagerly loaded component routes to lazy loaded routes. This allows the build process to split the production bundle into smaller chunks, to avoid big JS bundle that includes all routes, which negatively affects initial page load of an application. +Este schematic ayuda a los desarrolladores a convertir rutas de componentes cargadas de forma eager a rutas con lazy loading. Esto permite que el proceso de compilación divida el bundle de producción en fragmentos más pequeños, para evitar un bundle JS grande que incluya todas las rutas, lo que afecta negativamente la carga inicial de la página de una aplicación. -Run the schematic using the following command: +Ejecuta el schematic usando el siguiente comando: ```shell ng generate @angular/core:route-lazy-loading ``` -### `path` config option +### Opción de configuración `path` -By default, migration will go over the entire application. If you want to apply this migration to a subset of the files, you can pass the path argument as shown below: +Por defecto, la migración recorrerá toda la aplicación. Si quieres aplicar esta migración a un subconjunto de los archivos, puedes pasar el argumento path como se muestra a continuación: ```shell ng generate @angular/core:route-lazy-loading --path src/app/sub-component ``` -The value of the path parameter is a relative path within the project. +El valor del parámetro path es una ruta relativa dentro del proyecto. -### How does it work? +### ¿Cómo funciona? -The schematic will attempt to find all the places where the application routes as defined: +El schematic intentará encontrar todos los lugares donde se definen las rutas de la aplicación: -- `RouterModule.forRoot` and `RouterModule.forChild` +- `RouterModule.forRoot` y `RouterModule.forChild` - `Router.resetConfig` - `provideRouter` - `provideRoutes` -- variables of type `Routes` or `Route[]` (e.g. `const routes: Routes = [{...}]`) +- variables de tipo `Routes` o `Route[]` (por ejemplo, `const routes: Routes = [{...}]`) -The migration will check all the components in the routes, check if they are standalone and eagerly loaded, and if so, it will convert them to lazy loaded routes. +La migración verificará todos los componentes en las rutas, comprobará si son standalone y están cargados de forma eager, y en ese caso los convertirá a rutas con lazy loading. -#### Before +#### Antes ```typescript // app.module.ts @@ -41,7 +41,7 @@ import {HomeComponent} from './home/home.component'; RouterModule.forRoot([ { path: 'home', - // HomeComponent is standalone and eagerly loaded + // HomeComponent es standalone y está cargado de forma eager component: HomeComponent, }, ]), @@ -50,7 +50,7 @@ import {HomeComponent} from './home/home.component'; export class AppModule {} ``` -#### After +#### Después ```typescript // app.module.ts @@ -59,7 +59,7 @@ export class AppModule {} RouterModule.forRoot([ { path: 'home', - // ↓ HomeComponent is now lazy loaded + // ↓ HomeComponent ahora se carga de forma diferida loadComponent: () => import('./home/home.component').then(m => m.HomeComponent), }, ]), @@ -68,4 +68,4 @@ export class AppModule {} export class AppModule {} ``` -This migration will also collect information about all the components declared in NgModules and output the list of routes that use them (including corresponding location of the file). Consider making those components standalone and run this migration again. You can use an existing migration ([see](reference/migrations/standalone)) to convert those components to standalone. +Esta migración también recopilará información sobre todos los componentes declarados en NgModules y mostrará la lista de rutas que los usan (incluida la ubicación correspondiente del archivo). Considera hacer esos componentes standalone y ejecutar esta migración nuevamente. Puedes usar una migración existente ([consulta](reference/migrations/standalone)) para convertir esos componentes a standalone. diff --git a/adev-es/src/content/reference/migrations/router-testing-module-migration.en.md b/adev-es/src/content/reference/migrations/router-testing-module-migration.en.md new file mode 100644 index 0000000..4cf969e --- /dev/null +++ b/adev-es/src/content/reference/migrations/router-testing-module-migration.en.md @@ -0,0 +1,103 @@ +# RouterTestingModule migration + +This schematic migrates usages of `RouterTestingModule` inside tests to `RouterModule`. + +When a test imports `SpyLocation` from `@angular/common/testing` and uses `urlChanges` property , the schematic will also add `provideLocationMocks()` to preserve the original behavior. + +Run the schematic with: + +```shell +ng generate @angular/core:router-testing-module-migration +``` + +## Options + +| Option | Details | +| :----- | :---------------------------------------------------------------------------------------------------------------------------- | +| `path` | The path (relative to project root) to migrate. Defaults to `./`. Use this to incrementally migrate a subset of your project. | + +## Examples + +### Preserve router options + +Before: + +```ts +import { RouterTestingModule } from '@angular/router/testing'; +import { SpyLocation } from '@angular/common/testing'; + +describe('test', () => { + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [RouterTestingModule.withRoutes(routes, { initialNavigation: 'enabledBlocking' })] + }); + }); + +}); +``` + +After: + +```ts +import { RouterModule } from '@angular/router'; +import { SpyLocation } from '@angular/common/testing'; + +describe('test', () => { + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [RouterModule.forRoot(routes, { initialNavigation: 'enabledBlocking' })] + }); + }); + +}); +``` + +### Add provideLocationMocks when `SpyLocation` is imported and `urlChanges` is used + +Before: + +```ts +import { RouterTestingModule } from '@angular/router/testing'; +import { SpyLocation } from '@angular/common/testing'; + +describe('test', () => { + let spy : SpyLocation; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [RouterTestingModule] + }); + spy = TestBed.inject(SpyLocation); + }); + + it('Awesome test', () => { + expect(spy.urlChanges).toBeDefined() + }) +}); +``` + +After: + +```ts +import { RouterModule } from '@angular/router'; +import { provideLocationMocks } from '@angular/common/testing'; +import { SpyLocation } from '@angular/common/testing'; + +describe('test', () => { + let spy : SpyLocation; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [RouterModule], + providers: [provideLocationMocks()] + }); + spy = TestBed.inject(SpyLocation); + }); + + it('Awesome test', () => { + expect(spy.urlChanges).toBeDefined() + }) +}); +``` diff --git a/adev-es/src/content/reference/migrations/router-testing-module-migration.md b/adev-es/src/content/reference/migrations/router-testing-module-migration.md index 4cf969e..17d697b 100644 --- a/adev-es/src/content/reference/migrations/router-testing-module-migration.md +++ b/adev-es/src/content/reference/migrations/router-testing-module-migration.md @@ -1,26 +1,26 @@ -# RouterTestingModule migration +# Migración de RouterTestingModule -This schematic migrates usages of `RouterTestingModule` inside tests to `RouterModule`. +Este schematic migra los usos de `RouterTestingModule` dentro de las pruebas a `RouterModule`. -When a test imports `SpyLocation` from `@angular/common/testing` and uses `urlChanges` property , the schematic will also add `provideLocationMocks()` to preserve the original behavior. +Cuando una prueba importa `SpyLocation` de `@angular/common/testing` y usa la propiedad `urlChanges`, el schematic también agregará `provideLocationMocks()` para preservar el comportamiento original. -Run the schematic with: +Ejecuta el schematic con: ```shell ng generate @angular/core:router-testing-module-migration ``` -## Options +## Opciones -| Option | Details | -| :----- | :---------------------------------------------------------------------------------------------------------------------------- | -| `path` | The path (relative to project root) to migrate. Defaults to `./`. Use this to incrementally migrate a subset of your project. | +| Opción | Detalles | +| :----- | :----------------------------------------------------------------------------------------------------------------------------------------- | +| `path` | La ruta (relativa a la raíz del proyecto) a migrar. Por defecto es `./`. Úsala para migrar de forma incremental un subconjunto de tu proyecto. | -## Examples +## Ejemplos -### Preserve router options +### Preservar opciones del router -Before: +Antes: ```ts import { RouterTestingModule } from '@angular/router/testing'; @@ -37,7 +37,7 @@ describe('test', () => { }); ``` -After: +Después: ```ts import { RouterModule } from '@angular/router'; @@ -54,9 +54,9 @@ describe('test', () => { }); ``` -### Add provideLocationMocks when `SpyLocation` is imported and `urlChanges` is used +### Agregar provideLocationMocks cuando se importa `SpyLocation` y se usa `urlChanges` -Before: +Antes: ```ts import { RouterTestingModule } from '@angular/router/testing'; @@ -78,7 +78,7 @@ describe('test', () => { }); ``` -After: +Después: ```ts import { RouterModule } from '@angular/router'; diff --git a/adev-es/src/content/reference/migrations/self-closing-tags.en.md b/adev-es/src/content/reference/migrations/self-closing-tags.en.md new file mode 100644 index 0000000..255a5d3 --- /dev/null +++ b/adev-es/src/content/reference/migrations/self-closing-tags.en.md @@ -0,0 +1,27 @@ +# Migration to self-closing tags + +Self-closing tags are supported in Angular templates since [v16](https://blog.angular.dev/angular-v16-is-here-4d7a28ec680d#7065). . + +This schematic migrates the templates in your application to use self-closing tags. + +Run the schematic using the following command: + +```shell +ng generate @angular/core:self-closing-tag +``` + +#### Before + + + + + + + +#### After + + + + + + diff --git a/adev-es/src/content/reference/migrations/self-closing-tags.md b/adev-es/src/content/reference/migrations/self-closing-tags.md index 255a5d3..fb0f525 100644 --- a/adev-es/src/content/reference/migrations/self-closing-tags.md +++ b/adev-es/src/content/reference/migrations/self-closing-tags.md @@ -1,16 +1,16 @@ -# Migration to self-closing tags +# Migración a etiquetas auto-cerrables -Self-closing tags are supported in Angular templates since [v16](https://blog.angular.dev/angular-v16-is-here-4d7a28ec680d#7065). . +Las etiquetas auto-cerrables son compatibles con las plantillas de Angular desde [v16](https://blog.angular.dev/angular-v16-is-here-4d7a28ec680d#7065). -This schematic migrates the templates in your application to use self-closing tags. +Este schematic migra las plantillas de tu aplicación para usar etiquetas auto-cerrables. -Run the schematic using the following command: +Ejecuta el schematic usando el siguiente comando: ```shell ng generate @angular/core:self-closing-tag ``` -#### Before +#### Antes @@ -18,7 +18,7 @@ ng generate @angular/core:self-closing-tag -#### After +#### Después diff --git a/adev-es/src/content/reference/migrations/signal-inputs.en.md b/adev-es/src/content/reference/migrations/signal-inputs.en.md new file mode 100644 index 0000000..c92d329 --- /dev/null +++ b/adev-es/src/content/reference/migrations/signal-inputs.en.md @@ -0,0 +1,116 @@ +# Migration to signal inputs + +Angular introduced an improved API for inputs that is considered +production ready as of v19. +Read more about signal inputs and their benefits in the [dedicated guide](guide/signals/inputs). + +To support existing teams that would like to use signal inputs, the Angular team +provides an automated migration that converts `@Input` fields to the new `input()` API. + +Run the schematic using the following command: + +```bash +ng generate @angular/core:signal-input-migration +``` + +Alternatively, the migration is available as a [code refactor action](https://code.visualstudio.com/docs/typescript/typescript-refactoring#_refactoring) in VSCode. +Install the latest version of the VSCode extension and click on an `@Input` field. +See more details in the section [below](#vscode-extension). + +## What does the migration change? + +1. `@Input()` class members are updated to their signal `input()` equivalent. +2. References to migrated inputs are updated to call the signal. + - This includes references in templates, host bindings or TypeScript code. + +**Before** + +```typescript +import {Component, Input} from '@angular/core'; + +@Component({ + template: `Name: {{name ?? ''}}` +}) +export class MyComponent { + @Input() name: string|undefined = undefined; + + someMethod(): number { + if (this.name) { + return this.name.length; + } + return -1; + } +} +``` + +**After** + + +import {Component, input} from '@angular/core'; + +@Component({ +template: `Name: {{name() ?? ''}}` +}) +export class MyComponent { +readonly name = input(); + +someMethod(): number { +const name = this.name(); +if (name) { +return name.length; +} +return -1; +} +} + + +## Configuration options + +The migration supports a few options for fine tuning the migration to your specific needs. + +### `--path` + +By default, the migration will update your whole Angular CLI workspace. +You can limit the migration to a specific sub-directory using this option. + +### `--best-effort-mode` + +By default, the migration skips inputs that cannot be safely migrated. +The migration tries to refactor code as safely as possible. + +When the `--best-effort-mode` flag is enabled, the migration eagerly +tries to migrate as much as possible, even if it could break your build. + +### `--insert-todos` + +When enabled, the migration will add TODOs to inputs that couldn't be migrated. +The TODOs will include reasoning on why inputs were skipped. E.g. + +```ts +// TODO: Skipped for migration because: +// Your application code writes to the input. This prevents migration. +@Input() myInput = false; +``` + +### `--analysis-dir` + +In large projects you may use this option to reduce the amount of files being analyzed. +By default, the migration analyzes the whole workspace, regardless of the `--path` option, in +order to update all references affected by an `@Input()` migration. + +With this option, you can limit analysis to a sub-folder. Note that this means that any +references outside this directory are silently skipped, potentially breaking your build. + +## VSCode extension + +![Screenshot of the VSCode extension and clicking on an `@Input` field](assets/images/migrations/signal-inputs-vscode.png 'Screenshot of the VSCode extension and clicking on an `@Input` field.') + +The migration is available as a [code refactor action](https://code.visualstudio.com/docs/typescript/typescript-refactoring#_refactoring) in VSCode. + +To make use of the migration via VSCode, install the latest version of the VSCode extension and either click: + +- on a `@Input` field. +- or, on a directive/component + +Then, wait for the yellow lightbulb VSCode refactoring button to appear. +Via this button you can then select the signal input migration. diff --git a/adev-es/src/content/reference/migrations/signal-inputs.md b/adev-es/src/content/reference/migrations/signal-inputs.md index c92d329..aa4c7ca 100644 --- a/adev-es/src/content/reference/migrations/signal-inputs.md +++ b/adev-es/src/content/reference/migrations/signal-inputs.md @@ -1,29 +1,29 @@ -# Migration to signal inputs +# Migración a signal inputs -Angular introduced an improved API for inputs that is considered -production ready as of v19. -Read more about signal inputs and their benefits in the [dedicated guide](guide/signals/inputs). +Angular introdujo una API mejorada para entradas (inputs) que se considera +lista para producción desde v19. +Lee más sobre los signal inputs y sus beneficios en la [guía dedicada](guide/signals/inputs). -To support existing teams that would like to use signal inputs, the Angular team -provides an automated migration that converts `@Input` fields to the new `input()` API. +Para apoyar a los equipos existentes que deseen usar signal inputs, el equipo de Angular +proporciona una migración automatizada que convierte los campos `@Input` a la nueva API `input()`. -Run the schematic using the following command: +Ejecuta el schematic usando el siguiente comando: ```bash ng generate @angular/core:signal-input-migration ``` -Alternatively, the migration is available as a [code refactor action](https://code.visualstudio.com/docs/typescript/typescript-refactoring#_refactoring) in VSCode. -Install the latest version of the VSCode extension and click on an `@Input` field. -See more details in the section [below](#vscode-extension). +Alternativamente, la migración está disponible como una [acción de refactorización de código](https://code.visualstudio.com/docs/typescript/typescript-refactoring#_refactoring) en VSCode. +Instala la última versión de la extensión de VSCode y haz clic en un campo `@Input`. +Consulta más detalles en la sección [a continuación](#extensión-de-vscode). -## What does the migration change? +## ¿Qué cambia la migración? -1. `@Input()` class members are updated to their signal `input()` equivalent. -2. References to migrated inputs are updated to call the signal. - - This includes references in templates, host bindings or TypeScript code. +1. Los miembros de clase `@Input()` se actualizan a su equivalente signal `input()`. +2. Las referencias a las entradas migradas se actualizan para llamar al signal. + - Esto incluye referencias en plantillas, host bindings o código TypeScript. -**Before** +**Antes** ```typescript import {Component, Input} from '@angular/core'; @@ -43,7 +43,7 @@ export class MyComponent { } ``` -**After** +**Después** import {Component, input} from '@angular/core'; @@ -64,27 +64,27 @@ return -1; } -## Configuration options +## Opciones de configuración -The migration supports a few options for fine tuning the migration to your specific needs. +La migración admite algunas opciones para ajustar la migración a tus necesidades específicas. ### `--path` -By default, the migration will update your whole Angular CLI workspace. -You can limit the migration to a specific sub-directory using this option. +Por defecto, la migración actualizará todo tu espacio de trabajo de Angular CLI. +Puedes limitar la migración a un subdirectorio específico usando esta opción. ### `--best-effort-mode` -By default, the migration skips inputs that cannot be safely migrated. -The migration tries to refactor code as safely as possible. +Por defecto, la migración omite entradas que no se pueden migrar de forma segura. +La migración intenta refactorizar el código de la forma más segura posible. -When the `--best-effort-mode` flag is enabled, the migration eagerly -tries to migrate as much as possible, even if it could break your build. +Cuando la bandera `--best-effort-mode` está habilitada, la migración intenta de forma agresiva +migrar tanto como sea posible, incluso si pudiera romper tu compilación. ### `--insert-todos` -When enabled, the migration will add TODOs to inputs that couldn't be migrated. -The TODOs will include reasoning on why inputs were skipped. E.g. +Cuando está habilitado, la migración agregará TODOs a las entradas que no pudieron migrarse. +Los TODOs incluirán el razonamiento de por qué se omitieron las entradas. Por ejemplo: ```ts // TODO: Skipped for migration because: @@ -94,23 +94,23 @@ The TODOs will include reasoning on why inputs were skipped. E.g. ### `--analysis-dir` -In large projects you may use this option to reduce the amount of files being analyzed. -By default, the migration analyzes the whole workspace, regardless of the `--path` option, in -order to update all references affected by an `@Input()` migration. +En proyectos grandes puedes usar esta opción para reducir la cantidad de archivos que se analizan. +Por defecto, la migración analiza todo el espacio de trabajo, independientemente de la opción `--path`, para +actualizar todas las referencias afectadas por una migración de `@Input()`. -With this option, you can limit analysis to a sub-folder. Note that this means that any -references outside this directory are silently skipped, potentially breaking your build. +Con esta opción, puedes limitar el análisis a una subcarpeta. Ten en cuenta que esto significa que cualquier +referencia fuera de este directorio se omite silenciosamente, lo que podría romper tu compilación. -## VSCode extension +## Extensión de VSCode -![Screenshot of the VSCode extension and clicking on an `@Input` field](assets/images/migrations/signal-inputs-vscode.png 'Screenshot of the VSCode extension and clicking on an `@Input` field.') +![Captura de pantalla de la extensión de VSCode haciendo clic en un campo `@Input`](assets/images/migrations/signal-inputs-vscode.png 'Captura de pantalla de la extensión de VSCode haciendo clic en un campo `@Input`.') -The migration is available as a [code refactor action](https://code.visualstudio.com/docs/typescript/typescript-refactoring#_refactoring) in VSCode. +La migración está disponible como una [acción de refactorización de código](https://code.visualstudio.com/docs/typescript/typescript-refactoring#_refactoring) en VSCode. -To make use of the migration via VSCode, install the latest version of the VSCode extension and either click: +Para usar la migración a través de VSCode, instala la última versión de la extensión de VSCode y haz clic en: -- on a `@Input` field. -- or, on a directive/component +- un campo `@Input`. +- o, en una directiva/componente -Then, wait for the yellow lightbulb VSCode refactoring button to appear. -Via this button you can then select the signal input migration. +Luego, espera a que aparezca el botón de refactorización amarillo (lightbulb) de VSCode. +A través de este botón puedes seleccionar la migración de signal input. diff --git a/adev-es/src/content/reference/migrations/signal-queries.en.md b/adev-es/src/content/reference/migrations/signal-queries.en.md new file mode 100644 index 0000000..df500eb --- /dev/null +++ b/adev-es/src/content/reference/migrations/signal-queries.en.md @@ -0,0 +1,115 @@ +# Migration to signal queries + +Angular introduced improved APIs for queries that are considered +production ready as of v19. +Read more about signal queries and their benefits in the [dedicated guide](guide/signals/queries). + +To support existing teams that would like to use signal queries, the Angular team +provides an automated migration that converts existing decorator query fields to the new API. + +Run the schematic using the following command: + +```bash +ng generate @angular/core:signal-queries-migration +``` + +Alternatively, the migration is available as a [code refactor action](https://code.visualstudio.com/docs/typescript/typescript-refactoring#_refactoring) in VSCode. +Install the latest version of the VSCode extension and click onto e.g. a `@ViewChild` field. +See more details in the section [below](#vscode-extension). + +## What does the migration change? + +1. `@ViewChild()`, `@ViewChildren`, `@ContentChild` and `@ContentChildren` class members + are updated to their signal equivalents. +2. References in your application to migrated queries are updated to call the signal. + - This includes references in templates, host bindings or TypeScript code. + +**Before** + +```typescript +import {Component, ContentChild} from '@angular/core'; + +@Component({ + template: `Has ref: {{someRef ? 'Yes' : 'No'}}` +}) +export class MyComponent { + @ContentChild('someRef') ref: ElementRef|undefined = undefined; + + someMethod(): void { + if (this.ref) { + this.ref.nativeElement; + } + } +} +``` + +**After** + +```typescript +import {Component, contentChild} from '@angular/core'; + +@Component({ + template: `Has ref: {{someRef() ? 'Yes' : 'No'}}` +}) +export class MyComponent { + readonly ref = contentChild('someRef'); + + someMethod(): void { + const ref = this.ref(); + if (ref) { + ref.nativeElement; + } + } +} +``` + +## Configuration options + +The migration supports a few options for fine tuning the migration to your specific needs. + +### `--path` + +By default, the migration will update your whole Angular CLI workspace. +You can limit the migration to a specific sub-directory using this option. + +### `--best-effort-mode` + +By default, the migration skips queries that cannot be safely migrated. +The migration tries to refactor code as safely as possible. + +When the `--best-effort-mode` flag is enabled, the migration eagerly +tries to migrate as much as possible, even if it could break your build. + +### `--insert-todos` + +When enabled, the migration will add TODOs to queries that couldn't be migrated. +The TODOs will include reasoning on why queries were skipped. E.g. + +```ts +// TODO: Skipped for migration because: +// Your application code writes to the query. This prevents migration. +@ViewChild('ref') ref?: ElementRef; +``` + +### `--analysis-dir` + +In large projects you may use this option to reduce the amount of files being analyzed. +By default, the migration analyzes the whole workspace, regardless of the `--path` option, in +order to update all references affected by a query declaration being migrated. + +With this option, you can limit analysis to a sub-folder. Note that this means that any +references outside this directory are silently skipped, potentially breaking your build. + +## VSCode extension + +![Screenshot of the VSCode extension and clicking on an `@ViewChild` field](assets/images/migrations/signal-queries-vscode.png 'Screenshot of the VSCode extension and clicking on an `@ViewChild` field.') + +The migration is available as a [code refactor action](https://code.visualstudio.com/docs/typescript/typescript-refactoring#_refactoring) in VSCode. + +To make use of the migration via VSCode, install the latest version of the VSCode extension and either click: + +- on a `@ViewChild`, `@ViewChildren`, `@ContentChild`, or `@ContentChildren` field. +- on a directive/component + +Then, wait for the yellow lightbulb VSCode refactoring button to appear. +Via this button you can then select the signal queries migration. diff --git a/adev-es/src/content/reference/migrations/signal-queries.md b/adev-es/src/content/reference/migrations/signal-queries.md index df500eb..177e3c0 100644 --- a/adev-es/src/content/reference/migrations/signal-queries.md +++ b/adev-es/src/content/reference/migrations/signal-queries.md @@ -1,30 +1,30 @@ -# Migration to signal queries +# Migración a signal queries -Angular introduced improved APIs for queries that are considered -production ready as of v19. -Read more about signal queries and their benefits in the [dedicated guide](guide/signals/queries). +Angular introdujo APIs mejoradas para consultas que se consideran +listas para producción desde v19. +Lee más sobre los signal queries y sus beneficios en la [guía dedicada](guide/signals/queries). -To support existing teams that would like to use signal queries, the Angular team -provides an automated migration that converts existing decorator query fields to the new API. +Para apoyar a los equipos existentes que deseen usar signal queries, el equipo de Angular +proporciona una migración automatizada que convierte los campos de consulta de decoradores existentes a la nueva API. -Run the schematic using the following command: +Ejecuta el schematic usando el siguiente comando: ```bash ng generate @angular/core:signal-queries-migration ``` -Alternatively, the migration is available as a [code refactor action](https://code.visualstudio.com/docs/typescript/typescript-refactoring#_refactoring) in VSCode. -Install the latest version of the VSCode extension and click onto e.g. a `@ViewChild` field. -See more details in the section [below](#vscode-extension). +Alternativamente, la migración está disponible como una [acción de refactorización de código](https://code.visualstudio.com/docs/typescript/typescript-refactoring#_refactoring) en VSCode. +Instala la última versión de la extensión de VSCode y haz clic en, por ejemplo, un campo `@ViewChild`. +Consulta más detalles en la sección [a continuación](#extensión-de-vscode). -## What does the migration change? +## ¿Qué cambia la migración? -1. `@ViewChild()`, `@ViewChildren`, `@ContentChild` and `@ContentChildren` class members - are updated to their signal equivalents. -2. References in your application to migrated queries are updated to call the signal. - - This includes references in templates, host bindings or TypeScript code. +1. Los miembros de clase `@ViewChild()`, `@ViewChildren`, `@ContentChild` y `@ContentChildren` + se actualizan a sus equivalentes con signals. +2. Las referencias en tu aplicación a las consultas migradas se actualizan para llamar al signal. + - Esto incluye referencias en plantillas, host bindings o código TypeScript. -**Before** +**Antes** ```typescript import {Component, ContentChild} from '@angular/core'; @@ -43,7 +43,7 @@ export class MyComponent { } ``` -**After** +**Después** ```typescript import {Component, contentChild} from '@angular/core'; @@ -63,27 +63,27 @@ export class MyComponent { } ``` -## Configuration options +## Opciones de configuración -The migration supports a few options for fine tuning the migration to your specific needs. +La migración admite algunas opciones para ajustar la migración a tus necesidades específicas. ### `--path` -By default, the migration will update your whole Angular CLI workspace. -You can limit the migration to a specific sub-directory using this option. +Por defecto, la migración actualizará todo tu espacio de trabajo de Angular CLI. +Puedes limitar la migración a un subdirectorio específico usando esta opción. ### `--best-effort-mode` -By default, the migration skips queries that cannot be safely migrated. -The migration tries to refactor code as safely as possible. +Por defecto, la migración omite las consultas que no se pueden migrar de forma segura. +La migración intenta refactorizar el código de la forma más segura posible. -When the `--best-effort-mode` flag is enabled, the migration eagerly -tries to migrate as much as possible, even if it could break your build. +Cuando la bandera `--best-effort-mode` está habilitada, la migración intenta de forma agresiva +migrar tanto como sea posible, incluso si pudiera romper tu compilación. ### `--insert-todos` -When enabled, the migration will add TODOs to queries that couldn't be migrated. -The TODOs will include reasoning on why queries were skipped. E.g. +Cuando está habilitado, la migración agregará TODOs a las consultas que no pudieron migrarse. +Los TODOs incluirán el razonamiento de por qué se omitieron las consultas. Por ejemplo: ```ts // TODO: Skipped for migration because: @@ -93,23 +93,23 @@ The TODOs will include reasoning on why queries were skipped. E.g. ### `--analysis-dir` -In large projects you may use this option to reduce the amount of files being analyzed. -By default, the migration analyzes the whole workspace, regardless of the `--path` option, in -order to update all references affected by a query declaration being migrated. +En proyectos grandes puedes usar esta opción para reducir la cantidad de archivos que se analizan. +Por defecto, la migración analiza todo el espacio de trabajo, independientemente de la opción `--path`, para +actualizar todas las referencias afectadas por la migración de una declaración de consulta. -With this option, you can limit analysis to a sub-folder. Note that this means that any -references outside this directory are silently skipped, potentially breaking your build. +Con esta opción, puedes limitar el análisis a una subcarpeta. Ten en cuenta que esto significa que cualquier +referencia fuera de este directorio se omite silenciosamente, lo que podría romper tu compilación. -## VSCode extension +## Extensión de VSCode -![Screenshot of the VSCode extension and clicking on an `@ViewChild` field](assets/images/migrations/signal-queries-vscode.png 'Screenshot of the VSCode extension and clicking on an `@ViewChild` field.') +![Captura de pantalla de la extensión de VSCode haciendo clic en un campo `@ViewChild`](assets/images/migrations/signal-queries-vscode.png 'Captura de pantalla de la extensión de VSCode haciendo clic en un campo `@ViewChild`.') -The migration is available as a [code refactor action](https://code.visualstudio.com/docs/typescript/typescript-refactoring#_refactoring) in VSCode. +La migración está disponible como una [acción de refactorización de código](https://code.visualstudio.com/docs/typescript/typescript-refactoring#_refactoring) en VSCode. -To make use of the migration via VSCode, install the latest version of the VSCode extension and either click: +Para usar la migración a través de VSCode, instala la última versión de la extensión de VSCode y haz clic en: -- on a `@ViewChild`, `@ViewChildren`, `@ContentChild`, or `@ContentChildren` field. -- on a directive/component +- un campo `@ViewChild`, `@ViewChildren`, `@ContentChild` o `@ContentChildren`. +- o, en una directiva/componente -Then, wait for the yellow lightbulb VSCode refactoring button to appear. -Via this button you can then select the signal queries migration. +Luego, espera a que aparezca el botón de refactorización amarillo (lightbulb) de VSCode. +A través de este botón puedes seleccionar la migración de signal queries. diff --git a/adev-es/src/content/reference/migrations/standalone.en.md b/adev-es/src/content/reference/migrations/standalone.en.md new file mode 100644 index 0000000..31d65bf --- /dev/null +++ b/adev-es/src/content/reference/migrations/standalone.en.md @@ -0,0 +1,222 @@ +# Migrate an existing Angular project to standalone + +**Standalone components** provide a simplified way to build Angular applications. Standalone components, directives, and pipes aim to streamline the authoring experience by reducing the need for `NgModule`s. Existing applications can optionally and incrementally adopt the new standalone style without any breaking changes. + + + +This schematic helps to transform components, directive and pipes in existing projects to become standalone. The schematic aims to transform as much code as possible automatically, but it may require some manual fixes by the project author. + +Run the schematic using the following command: + +```shell +ng generate @angular/core:standalone +``` + +## Before updating + +Before using the schematic, please ensure that the project: + +1. Is using Angular 15.2.0 or later. +2. Builds without any compilation errors. +3. Is on a clean Git branch and all work is saved. + +## Schematic options + +| Option | Details | +| :----- | :---------------------------------------------------------------------------------------------------------------------------- | +| `mode` | The transformation to perform. See [Migration modes](#migration-modes) below for details on the available options. | +| `path` | The path to migrate, relative to the project root. You can use this option to migrate sections of your project incrementally. | + +## Migrations steps + +The migration process is composed of three steps. You'll have to run it multiple times and check manually that the project builds and behaves as expected. + +NOTE: While the schematic can automatically update most code, some edge cases require developer intervention. +You should plan to apply manual fixes after each step of the migration. Additionally, the new code generated by the schematic may not match your code's formatting rules. + +Run the migration in the order listed below, verifying that your code builds and runs between each step: + +1. Run `ng g @angular/core:standalone` and select "Convert all components, directives and pipes to standalone" +2. Run `ng g @angular/core:standalone` and select "Remove unnecessary NgModule classes" +3. Run `ng g @angular/core:standalone` and select "Bootstrap the project using standalone APIs" +4. Run any linting and formatting checks, fix any failures, and commit the result + +## After the migration + +Congratulations, your application has been converted to standalone 🎉. These are some optional follow-up steps you may want to take now: + +- Find and remove any remaining `NgModule` declarations: since the ["Remove unnecessary NgModules" step](#remove-unnecessary-ngmodules) cannot remove all modules automatically, you may have to remove the remaining declarations manually. +- Run the project's unit tests and fix any failures. +- Run any code formatters, if the project uses automatic formatting. +- Run any linters in your project and fix new warnings. Some linters support a `--fix` flag that may resolve some of your warnings automatically. + +## Migration modes + +The migration has the following modes: + +1. Convert declarations to standalone. +2. Remove unnecessary NgModules. +3. Switch to standalone bootstrapping API. + You should run these migrations in the order given. + +### Convert declarations to standalone + +In this mode, the migration converts all components, directives and pipes to standalone by removing `standalone: false` and adding dependencies to their `imports` array. + +HELPFUL: The schematic ignores NgModules which bootstrap a component during this step because they are likely root modules used by `bootstrapModule` rather than the standalone-compatible `bootstrapApplication`. The schematic converts these declarations automatically as a part of the ["Switch to standalone bootstrapping API"](#switch-to-standalone-bootstrapping-api) step. + +**Before:** + +```typescript +// shared.module.ts +@NgModule({ + imports: [CommonModule], + declarations: [GreeterComponent], + exports: [GreeterComponent] +}) +export class SharedModule {} +``` + +```typescript +// greeter.component.ts +@Component({ + selector: 'greeter', + template: '
Hello
', + standalone: false, +}) +export class GreeterComponent { + showGreeting = true; +} +``` + +**After:** + +```typescript +// shared.module.ts +@NgModule({ + imports: [CommonModule, GreeterComponent], + exports: [GreeterComponent] +}) +export class SharedModule {} +``` + +```typescript +// greeter.component.ts +@Component({ + selector: 'greeter', + template: '
Hello
', + imports: [NgIf] +}) +export class GreeterComponent { + showGreeting = true; +} +``` + +### Remove unnecessary NgModules + +After converting all declarations to standalone, many NgModules can be safely removed. This step deletes such module declarations and as many corresponding references as possible. If the migration cannot delete a reference automatically, it leaves the following TODO comment so that you can delete the NgModule manually: + +```typescript +/* TODO(standalone-migration): clean up removed NgModule reference manually */ +``` + +The migration considers a module safe to remove if that module: + +- Has no `declarations`. +- Has no `providers`. +- Has no `bootstrap` components. +- Has no `imports` that reference a `ModuleWithProviders` symbol or a module that can't be removed. +- Has no class members. Empty constructors are ignored. + +**Before:** + +```typescript +// importer.module.ts +@NgModule({ + imports: [FooComponent, BarPipe], + exports: [FooComponent, BarPipe] +}) +export class ImporterModule {} +``` + +**After:** + +```typescript +// importer.module.ts +// Does not exist! +``` + +### Switch to standalone bootstrapping API + +This step converts any usages of `bootstrapModule` to the new, standalone-based `bootstrapApplication`. It also removes `standalone: false` from the root component and deletes the root NgModule. If the root module has any `providers` or `imports`, the migration attempts to copy as much of this configuration as possible into the new bootstrap call. + +**Before:** + +```typescript +// ./app/app.module.ts +import { NgModule } from '@angular/core'; +import { AppComponent } from './app.component'; + +@NgModule({ + declarations: [AppComponent], + bootstrap: [AppComponent] +}) +export class AppModule {} +``` + +```typescript +// ./app/app.component.ts +@Component({ + selector: 'app', + template: 'hello', + standalone: false, +}) +export class AppComponent {} +``` + +```typescript +// ./main.ts +import { platformBrowser } from '@angular/platform-browser'; +import { AppModule } from './app/app.module'; + +platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e)); +``` + +**After:** + +```typescript +// ./app/app.module.ts +// Does not exist! +``` + +```typescript +// ./app/app.component.ts +@Component({ + selector: 'app', + template: 'hello' +}) +export class AppComponent {} +``` + +```typescript +// ./main.ts +import { bootstrapApplication } from '@angular/platform-browser'; +import { AppComponent } from './app/app.component'; + +bootstrapApplication(AppComponent).catch(e => console.error(e)); +``` + +## Common problems + +Some common problems that may prevent the schematic from working correctly include: + +- Compilation errors - if the project has compilation errors, Angular cannot analyze and migrate it correctly. +- Files not included in a tsconfig - the schematic determines which files to migrate by analyzing your project's `tsconfig.json` files. The schematic excludes any files not captured by a tsconfig. +- Code that cannot be statically analyzed - the schematic uses static analysis to understand your code and determine where to make changes. The migration may skip any classes with metadata that cannot be statically analyzed at build time. + +## Limitations + +Due to the size and complexity of the migration, there are some cases that the schematic cannot handle: + +- Because unit tests are not ahead-of-time (AoT) compiled, `imports` added to components in unit tests might not be entirely correct. +- The schematic relies on direct calls to Angular APIs. The schematic cannot recognize custom wrappers around Angular APIs. For example, if there you define a custom `customConfigureTestModule` function that wraps `TestBed.configureTestingModule`, components it declares may not be recognized. diff --git a/adev-es/src/content/reference/migrations/standalone.md b/adev-es/src/content/reference/migrations/standalone.md index 31d65bf..96d1c32 100644 --- a/adev-es/src/content/reference/migrations/standalone.md +++ b/adev-es/src/content/reference/migrations/standalone.md @@ -1,71 +1,71 @@ -# Migrate an existing Angular project to standalone +# Migrar un proyecto Angular existente a standalone -**Standalone components** provide a simplified way to build Angular applications. Standalone components, directives, and pipes aim to streamline the authoring experience by reducing the need for `NgModule`s. Existing applications can optionally and incrementally adopt the new standalone style without any breaking changes. +Los **componentes standalone** ofrecen una forma simplificada de construir aplicaciones Angular. Los componentes, directivas y pipes standalone buscan simplificar la experiencia de desarrollo al reducir la necesidad de `NgModule`s. Las aplicaciones existentes pueden adoptar de forma opcional e incremental el nuevo estilo standalone sin ningún cambio disruptivo. - + -This schematic helps to transform components, directive and pipes in existing projects to become standalone. The schematic aims to transform as much code as possible automatically, but it may require some manual fixes by the project author. +Este schematic ayuda a transformar componentes, directivas y pipes en proyectos existentes para que sean standalone. El schematic intenta transformar la mayor cantidad de código posible de forma automática, pero puede requerir algunas correcciones manuales por parte del autor del proyecto. -Run the schematic using the following command: +Ejecuta el schematic usando el siguiente comando: ```shell ng generate @angular/core:standalone ``` -## Before updating +## Antes de actualizar -Before using the schematic, please ensure that the project: +Antes de usar el schematic, asegúrate de que el proyecto: -1. Is using Angular 15.2.0 or later. -2. Builds without any compilation errors. -3. Is on a clean Git branch and all work is saved. +1. Use Angular 15.2.0 o posterior. +2. Se compile sin errores de compilación. +3. Esté en una rama Git limpia y todo el trabajo esté guardado. -## Schematic options +## Opciones del schematic -| Option | Details | -| :----- | :---------------------------------------------------------------------------------------------------------------------------- | -| `mode` | The transformation to perform. See [Migration modes](#migration-modes) below for details on the available options. | -| `path` | The path to migrate, relative to the project root. You can use this option to migrate sections of your project incrementally. | +| Opción | Detalles | +| :----- | :--------------------------------------------------------------------------------------------------------------------------------- | +| `mode` | La transformación a realizar. Consulta [Modos de migración](#modos-de-migración) a continuación para detalles sobre las opciones disponibles. | +| `path` | La ruta a migrar, relativa a la raíz del proyecto. Puedes usar esta opción para migrar secciones de tu proyecto de forma incremental. | -## Migrations steps +## Pasos de la migración -The migration process is composed of three steps. You'll have to run it multiple times and check manually that the project builds and behaves as expected. +El proceso de migración se compone de tres pasos. Deberás ejecutarlo varias veces y verificar manualmente que el proyecto se compile y funcione como se espera. -NOTE: While the schematic can automatically update most code, some edge cases require developer intervention. -You should plan to apply manual fixes after each step of the migration. Additionally, the new code generated by the schematic may not match your code's formatting rules. +NOTA: Aunque el schematic puede actualizar la mayor parte del código automáticamente, algunos casos extremos requieren intervención del desarrollador. +Debes planificar aplicar correcciones manuales después de cada paso de la migración. Además, el nuevo código generado por el schematic puede no coincidir con las reglas de formato de tu código. -Run the migration in the order listed below, verifying that your code builds and runs between each step: +Ejecuta la migración en el orden indicado a continuación, verificando que tu código se compile y ejecute entre cada paso: -1. Run `ng g @angular/core:standalone` and select "Convert all components, directives and pipes to standalone" -2. Run `ng g @angular/core:standalone` and select "Remove unnecessary NgModule classes" -3. Run `ng g @angular/core:standalone` and select "Bootstrap the project using standalone APIs" -4. Run any linting and formatting checks, fix any failures, and commit the result +1. Ejecuta `ng g @angular/core:standalone` y selecciona "Convert all components, directives and pipes to standalone" +2. Ejecuta `ng g @angular/core:standalone` y selecciona "Remove unnecessary NgModule classes" +3. Ejecuta `ng g @angular/core:standalone` y selecciona "Bootstrap the project using standalone APIs" +4. Ejecuta las verificaciones de linting y formato, corrige los fallos y confirma el resultado -## After the migration +## Después de la migración -Congratulations, your application has been converted to standalone 🎉. These are some optional follow-up steps you may want to take now: +¡Felicitaciones, tu aplicación ha sido convertida a standalone! Estos son algunos pasos opcionales de seguimiento que puedes realizar ahora: -- Find and remove any remaining `NgModule` declarations: since the ["Remove unnecessary NgModules" step](#remove-unnecessary-ngmodules) cannot remove all modules automatically, you may have to remove the remaining declarations manually. -- Run the project's unit tests and fix any failures. -- Run any code formatters, if the project uses automatic formatting. -- Run any linters in your project and fix new warnings. Some linters support a `--fix` flag that may resolve some of your warnings automatically. +- Encuentra y elimina las declaraciones `NgModule` restantes: dado que el paso ["Eliminar NgModules innecesarios"](#eliminar-ngmodules-innecesarios) no puede eliminar todos los módulos automáticamente, es posible que tengas que eliminar las declaraciones restantes manualmente. +- Ejecuta las pruebas unitarias del proyecto y corrige los fallos. +- Ejecuta los formateadores de código, si el proyecto usa formato automático. +- Ejecuta los linters en tu proyecto y corrige las nuevas advertencias. Algunos linters admiten una bandera `--fix` que puede resolver algunas advertencias automáticamente. -## Migration modes +## Modos de migración -The migration has the following modes: +La migración tiene los siguientes modos: -1. Convert declarations to standalone. -2. Remove unnecessary NgModules. -3. Switch to standalone bootstrapping API. - You should run these migrations in the order given. +1. Convertir declaraciones a standalone. +2. Eliminar NgModules innecesarios. +3. Cambiar a la API de bootstrap standalone. + Debes ejecutar estas migraciones en el orden indicado. -### Convert declarations to standalone +### Convertir declaraciones a standalone -In this mode, the migration converts all components, directives and pipes to standalone by removing `standalone: false` and adding dependencies to their `imports` array. +En este modo, la migración convierte todos los componentes, directivas y pipes a standalone eliminando `standalone: false` y agregando dependencias a su array `imports`. -HELPFUL: The schematic ignores NgModules which bootstrap a component during this step because they are likely root modules used by `bootstrapModule` rather than the standalone-compatible `bootstrapApplication`. The schematic converts these declarations automatically as a part of the ["Switch to standalone bootstrapping API"](#switch-to-standalone-bootstrapping-api) step. +ÚTIL: El schematic ignora los NgModules que hacen bootstrap de un componente durante este paso, ya que probablemente son módulos raíz usados por `bootstrapModule` en lugar del `bootstrapApplication` compatible con standalone. El schematic convierte estas declaraciones automáticamente como parte del paso ["Cambiar a la API de bootstrap standalone"](#cambiar-a-la-api-de-bootstrap-standalone). -**Before:** +**Antes:** ```typescript // shared.module.ts @@ -89,7 +89,7 @@ export class GreeterComponent { } ``` -**After:** +**Después:** ```typescript // shared.module.ts @@ -112,23 +112,23 @@ export class GreeterComponent { } ``` -### Remove unnecessary NgModules +### Eliminar NgModules innecesarios -After converting all declarations to standalone, many NgModules can be safely removed. This step deletes such module declarations and as many corresponding references as possible. If the migration cannot delete a reference automatically, it leaves the following TODO comment so that you can delete the NgModule manually: +Después de convertir todas las declaraciones a standalone, muchos NgModules pueden eliminarse de forma segura. Este paso elimina dichas declaraciones de módulos y la mayor cantidad de referencias correspondientes posible. Si la migración no puede eliminar una referencia automáticamente, deja el siguiente comentario TODO para que puedas eliminar el NgModule manualmente: ```typescript /* TODO(standalone-migration): clean up removed NgModule reference manually */ ``` -The migration considers a module safe to remove if that module: +La migración considera que un módulo es seguro de eliminar si ese módulo: -- Has no `declarations`. -- Has no `providers`. -- Has no `bootstrap` components. -- Has no `imports` that reference a `ModuleWithProviders` symbol or a module that can't be removed. -- Has no class members. Empty constructors are ignored. +- No tiene `declarations`. +- No tiene `providers`. +- No tiene componentes en `bootstrap`. +- No tiene `imports` que referencien un símbolo `ModuleWithProviders` o un módulo que no se pueda eliminar. +- No tiene miembros de clase. Los constructores vacíos se ignoran. -**Before:** +**Antes:** ```typescript // importer.module.ts @@ -139,18 +139,18 @@ The migration considers a module safe to remove if that module: export class ImporterModule {} ``` -**After:** +**Después:** ```typescript // importer.module.ts -// Does not exist! +// ¡No existe! ``` -### Switch to standalone bootstrapping API +### Cambiar a la API de bootstrap standalone -This step converts any usages of `bootstrapModule` to the new, standalone-based `bootstrapApplication`. It also removes `standalone: false` from the root component and deletes the root NgModule. If the root module has any `providers` or `imports`, the migration attempts to copy as much of this configuration as possible into the new bootstrap call. +Este paso convierte cualquier uso de `bootstrapModule` al nuevo `bootstrapApplication` basado en standalone. También elimina `standalone: false` del componente raíz y elimina el NgModule raíz. Si el módulo raíz tiene `providers` o `imports`, la migración intenta copiar la mayor parte posible de esta configuración en la nueva llamada de bootstrap. -**Before:** +**Antes:** ```typescript // ./app/app.module.ts @@ -182,11 +182,11 @@ import { AppModule } from './app/app.module'; platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e)); ``` -**After:** +**Después:** ```typescript // ./app/app.module.ts -// Does not exist! +// ¡No existe! ``` ```typescript @@ -206,17 +206,17 @@ import { AppComponent } from './app/app.component'; bootstrapApplication(AppComponent).catch(e => console.error(e)); ``` -## Common problems +## Problemas comunes -Some common problems that may prevent the schematic from working correctly include: +Algunos problemas comunes que pueden impedir que el schematic funcione correctamente incluyen: -- Compilation errors - if the project has compilation errors, Angular cannot analyze and migrate it correctly. -- Files not included in a tsconfig - the schematic determines which files to migrate by analyzing your project's `tsconfig.json` files. The schematic excludes any files not captured by a tsconfig. -- Code that cannot be statically analyzed - the schematic uses static analysis to understand your code and determine where to make changes. The migration may skip any classes with metadata that cannot be statically analyzed at build time. +- Errores de compilación - si el proyecto tiene errores de compilación, Angular no puede analizarlo ni migrarlo correctamente. +- Archivos no incluidos en un tsconfig - el schematic determina qué archivos migrar analizando los archivos `tsconfig.json` de tu proyecto. El schematic excluye cualquier archivo no capturado por un tsconfig. +- Código que no puede analizarse estáticamente - el schematic usa análisis estático para entender tu código y determinar dónde hacer cambios. La migración puede omitir cualquier clase con metadatos que no puedan analizarse estáticamente en tiempo de compilación. -## Limitations +## Limitaciones -Due to the size and complexity of the migration, there are some cases that the schematic cannot handle: +Debido al tamaño y la complejidad de la migración, hay algunos casos que el schematic no puede manejar: -- Because unit tests are not ahead-of-time (AoT) compiled, `imports` added to components in unit tests might not be entirely correct. -- The schematic relies on direct calls to Angular APIs. The schematic cannot recognize custom wrappers around Angular APIs. For example, if there you define a custom `customConfigureTestModule` function that wraps `TestBed.configureTestingModule`, components it declares may not be recognized. +- Debido a que las pruebas unitarias no se compilan ahead-of-time (AoT), los `imports` agregados a los componentes en las pruebas unitarias podrían no ser del todo correctos. +- El schematic se basa en llamadas directas a las APIs de Angular. El schematic no puede reconocer envoltorios personalizados alrededor de las APIs de Angular. Por ejemplo, si defines una función `customConfigureTestModule` personalizada que envuelve `TestBed.configureTestingModule`, los componentes que declara pueden no ser reconocidos. diff --git a/adev-es/src/content/reference/migrations/typed-forms.en.md b/adev-es/src/content/reference/migrations/typed-forms.en.md new file mode 100644 index 0000000..6844f58 --- /dev/null +++ b/adev-es/src/content/reference/migrations/typed-forms.en.md @@ -0,0 +1,43 @@ +# Typed Forms Migration + +As of Angular 14, reactive forms are strictly typed by default. + +## Overview of Typed Forms + + + +With Angular reactive forms, you explicitly specify a *form model*. As a simple example, consider this basic user login form: + +```ts +const login = new FormGroup({ + email: new FormControl(''), + password: new FormControl(''), +}); +``` + +Angular provides many APIs for interacting with this `FormGroup`. For example, you may call `login.value`, `login.controls`, `login.patchValue`, etc. (For a full API reference, see the [API documentation](api/forms/FormGroup).) + +In previous Angular versions, most of these APIs included `any` somewhere in their types, and interacting with the structure of the controls, or the values themselves, was not type-safe. For example: you could write the following invalid code: + +```ts +const emailDomain = login.value.email.domain; +``` + +With strictly typed reactive forms, the above code does not compile, because there is no `domain` property on `email`. + +In addition to the added safety, the types enable a variety of other improvements, such as better autocomplete in IDEs, and an explicit way to specify form structure. + +These improvements currently apply only to *reactive* forms (not [*template-driven* forms](guide/forms/template-driven-forms)). + +## Automated Untyped Forms Migration + +When upgrading to Angular 14, an included migration will automatically replace all the forms classes in your code with corresponding untyped versions. For example, the snippet from above would become: + +```ts +const login = new UntypedFormGroup({ + email: new UntypedFormControl(''), + password: new UntypedFormControl(''), +}); +``` + +Each `Untyped` symbol has exactly the same semantics as in previous Angular versions, so your application should continue to compile as before. By removing the `Untyped` prefixes, you can incrementally enable the types. diff --git a/adev-es/src/content/reference/migrations/typed-forms.md b/adev-es/src/content/reference/migrations/typed-forms.md index 6844f58..936406b 100644 --- a/adev-es/src/content/reference/migrations/typed-forms.md +++ b/adev-es/src/content/reference/migrations/typed-forms.md @@ -1,12 +1,12 @@ -# Typed Forms Migration +# Migración de formularios tipados -As of Angular 14, reactive forms are strictly typed by default. +A partir de Angular 14, los formularios reactivos son estrictamente tipados por defecto. -## Overview of Typed Forms +## Descripción general de los formularios tipados - + -With Angular reactive forms, you explicitly specify a *form model*. As a simple example, consider this basic user login form: +Con los formularios reactivos de Angular, especificas explícitamente un *modelo de formulario*. Como ejemplo simple, considera este formulario básico de inicio de sesión: ```ts const login = new FormGroup({ @@ -15,23 +15,23 @@ const login = new FormGroup({ }); ``` -Angular provides many APIs for interacting with this `FormGroup`. For example, you may call `login.value`, `login.controls`, `login.patchValue`, etc. (For a full API reference, see the [API documentation](api/forms/FormGroup).) +Angular proporciona muchas APIs para interactuar con este `FormGroup`. Por ejemplo, puedes llamar a `login.value`, `login.controls`, `login.patchValue`, etc. (Para una referencia completa de la API, consulta la [documentación de la API](api/forms/FormGroup).) -In previous Angular versions, most of these APIs included `any` somewhere in their types, and interacting with the structure of the controls, or the values themselves, was not type-safe. For example: you could write the following invalid code: +En versiones anteriores de Angular, la mayoría de estas APIs incluían `any` en algún lugar de sus tipos, e interactuar con la estructura de los controles, o los valores en sí mismos, no era seguro en cuanto a tipos. Por ejemplo, podías escribir el siguiente código inválido: ```ts const emailDomain = login.value.email.domain; ``` -With strictly typed reactive forms, the above code does not compile, because there is no `domain` property on `email`. +Con los formularios reactivos estrictamente tipados, el código anterior no compila, porque no hay ninguna propiedad `domain` en `email`. -In addition to the added safety, the types enable a variety of other improvements, such as better autocomplete in IDEs, and an explicit way to specify form structure. +Además de la seguridad añadida, los tipos habilitan una variedad de otras mejoras, como un mejor autocompletado en los IDEs y una forma explícita de especificar la estructura del formulario. -These improvements currently apply only to *reactive* forms (not [*template-driven* forms](guide/forms/template-driven-forms)). +Estas mejoras actualmente solo aplican a los formularios *reactivos* (no a los [formularios *basados en plantilla*](guide/forms/template-driven-forms)). -## Automated Untyped Forms Migration +## Migración automatizada de formularios sin tipo -When upgrading to Angular 14, an included migration will automatically replace all the forms classes in your code with corresponding untyped versions. For example, the snippet from above would become: +Al actualizar a Angular 14, una migración incluida reemplazará automáticamente todas las clases de formularios en tu código con versiones sin tipo correspondientes. Por ejemplo, el fragmento anterior se convertiría en: ```ts const login = new UntypedFormGroup({ @@ -40,4 +40,4 @@ const login = new UntypedFormGroup({ }); ``` -Each `Untyped` symbol has exactly the same semantics as in previous Angular versions, so your application should continue to compile as before. By removing the `Untyped` prefixes, you can incrementally enable the types. +Cada símbolo `Untyped` tiene exactamente la misma semántica que en versiones anteriores de Angular, por lo que tu aplicación debería seguir compilando como antes. Al eliminar los prefijos `Untyped`, puedes habilitar los tipos de forma incremental.