diff --git a/adev-es/src/app/sub-navigation-data.ts b/adev-es/src/app/sub-navigation-data.ts index b75a150..e554e93 100644 --- a/adev-es/src/app/sub-navigation-data.ts +++ b/adev-es/src/app/sub-navigation-data.ts @@ -32,45 +32,45 @@ const DOCS_SUB_NAVIGATION_DATA: NavigationItem[] = [ contentPath: 'introduction/what-is-angular', }, { - label: 'Essentials', + label: 'Esenciales', children: [ { - label: 'Overview', + label: 'Visión General', path: 'essentials', contentPath: 'introduction/essentials/overview', }, { - label: 'Composing with Components', + label: 'Composición basada en Componentes', path: 'essentials/components', contentPath: 'introduction/essentials/components', }, { - label: 'Managing Dynamic Data', + label: 'Gestión de Datos Dinámicos', path: 'essentials/managing-dynamic-data', contentPath: 'introduction/essentials/managing-dynamic-data', }, { - label: 'Rendering Dynamic Templates', + label: 'Renderizado de Plantillas Dinámicas', path: 'essentials/rendering-dynamic-templates', contentPath: 'introduction/essentials/rendering-dynamic-templates', }, { - label: 'Conditionals and Loops', + label: 'Condicionales y Bucles', path: 'essentials/conditionals-and-loops', contentPath: 'introduction/essentials/conditionals-and-loops', }, { - label: 'Handling User Interaction', + label: 'Manejo de la Interacción del Usuario', path: 'essentials/handling-user-interaction', contentPath: 'introduction/essentials/handling-user-interaction', }, { - label: 'Sharing Logic', + label: 'Compartiendo Lógica', path: 'essentials/sharing-logic', contentPath: 'introduction/essentials/sharing-logic', }, { - label: 'Next Steps', + label: 'Siguientes Pasos', path: 'essentials/next-steps', contentPath: 'introduction/essentials/next-steps', }, diff --git a/adev-es/src/content/introduction/essentials/components.en.md b/adev-es/src/content/introduction/essentials/components.en.md new file mode 100644 index 0000000..26733be --- /dev/null +++ b/adev-es/src/content/introduction/essentials/components.en.md @@ -0,0 +1,137 @@ + +The fundamental building block for creating applications in Angular. + + +Components provide structure for organizing your project into easy-to-understand parts with clear responsibilities so that your code is maintainable and scalable. + +Here is an example of how a Todo application could be broken down into a tree of components. + +```mermaid +flowchart TD + A[TodoApp]-->B + A-->C + B[TodoList]-->D + C[TodoMetrics] + D[TodoListItem] +``` + +In this guide, we'll take a look at how to create and use components in Angular. + +## Defining a Component + +Every component has the following core properties: + +1. A `@Component`[decorator](https://www.typescriptlang.org/docs/handbook/decorators.html) that contains some configuration +2. An HTML template that controls what renders into the DOM +3. A [CSS selector](https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors) that defines how the component is used in HTML +4. A TypeScript class with behaviors such as managing state, handling user input, or fetching data from a server. + +Here is a simplified example of a TodoListItem component. + +```ts +// todo-list-item.component.ts +@Component({ + selector: 'todo-list-item', + template: ` +
  • (TODO) Read Angular Essentials Guide
  • + `, +}) +export class TodoListItem { + /* Component behavior is defined in here */ +} +``` + +Other common metadata that you'll also see in components include: + +- `standalone: true` — The recommended approach of streamlining the authoring experience of components +- `styles` — A string or array of strings that contains any CSS styles you want applied to the component + +Knowing this, here is an updated version of our `TodoListItem` component. + +```ts +// todo-list-item.component.ts +@Component({ + standalone: true, + selector: 'todo-list-item', + template: ` +
  • (TODO) Read Angular Essentials Guide
  • + `, + styles: ` + li { + color: red; + font-weight: 300; + } + `, +}) +export class TodoListItem { + /* Component behavior is defined in here */ +} +``` + +### Separating HTML and CSS into separate files + +For teams that prefer managing their HTML and/or CSS in separate files, Angular provides two additional properties: `templateUrl` and `styleUrl`. + +Using the previous `TodoListItem` component, the alternative approach looks like: + +```ts +// todo-list-item.component.ts +@Component({ + standalone: true, + selector: 'todo-list-item', + templateUrl: './todo-list-item.component.html', + styleUrl: './todo-list-item.component.css', +}) +export class TodoListItem { + /* Component behavior is defined in here */ +} +``` + +```html + +
  • (TODO) Read Angular Essentials Guide
  • +``` + +```css +// todo-list-item.component.css +li { + color: red; + font-weight: 300; +} +``` + +## Using a Component + +One advantage of component architecture is that your application is modular. In other words, components can be used in other components. + +To use a component, you need to: + +1. Import the component into the file +2. Add it to the component's `imports` array +3. Use the component's selector in the `template` + +Here's an example of a `TodoList` component importing the `TodoListItem` component from before: + +```ts +// todo-list.component.ts +import {TodoListItem} from './todo-list-item.component.ts'; + +@Component({ + standalone: true, + imports: [TodoListItem], + template: ` + + `, +}) +export class TodoList {} +``` + +## Next Step + +Now that you know how components work in Angular, it's time to learn how we add and manage dynamic data in our application. + + + + diff --git a/adev-es/src/content/introduction/essentials/components.md b/adev-es/src/content/introduction/essentials/components.md index 26733be..8036818 100644 --- a/adev-es/src/content/introduction/essentials/components.md +++ b/adev-es/src/content/introduction/essentials/components.md @@ -1,10 +1,10 @@ - -The fundamental building block for creating applications in Angular. + +El elemento fundamental para crear aplicaciones en Angular. -Components provide structure for organizing your project into easy-to-understand parts with clear responsibilities so that your code is maintainable and scalable. +Los componentes proporcionan la estructura para organizar su proyecto en partes fáciles de entender con responsabilidades claras para que su código sea mantenible y escalable. -Here is an example of how a Todo application could be broken down into a tree of components. +Aquí hay un ejemplo de cómo una aplicación de Tareas Pendientes (ToDo en inglés) se podría dividir en un árbol de componentes. ```mermaid flowchart TD @@ -15,38 +15,38 @@ flowchart TD D[TodoListItem] ``` -In this guide, we'll take a look at how to create and use components in Angular. +En esta guía, veremos cómo crear y usar componentes en Angular. -## Defining a Component +## Definiendo un Componente -Every component has the following core properties: +Cada componente tiene las siguientes propiedades principales: -1. A `@Component`[decorator](https://www.typescriptlang.org/docs/handbook/decorators.html) that contains some configuration -2. An HTML template that controls what renders into the DOM -3. A [CSS selector](https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors) that defines how the component is used in HTML -4. A TypeScript class with behaviors such as managing state, handling user input, or fetching data from a server. +1. Un [decorator] `@Component`(https://www.typescriptlang.org/docs/handbook/decorators.html) que contiene alguna configuración +2. Una plantilla HTML que controla lo que se renderiza en el DOM +3. Un [selector CSS ](https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors) que define cómo se usa el componente en HTML +4. Una clase de TypeScript con comportamientos como gestión de estado, manejo de entrada de usuario o recuperación de datos de un servidor. -Here is a simplified example of a TodoListItem component. +Aquí hay un ejemplo simplificado de un componente TodoListItem. ```ts // todo-list-item.component.ts @Component({ selector: 'todo-list-item', template: ` -
  • (TODO) Read Angular Essentials Guide
  • +
  • (TODO) Lea la guía de Angular Essentials
  • `, }) export class TodoListItem { - /* Component behavior is defined in here */ + /* El comportamiento de los componentes se define aquí */ } ``` -Other common metadata that you'll also see in components include: +Otros metadatos comunes que también verás en los componentes incluyen: -- `standalone: true` — The recommended approach of streamlining the authoring experience of components -- `styles` — A string or array of strings that contains any CSS styles you want applied to the component +- `standalone: true` — El enfoque recomendado para simplificar la experiencia de creación de componentes +- `styles` — Una cadena o matriz de cadenas que contiene cualquier estilo CSS que desee aplicar al componente -Knowing this, here is an updated version of our `TodoListItem` component. +Sabiendo esto, aquí hay una versión actualizada de nuestro componente `TodoListItem` . ```ts // todo-list-item.component.ts @@ -54,7 +54,7 @@ Knowing this, here is an updated version of our `TodoListItem` component. standalone: true, selector: 'todo-list-item', template: ` -
  • (TODO) Read Angular Essentials Guide
  • +
  • (TODO) Lea la guía de Angular Essentials
  • `, styles: ` li { @@ -64,15 +64,15 @@ Knowing this, here is an updated version of our `TodoListItem` component. `, }) export class TodoListItem { - /* Component behavior is defined in here */ + /* El comportamiento de los componentes se define aquí */ } ``` -### Separating HTML and CSS into separate files +### Separando HTML y CSS en archivos separados -For teams that prefer managing their HTML and/or CSS in separate files, Angular provides two additional properties: `templateUrl` and `styleUrl`. +Para los equipos que prefieren administrar su HTML y/o CSS en archivos separados, Angular proporciona dos propiedades adicionales: `templateUrl` y `styleUrl`. -Using the previous `TodoListItem` component, the alternative approach looks like: +Usando el componente `TodoListItem` anterior, el enfoque alternativo se ve así: ```ts // todo-list-item.component.ts @@ -83,13 +83,13 @@ Using the previous `TodoListItem` component, the alternative approach looks like styleUrl: './todo-list-item.component.css', }) export class TodoListItem { - /* Component behavior is defined in here */ + /* El comportamiento de los componentes se define aquí */ } ``` ```html -
  • (TODO) Read Angular Essentials Guide
  • +
  • (TODO) Lea la guía de Angular Essentials
  • ``` ```css @@ -100,17 +100,17 @@ li { } ``` -## Using a Component +## Usando un Component -One advantage of component architecture is that your application is modular. In other words, components can be used in other components. +Una ventaja de la arquitectura de componentes es que su aplicación es modular. En otras palabras, los componentes se pueden usar en otros componentes. -To use a component, you need to: +Para usar un componente, necesitas: -1. Import the component into the file -2. Add it to the component's `imports` array -3. Use the component's selector in the `template` +1. Importar el componente en el archivo +2. Añadirlo a la matriz de `importaciones` del componente +3. Utilice el selector del componente en la `plantilla` -Here's an example of a `TodoList` component importing the `TodoListItem` component from before: +Aquí hay un ejemplo del componente `TodoList` importando el componente `TodoListItem` de antes: ```ts // todo-list.component.ts @@ -128,10 +128,10 @@ import {TodoListItem} from './todo-list-item.component.ts'; export class TodoList {} ``` -## Next Step +## Siguiente Paso -Now that you know how components work in Angular, it's time to learn how we add and manage dynamic data in our application. +Ahora que sabe cómo funcionan los componentes en Angular, es hora de aprender cómo agregamos y gestionamos los datos dinámicos en nuestra aplicación. - + diff --git a/adev-es/src/content/introduction/essentials/conditionals-and-loops.en.md b/adev-es/src/content/introduction/essentials/conditionals-and-loops.en.md new file mode 100644 index 0000000..1ad20b1 --- /dev/null +++ b/adev-es/src/content/introduction/essentials/conditionals-and-loops.en.md @@ -0,0 +1,112 @@ + +Conditionally show and/or repeat content based on dynamic data. + + +One of the advantages of using a framework like Angular is that it provides built-in solutions for common problems that developers encounter. Examples of this include: displaying content based on a certain condition, rendering a list of items based on application data, etc. + +To solve this problem, Angular uses built-in control flow blocks, which tell the framework when and how your templates should be rendered. + +## Conditional rendering + +One of the most common scenarios that developers encounter is the desire to show or hide content in templates based on a condition. + +A common example of this is whether or not to display certain controls on the screen based on the user's permission level. + +### `@if` block + +Similar to JavaScript's `if` statement, Angular uses `@if` control flow blocks to conditionally hide and show part of a template and its contents. + +```ts +// user-controls.component.ts +@Component({ + standalone: true, + selector: 'user-controls', + template: ` + @if (isAdmin) { + + } + `, +}) +export class UserControls { + isAdmin = true; +} +``` + +In this example, Angular only renders the ` + } @else { +

    You are not authorized.

    + } + `, +}) +export class UserControls { + isAdmin = true; +} +``` + +## Rendering a list + +Another common scenario developers encounter is the need to render a list of items. + +### `@for` block + +Similar to JavaScript’s `for...of` loops, Angular provides the `@for` block for rendering repeated elements. + +```html + + +``` + +```ts +// ingredient-list.component.ts +@Component({ + standalone: true, + selector: 'ingredient-list', + templateUrl: './ingredient-list.component.html', +}) +export class IngredientList { + ingredientList = [ + {name: 'noodles', quantity: 1}, + {name: 'miso broth', quantity: 1}, + {name: 'egg', quantity: 2}, + ]; +} +``` + +However, unlike a standard `for...of` loop, you might've noticed that there's an additional `track` keyword. + +#### `track` property + +When Angular renders a list of elements with `@for`, those items can later change or move. Angular needs to track each element through any reordering, usually by treating a property of the item as a unique identifier or key. + +This ensures any updates to the list are reflected correctly in the UI and tracked properly within Angular, especially in the case of stateful elements or animations. + +To accomplish this, we can provide a unique key to Angular with the `track` keyword. + +## Next Step + +With the ability to determine when and how templates are rendered, it's time to learn how we handle an important aspect of most applications: handling user input. + + + + diff --git a/adev-es/src/content/introduction/essentials/conditionals-and-loops.md b/adev-es/src/content/introduction/essentials/conditionals-and-loops.md index 1ad20b1..931acd8 100644 --- a/adev-es/src/content/introduction/essentials/conditionals-and-loops.md +++ b/adev-es/src/content/introduction/essentials/conditionals-and-loops.md @@ -1,20 +1,20 @@ - -Conditionally show and/or repeat content based on dynamic data. + +Mostrar y/o repetir contenido condicionalmente basado en datos dinámicos. -One of the advantages of using a framework like Angular is that it provides built-in solutions for common problems that developers encounter. Examples of this include: displaying content based on a certain condition, rendering a list of items based on application data, etc. +Una de las ventajas de usar un framework como Angular es que proporciona soluciones integradas para problemas comunes que los desarrolladores encuentran. Ejemplos de esto incluyen: mostrar contenido basado en una condición determinada, representar una lista de elementos basada en datos de la aplicación, etc. -To solve this problem, Angular uses built-in control flow blocks, which tell the framework when and how your templates should be rendered. +Para resolver este problema, Angular utiliza bloques de control de flujo integrados, que indican al framework cuándo y cómo se deben representar las plantillas. -## Conditional rendering +## Renderizado Condicional -One of the most common scenarios that developers encounter is the desire to show or hide content in templates based on a condition. +Uno de los escenarios más comunes que encuentran los desarrolladores es el deseo de mostrar u ocultar contenido en plantillas basadas en una condición. -A common example of this is whether or not to display certain controls on the screen based on the user's permission level. +Un ejemplo común de esto es si mostrar o no ciertos controles en la pantalla en función del nivel de permisos del usuario. -### `@if` block +### Bloque `@if` -Similar to JavaScript's `if` statement, Angular uses `@if` control flow blocks to conditionally hide and show part of a template and its contents. +Similar a la sentencia `if` de JavaScript, Angular utiliza bloques de control de flujo `@if` para ocultar o mostrar condicionalmente partes de una plantilla y su contenido. ```ts // user-controls.component.ts @@ -23,7 +23,7 @@ Similar to JavaScript's `if` statement, Angular uses `@if` control flow blocks t selector: 'user-controls', template: ` @if (isAdmin) { - + } `, }) @@ -32,15 +32,15 @@ export class UserControls { } ``` -In this example, Angular only renders the ` + } @else { -

    You are not authorized.

    +

    No estás autorizado.

    } `, }) @@ -60,13 +60,13 @@ export class UserControls { } ``` -## Rendering a list +## Renderizado de Listas -Another common scenario developers encounter is the need to render a list of items. +Otro escenario habitual que enfrentan los desarrolladores es la necesidad de mostrar una lista de elementos. -### `@for` block +### Bloque `@for` -Similar to JavaScript’s `for...of` loops, Angular provides the `@for` block for rendering repeated elements. +Similar a los bucles for...of de JavaScript, Angular proporciona el bloque `@for` para renderizar elementos repetidos. ```html @@ -93,20 +93,20 @@ export class IngredientList { } ``` -However, unlike a standard `for...of` loop, you might've noticed that there's an additional `track` keyword. +Sin embargo, a diferencia de un bucle `for...of` estándar, te habrás dado cuenta de que el bloque @for de Angular tiene una palabra clave adicional: `track`. -#### `track` property +#### Propiedad `track` -When Angular renders a list of elements with `@for`, those items can later change or move. Angular needs to track each element through any reordering, usually by treating a property of the item as a unique identifier or key. +Cuando Angular renderiza una lista de elementos con `@for`, esos elementos pueden cambiar o moverse posteriormente. Angular necesita rastrear cada elemento a través de cualquier reordenamiento, generalmente utilizando una propiedad del elemento como un identificador único o clave. -This ensures any updates to the list are reflected correctly in the UI and tracked properly within Angular, especially in the case of stateful elements or animations. +Esto asegura que cualquier actualización en la lista se refleje correctamente en la interfaz de usuario y se rastree de manera adecuada dentro de Angular, especialmente en el caso de elementos con estado o animaciones. -To accomplish this, we can provide a unique key to Angular with the `track` keyword. +Para lograr esto, podemos proporcionarle a Angular una clave única con la palabra clave `track`. -## Next Step +## Siguiente Paso -With the ability to determine when and how templates are rendered, it's time to learn how we handle an important aspect of most applications: handling user input. +Ahora que ya sabes cómo determinar cuándo y cómo se renderizan las plantillas, es momento de aprender a manejar un aspecto importante de la mayoría de las aplicaciones: El Manejo de la interacción del usuario (o la entrada del usuario). - + diff --git a/adev-es/src/content/introduction/essentials/handling-user-interaction.en.md b/adev-es/src/content/introduction/essentials/handling-user-interaction.en.md new file mode 100644 index 0000000..8b5b2a9 --- /dev/null +++ b/adev-es/src/content/introduction/essentials/handling-user-interaction.en.md @@ -0,0 +1,56 @@ + +Handle user interaction in your application. + + +The ability to handle user interaction and then work with - it is one of the key aspects of building dynamic applications. In this guide, we'll take a look at simple user interaction - event handling. + +## Event Handling + +You can add an event handler to an element by: + +1. Adding an attribute with the events name inside of parentheses +2. Specify what JavaScript statement you want to run when it fires + +```html + +``` + +For example, if we wanted to create a button that would run a `transformText` function when the `click` event is fired, it would look like the following: + +```ts +// text-transformer.component.ts +@Component({ + standalone: true, + selector: 'text-transformer', + template: ` +

    {{ announcement }}

    + + `, +}) +export class TextTransformer { + announcement = 'Hello again Angular!'; + + transformText() { + this.announcement = this.announcement.toUpperCase(); + } +} +``` + +Other common examples of event listeners include: + +- `` +- `` + +### $event + +If you need to access the [event](https://developer.mozilla.org/en-US/docs/Web/API/Event) object, Angular provides an implicit `$event` variable that you can pass to a function: + +```html + +``` + +## Next Step + + + + diff --git a/adev-es/src/content/introduction/essentials/handling-user-interaction.md b/adev-es/src/content/introduction/essentials/handling-user-interaction.md index 8b5b2a9..716ade8 100644 --- a/adev-es/src/content/introduction/essentials/handling-user-interaction.md +++ b/adev-es/src/content/introduction/essentials/handling-user-interaction.md @@ -1,21 +1,21 @@ - + Handle user interaction in your application. -The ability to handle user interaction and then work with - it is one of the key aspects of building dynamic applications. In this guide, we'll take a look at simple user interaction - event handling. +La capacidad de manejar la interacción del usuario y luego trabajar con ella es uno de los aspectos clave de la construcción de aplicaciones dinámicas. En esta guía, veremos la interacción básica del usuario: El manejo de eventos. -## Event Handling +## Manejo de Eventos -You can add an event handler to an element by: +Puede agregar un controlador de eventos a un elemento mediante: -1. Adding an attribute with the events name inside of parentheses -2. Specify what JavaScript statement you want to run when it fires +1. Agregando un atributo con el nombre de los eventos entre parentesis +2. Especifique qué instrucción JavaScript desea ejecutar cuando se active ```html - + ``` -For example, if we wanted to create a button that would run a `transformText` function when the `click` event is fired, it would look like the following: +Por ejemplo, si quisiéramos crear un botón que ejecute la función `transformText` cuando se produzca el evento `click`, se vería de la siguiente manera: ```ts // text-transformer.component.ts @@ -28,7 +28,7 @@ For example, if we wanted to create a button that would run a `transformText` fu `, }) export class TextTransformer { - announcement = 'Hello again Angular!'; + announcement = 'Hola de nuevo Angular!'; transformText() { this.announcement = this.announcement.toUpperCase(); @@ -36,21 +36,21 @@ export class TextTransformer { } ``` -Other common examples of event listeners include: +Otros ejemplos comunes de detectores de eventos incluyen: - `` - `` ### $event -If you need to access the [event](https://developer.mozilla.org/en-US/docs/Web/API/Event) object, Angular provides an implicit `$event` variable that you can pass to a function: +Si necesitas acceder al objeto [event](https://developer.mozilla.org/en-US/docs/Web/API/Event) Angular proporciona una variable `$event` implícita que puede pasar a una función: ```html - + ``` -## Next Step +## Siguiente Paso - + diff --git a/adev-es/src/content/introduction/essentials/managing-dynamic-data.en.md b/adev-es/src/content/introduction/essentials/managing-dynamic-data.en.md new file mode 100644 index 0000000..175aca3 --- /dev/null +++ b/adev-es/src/content/introduction/essentials/managing-dynamic-data.en.md @@ -0,0 +1,56 @@ + +Define component state and behavior to manage dynamic data. + + +Now that we have learned the basic structure for a component, let’s learn how you can define the component’s data (i.e., state) and behavior. + +## What is state? + +Components let you neatly encapsulate responsibility for discrete parts of your application. For example, a `SignUpForm` component might need to keep track of whether the form is valid or not before allowing users to take a specific action. As a result, the various properties that a component needs to track is often referred to as "state." + +## Defining state + +To define state, you use [class fields syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields) inside of your component. + +For example, using the `TodoListItem` component, create two properties that you want to track: + +1. `taskTitle` — What the title of the task is +2. `isComplete` — Whether or not the task is complete + +```ts +// todo-list-item.component.ts +@Component({ ... }) +export class TodoListItem { + taskTitle = ''; + isComplete = false; +} +``` + +## Updating state + +When you want to update state, this is typically accomplished by defining methods in the component class that can access the various class fields with the `this` keyword. + +```ts +// todo-list-item.component.ts +@Component({ ... }) +export class TodoListItem { + taskTitle = ''; + isComplete = false; + + completeTask() { + this.isComplete = true; + } + + updateTitle(newTitle: string) { + this.taskTitle = newTitle; + } +} +``` + +## Next Step + +Now that you have learned how to declare and manage dynamic data, it's time to learn how to use that data inside of templates. + + + + diff --git a/adev-es/src/content/introduction/essentials/managing-dynamic-data.md b/adev-es/src/content/introduction/essentials/managing-dynamic-data.md index 175aca3..8d86063 100644 --- a/adev-es/src/content/introduction/essentials/managing-dynamic-data.md +++ b/adev-es/src/content/introduction/essentials/managing-dynamic-data.md @@ -1,21 +1,21 @@ - -Define component state and behavior to manage dynamic data. + +Defina el estado y el comportamiento del componente para gestionar los datos dinámicos. -Now that we have learned the basic structure for a component, let’s learn how you can define the component’s data (i.e., state) and behavior. +Ahora que hemos aprendido la estructura básica de un componente, aprendamos cómo puede definir los datos (es decir, el estado) y el comportamiento del componente. -## What is state? +## ¿Qué es el estado? -Components let you neatly encapsulate responsibility for discrete parts of your application. For example, a `SignUpForm` component might need to keep track of whether the form is valid or not before allowing users to take a specific action. As a result, the various properties that a component needs to track is often referred to as "state." +Los componentes le permiten encapsular cuidadosamente la responsabilidad de partes discretas de su aplicación. Por ejemplo, un componente `SignUpForm` podría necesitar llevar un registro de si el formulario es válido o no antes de permitir a los usuarios tomar una acción específica. Como resultado, las diversas propiedades que un componente necesita rastrear a menudo se conoce como "estado." -## Defining state +## Definiendo el estado -To define state, you use [class fields syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields) inside of your component. +Para definir el estado, use [class fields syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields) entro de su componente. -For example, using the `TodoListItem` component, create two properties that you want to track: +Por ejemplo, usando el componente `TodoListItem`, cree dos propiedades que desee rastrear: -1. `taskTitle` — What the title of the task is -2. `isComplete` — Whether or not the task is complete +1. `taskTitle` — El título de la tarea +2. `isComplete` — Si la tarea está completa o no ```ts // todo-list-item.component.ts @@ -26,9 +26,9 @@ export class TodoListItem { } ``` -## Updating state +## Actualizando el estado -When you want to update state, this is typically accomplished by defining methods in the component class that can access the various class fields with the `this` keyword. +Cuando desea actualizar el estado, típicamente se logra definiendo métodos en la clase del componente. Estos métodos pueden acceder a los distintos campos de la clase utilizando la palabra clave `this`. ```ts // todo-list-item.component.ts @@ -47,10 +47,10 @@ export class TodoListItem { } ``` -## Next Step +## Siguiente paso -Now that you have learned how to declare and manage dynamic data, it's time to learn how to use that data inside of templates. +Ahora que haz aprendido como declarar y gestionar datos dinámicos, es hora de aprender a usar esos datos dentro de las plantillas. - + diff --git a/adev-es/src/content/introduction/essentials/next-steps.en.md b/adev-es/src/content/introduction/essentials/next-steps.en.md new file mode 100644 index 0000000..10a86f8 --- /dev/null +++ b/adev-es/src/content/introduction/essentials/next-steps.en.md @@ -0,0 +1,29 @@ + + + +Now that you have been introduced to core concepts of Angular - you're ready to put what you learned into practices with our interactive tutorials and learn more with our in-depth guides. + +## Playground + + + + + +## Tutorials + + + + + + +## In-depth Guides + +Here are some in-depth guides you might be interested in reading: + + + + + + + +To see the rest of our in-depth guides, check out the main navigation. diff --git a/adev-es/src/content/introduction/essentials/next-steps.md b/adev-es/src/content/introduction/essentials/next-steps.md index 10a86f8..7a4b4a6 100644 --- a/adev-es/src/content/introduction/essentials/next-steps.md +++ b/adev-es/src/content/introduction/essentials/next-steps.md @@ -1,29 +1,29 @@ - + -Now that you have been introduced to core concepts of Angular - you're ready to put what you learned into practices with our interactive tutorials and learn more with our in-depth guides. +¡Ahora que has conocido los conceptos básicos de Angular, estás listo para poner en práctica lo aprendido con nuestros tutoriales interactivos y profundizar tus conocimientos con nuestras guías detalladas! ## Playground - + -## Tutorials +## Tutoriales - - + + -## In-depth Guides +## Guías detalladas -Here are some in-depth guides you might be interested in reading: +Aquí hay algunas guías detalladas que podría estar interesado en leer: - - - + + + -To see the rest of our in-depth guides, check out the main navigation. +Para ver el resto de nuestras guías detalladas, echa un vistazo a la navegación principal. diff --git a/adev-es/src/content/introduction/essentials/overview.en.md b/adev-es/src/content/introduction/essentials/overview.en.md new file mode 100644 index 0000000..950cb88 --- /dev/null +++ b/adev-es/src/content/introduction/essentials/overview.en.md @@ -0,0 +1,20 @@ + + + +## Before you start + +Like most modern frameworks, Angular expects you to be familiar with HTML, CSS and JavaScript. If you are totally new to frontend development, it might not be the best idea to jump right into a framework as your first step. Grasp the basics and then come back! Prior experience with other frameworks helps, but is not required. + +In addition, you should be familiar with the following concepts: + +- [JavaScript Classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) +- [TypeScript fundamentals](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html) +- [TypeScript Decorators](https://www.typescriptlang.org/docs/handbook/decorators.html) + +## Next Step + +Ready to jump in? It's time to learn about components in Angular! + + + + diff --git a/adev-es/src/content/introduction/essentials/overview.md b/adev-es/src/content/introduction/essentials/overview.md index 950cb88..4c747f6 100644 --- a/adev-es/src/content/introduction/essentials/overview.md +++ b/adev-es/src/content/introduction/essentials/overview.md @@ -1,20 +1,21 @@ - + -## Before you start +## Antes de empezar -Like most modern frameworks, Angular expects you to be familiar with HTML, CSS and JavaScript. If you are totally new to frontend development, it might not be the best idea to jump right into a framework as your first step. Grasp the basics and then come back! Prior experience with other frameworks helps, but is not required. -In addition, you should be familiar with the following concepts: +Como la mayoría de los frameworks modernos, Angular espera que estés familiarizado con HTML, CSS y JavaScript. Si eres totalmente nuevo en el desarrollo de frontend, puede que no sea la mejor idea saltar directamente a un framework como tu primer paso. ¡Comprenda lo básico y luego regrese! La experiencia previa con otros frameworks ayuda, pero no es necesaria. -- [JavaScript Classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) -- [TypeScript fundamentals](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html) -- [TypeScript Decorators](https://www.typescriptlang.org/docs/handbook/decorators.html) +Además, debes estar familiarizado con los siguientes conceptos: -## Next Step +- [Clases de JavaScript ](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) +- [Fundamentos de TypeScript](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html) +- [Decoradores de TypeScript](https://www.typescriptlang.org/docs/handbook/decorators.html) -Ready to jump in? It's time to learn about components in Angular! +## Siguiente Paso + +¿Listo para sumergirte? Es hora de aprender sobre componentes en Angular! - + diff --git a/adev-es/src/content/introduction/essentials/rendering-dynamic-templates.en.md b/adev-es/src/content/introduction/essentials/rendering-dynamic-templates.en.md new file mode 100644 index 0000000..28aa91c --- /dev/null +++ b/adev-es/src/content/introduction/essentials/rendering-dynamic-templates.en.md @@ -0,0 +1,95 @@ + +Use Angular's template syntax to create dynamic HTML. + + +What you've learned so far enables you to break an application up into components of HTML, but this limits you to static templates (i.e., content that doesn't change). The next step is to learn how to make use of Angular's template syntax to create dynamic HTML. + +## Rendering Dynamic Data + +When you need to display dynamic content in your template, Angular uses the double curly brace syntax in order to distinguish between static and dynamic content. + +Here is a simplified example from a `TodoListItem` component. + +```ts +@Component({ + selector: 'todo-list-item', + template: ` +

    Title: {{ taskTitle }}

    + `, +}) +export class TodoListItem { + taskTitle = 'Read cup of coffee'; +} +``` + +When Angular renders the component you'll see the output: + +```html +

    Title: Read cup of coffee

    +``` + +This syntax declares an **interpolation** between the dynamic data property inside of the HTML. As a result, whenever the data changes, Angular will automatically update the DOM reflecting the new value of the property. + +## Dynamic Properties + +When you need to dynamically set the value of standard DOM properties on an HTML element, the property is wrapped in square brackets to inform Angular that the declared value should be interpreted as a JavaScript-like statement ([with some Angular enhancements](guide/templates/interpolation)) instead of a plain string. + +For example, a common example of dynamically updating properties in your HTML is determining whether the form submit button should be disabled based on whether the form is valid or not. + +Wrap the desired property in square brackets to tell Angular that the assigned value is dynamic (i.e., not a static string). + +```ts +@Component({ + selector: 'sign-up-form', + template: ` + + `, +}) +export class SignUpForm { + formIsInvalid = true; +} +``` + +In this example, because `formIsInvalid` is true, the rendered HTML would be: + +```html + +``` + +## Dynamic Attributes + +In the event you want to dynamically bind custom HTML attributes (e.g., `aria-`, `data-`, etc.), you might be inclined to wrap the custom attributes with the same square brackets. + +```ts +@Component({ + standalone: true, + template: ` + + `, +}) +export class AppBanner { + testId = 'main-cta'; +} +``` + +Unfortunately, this will not work because custom HTML attributes are not standard DOM properties. In order for this to work as intended, we need to prepend the custom HTML attribute with the `attr.` prefix. + +```ts +@Component({ + standalone: true, + template: ` + + `, +}) +export class AppBanner { + testId = 'main-cta'; +} +``` + +## Next Step + +Now that you have dynamic data and templates in the application, it's time to learn how to enhance templates by conditionally hiding or showing certain elements, looping over elements, and more. + + + + diff --git a/adev-es/src/content/introduction/essentials/rendering-dynamic-templates.md b/adev-es/src/content/introduction/essentials/rendering-dynamic-templates.md index 28aa91c..5ba347c 100644 --- a/adev-es/src/content/introduction/essentials/rendering-dynamic-templates.md +++ b/adev-es/src/content/introduction/essentials/rendering-dynamic-templates.md @@ -1,14 +1,14 @@ - -Use Angular's template syntax to create dynamic HTML. + +Utilice la sintaxis de plantilla de Angular para crear HTML dinámico. -What you've learned so far enables you to break an application up into components of HTML, but this limits you to static templates (i.e., content that doesn't change). The next step is to learn how to make use of Angular's template syntax to create dynamic HTML. +Lo que has aprendido hasta ahora te permite dividir una aplicación en componentes de HTML, pero esto te limita a plantillas estáticas (es decir, contenido que no cambia). El siguiente paso es aprender cómo hacer uso de la sintaxis de plantilla de Angular para crear HTML dinámico. -## Rendering Dynamic Data +## Renderizado de Datos Dinámicos -When you need to display dynamic content in your template, Angular uses the double curly brace syntax in order to distinguish between static and dynamic content. +Cuando necesitas mostrar contenido dinámico en tu plantilla, Angular utiliza la sintaxis de doble llave `{{}}` para diferenciar entre contenido estático y dinámico. -Here is a simplified example from a `TodoListItem` component. +Aquí hay un ejemplo simplificado del componente `TodoListItem`. ```ts @Component({ @@ -18,31 +18,31 @@ Here is a simplified example from a `TodoListItem` component. `, }) export class TodoListItem { - taskTitle = 'Read cup of coffee'; + taskTitle = 'Leer la taza de café'; } ``` -When Angular renders the component you'll see the output: +Cuando Angular renderiza el componente, verá la salida: ```html -

    Title: Read cup of coffee

    +

    Title: Leer la taza de café

    ``` -This syntax declares an **interpolation** between the dynamic data property inside of the HTML. As a result, whenever the data changes, Angular will automatically update the DOM reflecting the new value of the property. +Esta sintaxis declara una **interpolación** entre la propiedad de datos dinámicos dentro del HTML. Como resultado, cada vez que los datos cambian, Angular actualizará automáticamente el DOM reflejando el nuevo valor de la propiedad. -## Dynamic Properties +## Propiedades Dinámicas -When you need to dynamically set the value of standard DOM properties on an HTML element, the property is wrapped in square brackets to inform Angular that the declared value should be interpreted as a JavaScript-like statement ([with some Angular enhancements](guide/templates/interpolation)) instead of a plain string. +Cuando necesita establecer dinámicamente el valor de las propiedades DOM estándar en un elemento HTML, la propiedad se envuelve entre corchetes para informar a Angular que el valor declarado debe interpretarse como una declaración similar a JavaScript ([con algunas mejoras de Angular](guide/templates/interpolation)) en lugar de una cadena simple. -For example, a common example of dynamically updating properties in your HTML is determining whether the form submit button should be disabled based on whether the form is valid or not. +Por ejemplo, un ejemplo común de actualización dinámica de propiedades en su HTML es determinar si el botón de envío de formulario debe ser deshabilitado en función de si el formulario es válido o no. -Wrap the desired property in square brackets to tell Angular that the assigned value is dynamic (i.e., not a static string). +Envuelva la propiedad deseada entre corchetes `[]` para decirle a Angular que el valor asignado es dinámico (es decir, no una cadena estática). ```ts @Component({ selector: 'sign-up-form', template: ` - + `, }) export class SignUpForm { @@ -50,21 +50,21 @@ export class SignUpForm { } ``` -In this example, because `formIsInvalid` is true, the rendered HTML would be: +En este ejemplo, debido a que `formIsInvalid` es verdadero, el HTML renderizado sería: ```html - + ``` -## Dynamic Attributes +## Atributos Dinámicos -In the event you want to dynamically bind custom HTML attributes (e.g., `aria-`, `data-`, etc.), you might be inclined to wrap the custom attributes with the same square brackets. +En el caso de que desee vincular dinámicamente atributos HTML personalizados (por ejemplo, `aria-`, `data-`, etc.), podría inclinarse a envolver los atributos personalizados con los mismos corchetes `[]`. ```ts @Component({ standalone: true, template: ` - + `, }) export class AppBanner { @@ -72,13 +72,13 @@ export class AppBanner { } ``` -Unfortunately, this will not work because custom HTML attributes are not standard DOM properties. In order for this to work as intended, we need to prepend the custom HTML attribute with the `attr.` prefix. +Desafortunadamente, esto no funcionará porque los atributos HTML personalizados no son propiedades DOM estándar. Para que esto funcione como se pretende, necesitamos anteponer el atributo HTML personalizado con el prefijo `attr. ` . ```ts @Component({ standalone: true, template: ` - + `, }) export class AppBanner { @@ -86,10 +86,10 @@ export class AppBanner { } ``` -## Next Step +## Siguiente paso -Now that you have dynamic data and templates in the application, it's time to learn how to enhance templates by conditionally hiding or showing certain elements, looping over elements, and more. +Ahora que tiene plantillas y datos dinámicos en la aplicación, es hora de aprender a mejorar las plantillas ocultando o mostrando condicionalmente ciertos elementos, iterando sobre elementos, y más! - + diff --git a/adev-es/src/content/introduction/essentials/sharing-logic.en.md b/adev-es/src/content/introduction/essentials/sharing-logic.en.md new file mode 100644 index 0000000..138c355 --- /dev/null +++ b/adev-es/src/content/introduction/essentials/sharing-logic.en.md @@ -0,0 +1,61 @@ + +Dependency injection allows you to share code. + + +When you need to share logic between components, Angular leverages the design pattern of [dependency injection](guide/di) that allows you to create a “service” which allows you to inject code into components while managing it from a single source of truth. + +## What are services? + +Services are reusable pieces of code that can be injected + +Similar to defining a component, services are comprised of the following: + +- A **TypeScript decorator** that declares the class as an Angular service via `@Injectable` and allows you to define what part of the application can access the service via the `providedIn` property (which is typically `'root'`) to allow a service to be accessed anywhere within the application. +- A **TypeScript class** that defines the desired code that will be accessible when the service is injected + +Here is an example of a `Calculator` service. + +```ts +import {Injectable} from '@angular/core'; + +@Injectable({ + providedIn: 'root', +}) +export class CalculatorService { + add(x: number, y: number) { + return x + y; + } +} +``` + +## How to use a service + +When you want to use a service in a component, you need to: + +1. Import the service +2. Declare a class field where the service is injected. Assign the class field to the result of the call of the built-in function `inject` which creates the service + +Here’s what it might look like in the `Receipt` component: + +```ts +import { Component } from '@angular/core'; +import { CalculatorService } from './calculator.service'; + +@Component({ + selector: 'app-receipt', + template: `

    The total is {{ totalCost }}

    `, +}) + +export class Receipt { + private calculatorService = inject(CalculatorService); + totalCost = this.calculatorService.add(50, 25); +} +``` + +In this example, the `CalculatorService` is being used by calling the Angular function `inject` and passing in the service to it. + +## Next Step + + + + diff --git a/adev-es/src/content/introduction/essentials/sharing-logic.md b/adev-es/src/content/introduction/essentials/sharing-logic.md index 138c355..ca6d3c7 100644 --- a/adev-es/src/content/introduction/essentials/sharing-logic.md +++ b/adev-es/src/content/introduction/essentials/sharing-logic.md @@ -1,19 +1,19 @@ - -Dependency injection allows you to share code. + +La inyección de dependencias le permite compartir código. -When you need to share logic between components, Angular leverages the design pattern of [dependency injection](guide/di) that allows you to create a “service” which allows you to inject code into components while managing it from a single source of truth. +Cuando necesita compartir lógica entre componentes, Angular aprovecha el patrón de diseño de [inyección de dependencia](guide/di) que le permite crear un "servicio" que le permite inyectar código en componentes mientras lo administra desde una sola fuente de verdad. -## What are services? +## ¿Qué son los servicios? -Services are reusable pieces of code that can be injected +Los servicios son piezas reutilizables de código que puender inyectados. -Similar to defining a component, services are comprised of the following: +Similares a la definición de un componente, los servicios se componen de lo siguiente: -- A **TypeScript decorator** that declares the class as an Angular service via `@Injectable` and allows you to define what part of the application can access the service via the `providedIn` property (which is typically `'root'`) to allow a service to be accessed anywhere within the application. -- A **TypeScript class** that defines the desired code that will be accessible when the service is injected +- A **decorator TypeScript** que declara la clase como un servicio Angular a través de `@Injectable` y le permite definir qué parte de la aplicación puede acceder al servicio a través de la propiedad `providedIn` (que es típicamente `'root'`) para permitir el acceso a un servicio en cualquier parte de la aplicación. +- Una **clase TypeScript** que define el código deseado que será accesible cuando el servicio sea inyectado. -Here is an example of a `Calculator` service. +Aquí hay un ejemplo del servicio `Calculator`. ```ts import {Injectable} from '@angular/core'; @@ -28,14 +28,14 @@ export class CalculatorService { } ``` -## How to use a service +## Cómo usar un servicio -When you want to use a service in a component, you need to: +Cuando deseas utilizar un servicio en un componente, necesitas: -1. Import the service -2. Declare a class field where the service is injected. Assign the class field to the result of the call of the built-in function `inject` which creates the service +1. Importar el servicio +2. Declarar un campo de clase donde se inyecta el servicio. Asignar el campo de clase al resultado de la llamada de la función integrada `inject` que crea el servicio -Here’s what it might look like in the `Receipt` component: +Esto es lo que podría parecer en el componente `Receipt: ```ts import { Component } from '@angular/core'; @@ -52,10 +52,10 @@ export class Receipt { } ``` -In this example, the `CalculatorService` is being used by calling the Angular function `inject` and passing in the service to it. +En este ejemplo, el `CalculatorService` se usa llamando a la función Angular `inject` y pasándole el servicio. -## Next Step +## Siguiente Paso - +