diff --git a/aio/content/guide/property-binding.en.md b/aio/content/guide/property-binding.en.md new file mode 100644 index 0000000000000..673be0e3dcf9d --- /dev/null +++ b/aio/content/guide/property-binding.en.md @@ -0,0 +1,228 @@ + +# Property binding `[property]` + +Use property binding to _set_ properties of target elements or +directive `@Input()` decorators. + +
+ +See the for a working example containing the code snippets in this guide. + +
+ +## One-way in + +Property binding flows a value in one direction, +from a component's property into a target element property. + +You can't use property +binding to read or pull values out of target elements. Similarly, you cannot use +property binding to call a method on the target element. +If the element raises events, you can listen to them with an [event binding](guide/event-binding). + +If you must read a target element property or call one of its methods, +see the API reference for [ViewChild](api/core/ViewChild) and +[ContentChild](api/core/ContentChild). + +## Examples + +The most common property binding sets an element property to a component +property value. An example is +binding the `src` property of an image element to a component's `itemImageUrl` property: + + + +Here's an example of binding to the `colSpan` property. Notice that it's not `colspan`, +which is the attribute, spelled with a lowercase `s`. + + + +For more details, see the [MDN HTMLTableCellElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableCellElement) documentation. + +For more information about `colSpan` and `colspan`, see the [Attribute binding](guide/attribute-binding#colspan) guide. + +Another example is disabling a button when the component says that it `isUnchanged`: + + + +Another is setting a property of a directive: + + + +Yet another is setting the model property of a custom component—a great way +for parent and child components to communicate: + + + +## Binding targets + +An element property between enclosing square brackets identifies the target property. +The target property in the following code is the image element's `src` property. + + + +There's also the `bind-` prefix alternative: + + + + +In most cases, the target name is the name of a property, even +when it appears to be the name of an attribute. +So in this case, `src` is the name of the `` element property. + +Element properties may be the more common targets, +but Angular looks first to see if the name is a property of a known directive, +as it is in the following example: + + + +Technically, Angular is matching the name to a directive `@Input()`, +one of the property names listed in the directive's `inputs` array +or a property decorated with `@Input()`. +Such inputs map to the directive's own properties. + +If the name fails to match a property of a known directive or element, Angular reports an “unknown directive” error. + +
+ +Though the target name is usually the name of a property, +there is an automatic attribute-to-property mapping in Angular for +several common attributes. These include `class`/`className`, `innerHtml`/`innerHTML`, and +`tabindex`/`tabIndex`. + +
+ + +## Avoid side effects + +Evaluation of a template expression should have no visible side effects. +The expression language itself, or the way you write template expressions, +helps to a certain extent; +you can't assign a value to anything in a property binding expression +nor use the increment and decrement operators. + +For example, you could have an expression that invoked a property or method that had +side effects. The expression could call something like `getFoo()` where only you +know what `getFoo()` does. If `getFoo()` changes something +and you happen to be binding to that something, +Angular may or may not display the changed value. Angular may detect the +change and throw a warning error. +As a best practice, stick to properties and to methods that return +values and avoid side effects. + +## Return the proper type + +The template expression should evaluate to the type of value +that the target property expects. +Return a string if the target property expects a string, a number if it +expects a number, an object if it expects an object, and so on. + +In the following example, the `childItem` property of the `ItemDetailComponent` expects a string, which is exactly what you're sending in the property binding: + + + +You can confirm this by looking in the `ItemDetailComponent` where the `@Input` type is set to a string: + + +As you can see here, the `parentItem` in `AppComponent` is a string, which the `ItemDetailComponent` expects: + + +### Passing in an object + +The previous simple example showed passing in a string. To pass in an object, +the syntax and thinking are the same. + +In this scenario, `ItemListComponent` is nested within `AppComponent` and the `items` property expects an array of objects. + + + +The `items` property is declared in the `ItemListComponent` with a type of `Item` and decorated with `@Input()`: + + + +In this sample app, an `Item` is an object that has two properties; an `id` and a `name`. + + + +While a list of items exists in another file, `mock-items.ts`, you can +specify a different item in `app.component.ts` so that the new item will render: + + + +You just have to make sure, in this case, that you're supplying an array of objects because that's the type of `Item` and is what the nested component, `ItemListComponent`, expects. + +In this example, `AppComponent` specifies a different `item` object +(`currentItems`) and passes it to the nested `ItemListComponent`. `ItemListComponent` was able to use `currentItems` because it matches what an `Item` object is according to `item.ts`. The `item.ts` file is where +`ItemListComponent` gets its definition of an `item`. + +## Remember the brackets + +The brackets, `[]`, tell Angular to evaluate the template expression. +If you omit the brackets, Angular treats the string as a constant +and *initializes the target property* with that string: + + + + +Omitting the brackets will render the string +`parentItem`, not the value of `parentItem`. + +## One-time string initialization + +You *should* omit the brackets when all of the following are true: + +* The target property accepts a string value. +* The string is a fixed value that you can put directly into the template. +* This initial value never changes. + +You routinely initialize attributes this way in standard HTML, and it works +just as well for directive and component property initialization. +The following example initializes the `prefix` property of the `StringInitComponent` to a fixed string, +not a template expression. Angular sets it and forgets about it. + + + +The `[item]` binding, on the other hand, remains a live binding to the component's `currentItems` property. + +## Property binding vs. interpolation + +You often have a choice between interpolation and property binding. +The following binding pairs do the same thing: + + + +Interpolation is a convenient alternative to property binding in +many cases. When rendering data values as strings, there is no +technical reason to prefer one form to the other, though readability +tends to favor interpolation. However, *when setting an element +property to a non-string data value, you must use property binding*. + +## Content security + +Imagine the following malicious content. + + + +In the component template, the content might be used with interpolation: + + + +Fortunately, Angular data binding is on alert for dangerous HTML. In the above case, +the HTML displays as is, and the Javascript does not execute. Angular **does not** +allow HTML with script tags to leak into the browser, neither with interpolation +nor property binding. + +In the following example, however, Angular [sanitizes](guide/security#sanitization-and-security-contexts) +the values before displaying them. + + + +Interpolation handles the ` Syntax" is the interpolated evil title. +"Template alert("evil never sleeps")Syntax" is the property bound evil title. + diff --git a/aio/content/guide/property-binding.md b/aio/content/guide/property-binding.md index 673be0e3dcf9d..0aea9922d4c34 100644 --- a/aio/content/guide/property-binding.md +++ b/aio/content/guide/property-binding.md @@ -1,226 +1,226 @@ -# Property binding `[property]` +# Enlace de propiedad `[propiedad]` -Use property binding to _set_ properties of target elements or -directive `@Input()` decorators. +Usa los enlaces de propiedad para asignar valores (_set_) a propiedades de ciertos elementos o +decoradores de directiva `@Input()`.
-See the for a working example containing the code snippets in this guide. +Echa un vistazo a , un ejemplo en acción usando los fragmentos de código de esta guía.
-## One-way in +## De una dirección (One-way) -Property binding flows a value in one direction, -from a component's property into a target element property. +Este tipo de enlace permite que un dato fluya en una única dirección, +desde una propiedad origen de un componente hacia la propiedad destino de un elemento. -You can't use property -binding to read or pull values out of target elements. Similarly, you cannot use -property binding to call a method on the target element. -If the element raises events, you can listen to them with an [event binding](guide/event-binding). +No puedes usar enlaces de propiedad +para leer ni recibir valores desde elemento destino. Asimismo, tampoco puedes utilizar +enlaces de propiedad para llamar a métodos del elemento destino. +Si el elemento en cuestión dispara eventos, puedes añadir un escuchador utilizando [enlaces de eventos](guide/event-binding). -If you must read a target element property or call one of its methods, -see the API reference for [ViewChild](api/core/ViewChild) and +Si necesitas leer la propiedad de un elemento destino o llamar a alguno de sus métodos, +echa un vistazo a la referencia de la API para los decoradores [ViewChild](api/core/ViewChild) y [ContentChild](api/core/ContentChild). -## Examples +## Ejemplos -The most common property binding sets an element property to a component -property value. An example is -binding the `src` property of an image element to a component's `itemImageUrl` property: +El enlace de propiedad más común establece la propiedad de un elemento +como valor de propiedad de un componente. Un ejemplo es +enlazar la propiedad `src` de un elemento de imagen desde la propiedad `itemImageUrl` (_urlDeImagen_) de un componente: -Here's an example of binding to the `colSpan` property. Notice that it's not `colspan`, -which is the attribute, spelled with a lowercase `s`. +En otro ejemplo, enlazamos la propiedad `colSpan`. Ten cuidado de no confundirla con `colspan`, +que es el atributo HTML, escrito con una `s` minúscula. -For more details, see the [MDN HTMLTableCellElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableCellElement) documentation. +Para más detalles, revisa la documentación de [HTMLTableCellElement en MDN](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableCellElement). -For more information about `colSpan` and `colspan`, see the [Attribute binding](guide/attribute-binding#colspan) guide. +Para más información sobre este ejemplo de enlace con `colSpan` y `colspan`, echa un vistazo a la guía de [Enlaces de atributo](guide/attribute-binding#colspan). -Another example is disabling a button when the component says that it `isUnchanged`: +Otro ejemplo es desactivar un botón cuando el componente posee una propiedad `isUnchanged` (_noPoseeCambios_): -Another is setting a property of a directive: +Otro ejemplo, asignar un valor a la propiedad de una directiva: -Yet another is setting the model property of a custom component—a great way -for parent and child components to communicate: +Otro más es asignar un objeto como valor a la propiedad de un componente—que es una excelente +manera de comunicar componentes padres con hijos: -## Binding targets +## Destinos de enlaces de propiedad -An element property between enclosing square brackets identifies the target property. -The target property in the following code is the image element's `src` property. +Una propiedad de elemento encerrada en corchetes (_square brackets_) se identifica +como propiedad de destino. +En el código a continuación, la propiedad destino del elemento de imagen es `src`. -There's also the `bind-` prefix alternative: +También es posible usar la nomenclatura alternativa, añadiendo el prefijo `bind-`: +En la mayoría de los casos, el nombre del destino es de una propiedad, incluso +cuando parece ser el nombre de un atributo. +En este caso, `src` es el nombre de una propiedad del elemento ``. -In most cases, the target name is the name of a property, even -when it appears to be the name of an attribute. -So in this case, `src` is the name of the `` element property. - -Element properties may be the more common targets, -but Angular looks first to see if the name is a property of a known directive, -as it is in the following example: +Las propiedades de elemento pueden ser destinos comunes de enlace, +pero Angular siempre analiza antes si el nombre corresponde a la propiedad de una directiva conocida, +como en el caso del ejemplo que sigue: -Technically, Angular is matching the name to a directive `@Input()`, -one of the property names listed in the directive's `inputs` array -or a property decorated with `@Input()`. -Such inputs map to the directive's own properties. +Técnicamente, Angular está enlazando el nombre a una directiva `@Input()`, +o un nombre de propiedad incluido en el array `inputs` de la directiva, +o una propiedad decorada con `@Input()`. +En tales casos se realiza un mapeo hacia las propiedades de la directiva. -If the name fails to match a property of a known directive or element, Angular reports an “unknown directive” error. +Si el nombre no se corresponde con una propiedad de una directiva o elemento conocido, Angular reporta un error de “directiva desconocida” (_unknown directive_).
-Though the target name is usually the name of a property, -there is an automatic attribute-to-property mapping in Angular for -several common attributes. These include `class`/`className`, `innerHtml`/`innerHTML`, and +Aunque el destino usualmente es el nombre de una propiedad, +Angular posee un mapeo automático de attributo-a-propiedad para +varios atributos comunes. Entre ellos se incluyen `class`/`className`, `innerHtml`/`innerHTML`, y `tabindex`/`tabIndex`.
+## Evitar efectos secundarios -## Avoid side effects - -Evaluation of a template expression should have no visible side effects. -The expression language itself, or the way you write template expressions, -helps to a certain extent; -you can't assign a value to anything in a property binding expression -nor use the increment and decrement operators. +El evaluamiento de una expresión de plantilla no debería tener efectos secundarios visibles. +El propio lenguaje de expresión, o la manera en que escribes expresiones de plantilla, +favorece este aspecto hasta cierto punto; +no puedes asignar valores a cualquier cosa dentro de una expresión de enlace de propiedad +ni usar los operadores de incremento o decremento. -For example, you could have an expression that invoked a property or method that had -side effects. The expression could call something like `getFoo()` where only you -know what `getFoo()` does. If `getFoo()` changes something -and you happen to be binding to that something, -Angular may or may not display the changed value. Angular may detect the -change and throw a warning error. -As a best practice, stick to properties and to methods that return -values and avoid side effects. +Pero por ejempo, podrías tener una expresión que invocase una propiedad o método el cual tuviera +efectos secundarios. La expresión internamente podría llamar a un método `getFoo()` y sólo tú sabrías +lo que `getFoo()` hace. Si `getFoo()` cambia algo más +y estás enlazando algún dato a ese algo más, +Angular podría no mostrar el dato correcto. O Angular podría detectar el +cambio y lanzar una advertencia o un error. +Como buena práctica, es mejor atenerse a enlazar propiedades y métodos que devuelvan +valores para evitar efectos secundarios. -## Return the proper type +## Devolver el tipo correcto -The template expression should evaluate to the type of value -that the target property expects. -Return a string if the target property expects a string, a number if it -expects a number, an object if it expects an object, and so on. +Toda expresión de plantilla debe ser evaluada con el tipo de valor +que la propiedad destino espera. +Devuelve un string si la propiedad destino espera un string, o un número si ésta +espera un número, un objeto si lo que espera es un objeto, y así consecutivamente. -In the following example, the `childItem` property of the `ItemDetailComponent` expects a string, which is exactly what you're sending in the property binding: +En el siguiente ejemplo, la propiedad `childItem` (__itemHijo__) del `ItemDetailComponent` espera un string, exactamente lo mismo que es enviado a través del enlace de propiedad: -You can confirm this by looking in the `ItemDetailComponent` where the `@Input` type is set to a string: +Al revisar el `ItemDetailComponent` se puede verificar que la propiedad con el decorador `@Input` ha sido declarada de tipo string: -As you can see here, the `parentItem` in `AppComponent` is a string, which the `ItemDetailComponent` expects: +Y como se aprecia aquí, el `parentItem` (__itemPadre__) del `AppComponent` es un string, justamente lo que `ItemDetailComponent` espera: -### Passing in an object +### Pasando objetos -The previous simple example showed passing in a string. To pass in an object, -the syntax and thinking are the same. +El ejemplo anterior demostró el enlazado de un string. No obstante, para enlazar un objeto, +se usa el mismo fundamento y sintaxis. -In this scenario, `ItemListComponent` is nested within `AppComponent` and the `items` property expects an array of objects. +En el siguiente escenario, el `ItemListComponent` se anida dentro del `AppComponent` y la propiedad `items` espera recibir un array de objetos. -The `items` property is declared in the `ItemListComponent` with a type of `Item` and decorated with `@Input()`: +La propiedad `items` es declarada en el `ItemListComponent` como array de tipo `Item` y decorada con `@Input()`: -In this sample app, an `Item` is an object that has two properties; an `id` and a `name`. +En esta aplicación de muestra, un `Item` es un objeto con dos propiedades; `id` y `name`. -While a list of items exists in another file, `mock-items.ts`, you can -specify a different item in `app.component.ts` so that the new item will render: +Mientras una lista de items existe en otro archivo, `mock-items.ts`, puedes +indicar un item diferente en `app.component.ts` de forma que el nuevo item se renderizará: -You just have to make sure, in this case, that you're supplying an array of objects because that's the type of `Item` and is what the nested component, `ItemListComponent`, expects. +Sólo tienes que asegurarte, en este caso, de que provees un array de objetos porque es el tipo de `item` y lo que el componente anidado, `ItemListComponent`, espera. -In this example, `AppComponent` specifies a different `item` object -(`currentItems`) and passes it to the nested `ItemListComponent`. `ItemListComponent` was able to use `currentItems` because it matches what an `Item` object is according to `item.ts`. The `item.ts` file is where -`ItemListComponent` gets its definition of an `item`. +En este ejemplo, `AppComponent` declara un objeto `item` diferente +(`currentItems`) y lo enlaza al `ItemListComponent` anidado. `ItemListComponent` es capaz de recibir `currentItems` pues éste +corresponde a la definición de `Item` dada por `item.ts`. El archivo `item.ts` es donde +`ItemListComponent` obtiene su definición de un `item`. -## Remember the brackets +## Recordar los corchetes -The brackets, `[]`, tell Angular to evaluate the template expression. -If you omit the brackets, Angular treats the string as a constant -and *initializes the target property* with that string: +Los corchetes (__square brackets__), `[]`, indican a Angular que debe evaluar la expresión de plantilla. +Si omites los corchetes, Angular trata al string como una constante +e *inicializa la propiedad de destino* con ese string: -Omitting the brackets will render the string -`parentItem`, not the value of `parentItem`. +Omitir los corchetes renderizará el texto +`parentItem`, no el valor de la propiedad `parentItem`. -## One-time string initialization +## Inicialización aislada de string -You *should* omit the brackets when all of the following are true: +*Sí deberías* omitir los corchetes cuando se cumplan todas las siguientes condiciones: -* The target property accepts a string value. -* The string is a fixed value that you can put directly into the template. -* This initial value never changes. +* La propiedad destino acepta un valor de tipo string. +* El string es un valor fijo que puedes ingresar directamente en la plantilla. +* Este valor inicial nunca cambia. -You routinely initialize attributes this way in standard HTML, and it works -just as well for directive and component property initialization. -The following example initializes the `prefix` property of the `StringInitComponent` to a fixed string, -not a template expression. Angular sets it and forgets about it. +Esta es la manera en que inicializas atributos en la sintaxis estándar de HTML, y funciona +sin problemas para inicializar directivas y propiedades de componentes. +El siguiente ejemplo inicializa la propiedad `prefix` del `StringInitComponent` con un string fijo, +y no una expresión de plantilla. Angular le asigna el valor y se olvida de ella. -The `[item]` binding, on the other hand, remains a live binding to the component's `currentItems` property. +El enlace de `[item]`, en cambio, se mantiene unido a la propiedad `currentItems` del componente. -## Property binding vs. interpolation +## Enlace de propiedad vs. interpolación -You often have a choice between interpolation and property binding. -The following binding pairs do the same thing: +A menudo tienes la posibilidad de elegir entre realizar uniones de datos con interpolación o con enlace de propiedad. +Los siguientes pares de enlaces tienen el mismo efecto: -Interpolation is a convenient alternative to property binding in -many cases. When rendering data values as strings, there is no -technical reason to prefer one form to the other, though readability -tends to favor interpolation. However, *when setting an element -property to a non-string data value, you must use property binding*. +La interpolación en muchos casos es una alternativa conveniente a la unión de propiedad. +Cuando se renderizan valores de datos como string, no existe motivo +técnico para preferir una opción sobre la otra, aunque la legibilidad +tiende a favorecer la interpolación. +Sin embargo, *debes usar el enlace de propiedad para asignar un valor que no sea string a la propiedad de un elemento*. -## Content security +## Seguridad del contenido -Imagine the following malicious content. +Supongamos que tenemos el siguiente contenido malicioso. -In the component template, the content might be used with interpolation: +En la plantilla del componente, este contenido podría ser interpolado: -Fortunately, Angular data binding is on alert for dangerous HTML. In the above case, -the HTML displays as is, and the Javascript does not execute. Angular **does not** -allow HTML with script tags to leak into the browser, neither with interpolation -nor property binding. +Afortunadamente, los enlaces de Angular están alertas ante la posibilidad de encontrar HTML peligroso. En el caso anterior, +el código HTML se muestra tal cual, y la porción Javascript no se ejecuta. Angular **no permite** +que se filtre código HTML con etiquetas script al navegador, ni por medio de interpolación +ni de enlaces de propiedad. -In the following example, however, Angular [sanitizes](guide/security#sanitization-and-security-contexts) -the values before displaying them. +En el ejemplo siguiente, sin embargo, Angular sanea (_sanitizes_)(guide/security#sanitization-and-security-contexts) +los valores antes de mostrarlos. -Interpolation handles the ` Syntax" is the interpolated evil title.