diff --git a/aio/content/guide/attribute-binding.en.md b/aio/content/guide/attribute-binding.en.md new file mode 100644 index 0000000000000..13525002ccf20 --- /dev/null +++ b/aio/content/guide/attribute-binding.en.md @@ -0,0 +1,303 @@ +# Attribute, class, and style bindings + +The template syntax provides specialized one-way bindings for scenarios less well-suited to property binding. + +
+ +See the for a working example containing the code snippets in this guide. + +
+ + +## Attribute binding + +Set the value of an attribute directly with an **attribute binding**. This is the only exception to the rule that a binding sets a target property and the only binding that creates and sets an attribute. + +Usually, setting an element property with a [property binding](guide/property-binding) +is preferable to setting the attribute with a string. However, sometimes +there is no element property to bind, so attribute binding is the solution. + +Consider the [ARIA](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA) and +[SVG](https://developer.mozilla.org/en-US/docs/Web/SVG). They are purely attributes, don't correspond to element properties, and don't set element properties. In these cases, there are no property targets to bind to. + +Attribute binding syntax resembles property binding, but +instead of an element property between brackets, start with the prefix `attr`, +followed by a dot (`.`), and the name of the attribute. +You then set the attribute value, using an expression that resolves to a string, +or remove the attribute when the expression resolves to `null`. + +One of the primary use cases for attribute binding +is to set ARIA attributes, as in this example: + + + +{@a colspan} + +
+ +#### `colspan` and `colSpan` + +Notice the difference between the `colspan` attribute and the `colSpan` property. + +If you wrote something like this: + + + <tr><td colspan="{{1 + 1}}">Three-Four</td></tr> + + +You'd get this error: + + + Template parse errors: + Can't bind to 'colspan' since it isn't a known native property + + +As the message says, the `` element does not have a `colspan` property. This is true +because `colspan` is an attribute—`colSpan`, with a capital `S`, is the +corresponding property. Interpolation and property binding can set only *properties*, not attributes. + +Instead, you'd use property binding and write it like this: + + + +
+ +
+ +{@a class-binding} + +## Class binding + +Here's how to set the `class` attribute without a binding in plain HTML: + +```html + +
Some text
+``` + +You can also add and remove CSS class names from an element's `class` attribute with a **class binding**. + +To create a single class binding, start with the prefix `class` followed by a dot (`.`) and the name of the CSS class (for example, `[class.foo]="hasFoo"`). +Angular adds the class when the bound expression is truthy, and it removes the class when the expression is falsy (with the exception of `undefined`, see [styling delegation](#styling-delegation)). + +To create a binding to multiple classes, use a generic `[class]` binding without the dot (for example, `[class]="classExpr"`). +The expression can be a space-delimited string of class names, or you can format it as an object with class names as the keys and truthy/falsy expressions as the values. +With object format, Angular will add a class only if its associated value is truthy. + +It's important to note that with any object-like expression (`object`, `Array`, `Map`, `Set`, etc), the identity of the object must change for the class list to be updated. +Updating the property without changing object identity will have no effect. + +If there are multiple bindings to the same class name, conflicts are resolved using [styling precedence](#styling-precedence). + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ Binding Type + + Syntax + + Input Type + + Example Input Values +
Single class binding[class.foo]="hasFoo"boolean | undefined | nulltrue, false
Multi-class binding[class]="classExpr"string"my-class-1 my-class-2 my-class-3"
{[key: string]: boolean | undefined | null}{foo: true, bar: false}
Array<string>['foo', 'bar']
+ + +The [NgClass](guide/built-in-directives/#ngclass) directive can be used as an alternative to direct `[class]` bindings. +However, using the above class binding syntax without `NgClass` is preferred because due to improvements in class binding in Angular, `NgClass` no longer provides significant value, and might eventually be removed in the future. + + +
+ +## Style binding + +Here's how to set the `style` attribute without a binding in plain HTML: + +```html + +
Some text
+``` + +You can also set styles dynamically with a **style binding**. + +To create a single style binding, start with the prefix `style` followed by a dot (`.`) and the name of the CSS style property (for example, `[style.width]="width"`). +The property will be set to the value of the bound expression, which is normally a string. +Optionally, you can add a unit extension like `em` or `%`, which requires a number type. + +
+ +Note that a _style property_ name can be written in either +[dash-case](guide/glossary#dash-case), as shown above, or +[camelCase](guide/glossary#camelcase), such as `fontSize`. + +
+ +If there are multiple styles you'd like to toggle, you can bind to the `[style]` property directly without the dot (for example, `[style]="styleExpr"`). +The expression attached to the `[style]` binding is most often a string list of styles like `"width: 100px; height: 100px;"`. + +You can also format the expression as an object with style names as the keys and style values as the values, like `{width: '100px', height: '100px'}`. +It's important to note that with any object-like expression (`object`, `Array`, `Map`, `Set`, etc), the identity of the object must change for the class list to be updated. +Updating the property without changing object identity will have no effect. + +If there are multiple bindings to the same style property, conflicts are resolved using [styling precedence rules](#styling-precedence). + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ Binding Type + + Syntax + + Input Type + + Example Input Values +
Single style binding[style.width]="width"string | undefined | null"100px"
Single style binding with units[style.width.px]="width"number | undefined | null100
Multi-style binding[style]="styleExpr"string"width: 100px; height: 100px"
{[key: string]: string | undefined | null}{width: '100px', height: '100px'}
Array<string>['width', '100px']
+ +The [NgStyle](guide/built-in-directives/#ngstyle) directive can be used as an alternative to direct `[style]` bindings. +However, using the above style binding syntax without `NgStyle` is preferred because due to improvements in style binding in Angular, `NgStyle` no longer provides significant value, and might eventually be removed in the future. + + +
+ +{@a styling-precedence} + +## Styling Precedence + +A single HTML element can have its CSS class list and style values bound to multiple sources (for example, host bindings from multiple directives). + +When there are multiple bindings to the same class name or style property, Angular uses a set of precedence rules to resolve conflicts and determine which classes or styles are ultimately applied to the element. + +
+

Styling precedence (highest to lowest)

+ +1. Template bindings + 1. Property binding (for example, `
` or `
`) + 1. Map binding (for example, `
` or `
`) + 1. Static value (for example, `
` or `
`) +1. Directive host bindings + 1. Property binding (for example, `host: {'[class.foo]': 'hasFoo'}` or `host: {'[style.color]': 'color'}`) + 1. Map binding (for example, `host: {'[class]': 'classExpr'}` or `host: {'[style]': 'styleExpr'}`) + 1. Static value (for example, `host: {'class': 'foo'}` or `host: {'style': 'color: blue'}`) +1. Component host bindings + 1. Property binding (for example, `host: {'[class.foo]': 'hasFoo'}` or `host: {'[style.color]': 'color'}`) + 1. Map binding (for example, `host: {'[class]': 'classExpr'}` or `host: {'[style]': 'styleExpr'}`) + 1. Static value (for example, `host: {'class': 'foo'}` or `host: {'style': 'color: blue'}`) + +
+ +The more specific a class or style binding is, the higher its precedence. + +A binding to a specific class (for example, `[class.foo]`) will take precedence over a generic `[class]` binding, and a binding to a specific style (for example, `[style.bar]`) will take precedence over a generic `[style]` binding. + + + +Specificity rules also apply when it comes to bindings that originate from different sources. +It's possible for an element to have bindings in the template where it's declared, from host bindings on matched directives, and from host bindings on matched components. + +Template bindings are the most specific because they apply to the element directly and exclusively, so they have the highest precedence. + +Directive host bindings are considered less specific because directives can be used in multiple locations, so they have a lower precedence than template bindings. + +Directives often augment component behavior, so host bindings from components have the lowest precedence. + + + +In addition, bindings take precedence over static attributes. + +In the following case, `class` and `[class]` have similar specificity, but the `[class]` binding will take precedence because it is dynamic. + + + +{@a styling-delegation} +### Delegating to styles with lower precedence + +It is possible for higher precedence styles to "delegate" to lower precedence styles using `undefined` values. +Whereas setting a style property to `null` ensures the style is removed, setting it to `undefined` will cause Angular to fall back to the next-highest precedence binding to that style. + +For example, consider the following template: + + + +Imagine that the `dirWithHostBinding` directive and the `comp-with-host-binding` component both have a `[style.width]` host binding. +In that case, if `dirWithHostBinding` sets its binding to `undefined`, the `width` property will fall back to the value of the `comp-with-host-binding` host binding. +However, if `dirWithHostBinding` sets its binding to `null`, the `width` property will be removed entirely. \ No newline at end of file diff --git a/aio/content/guide/attribute-binding.md b/aio/content/guide/attribute-binding.md index c73dbcdb0325f..4df8847370e53 100644 --- a/aio/content/guide/attribute-binding.md +++ b/aio/content/guide/attribute-binding.md @@ -1,33 +1,28 @@ -# Attribute, class, and style bindings +# Enlaces de atributos, clases y estilos -The template syntax provides specialized one-way bindings for scenarios less well-suited to property binding. +La sintaxis de la plantilla proporciona enlaces one-way especializados para escenarios menos adecuados para el enlace de propiedades.
-See the for a working example containing the code snippets in this guide. +Consulta el para ver un ejemplo práctico que contiene los fragmentos de código de esta guía.
-## Attribute binding +## Enlace de atributo -Set the value of an attribute directly with an **attribute binding**. This is the only exception to the rule that a binding sets a target property and the only binding that creates and sets an attribute. +Establece el valor de un atributo directamente con un **enlace de atributo**. Esta es la única excepción a la regla de que un enlace establece una propiedad de destino y el único enlace que crea y establece un atributo. -Usually, setting an element property with a [property binding](guide/property-binding) -is preferable to setting the attribute with a string. However, sometimes -there is no element property to bind, so attribute binding is the solution. +Por lo general, establecer una propiedad de elemento con un [enlace de propiedad](guide/property-binding) es preferible establecer el atributo con una string. Sin embargo, a veces +no hay ninguna propiedad de elemento para vincular, por lo que la vinculación de atributos es la solución. -Consider the [ARIA](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA) and -[SVG](https://developer.mozilla.org/en-US/docs/Web/SVG). They are purely attributes, don't correspond to element properties, and don't set element properties. In these cases, there are no property targets to bind to. +Considera el [ARIA](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA) y +[SVG](https://developer.mozilla.org/en-US/docs/Web/SVG). Son puramente atributos, no corresponden a las propiedades del elemento y no establecen las propiedades del elemento. En estos casos, no hay objetivos de propiedad a los que vincularse. -Attribute binding syntax resembles property binding, but -instead of an element property between brackets, start with the prefix `attr`, -followed by a dot (`.`), and the name of the attribute. -You then set the attribute value, using an expression that resolves to a string, -or remove the attribute when the expression resolves to `null`. +La sintaxis de enlace de atributo se parece al enlace de propiedad, pero en lugar de una propiedad de elemento entre paréntesis, comienza con el prefijo `attr`, seguido de un punto (`.`) y el nombre del atributo. +Luego establece el valor del atributo, utilizando una expresión que se resuelve en una string, o elimina el atributo cuando la expresión se resuelva en `null`. -One of the primary use cases for attribute binding -is to set ARIA attributes, as in this example: +Uno de los casos de uso principales para el enlace de atributos es establecer atributos ARIA, como en este ejemplo: @@ -35,28 +30,27 @@ is to set ARIA attributes, as in this example:
-#### `colspan` and `colSpan` +#### `colspan` y `colSpan` -Notice the difference between the `colspan` attribute and the `colSpan` property. +Observa la diferencia entre el atributo `colspan` y la propiedad `colSpan`. -If you wrote something like this: +Si escribes algo como esto: <tr><td colspan="{{1 + 1}}">Three-Four</td></tr> -You'd get this error: +Recibirías este error: Template parse errors: Can't bind to 'colspan' since it isn't a known native property -As the message says, the `` element does not have a `colspan` property. This is true -because `colspan` is an attribute—`colSpan`, with a capital `S`, is the -corresponding property. Interpolation and property binding can set only *properties*, not attributes. +Como dice el mensaje, el elemento `` no tiene una propiedad `colspan`. Esto es verdad +porque `colspan` es un atributo—`colSpan`, con una `S` mayúscula, es la propiedad correspondiente. La interpolación y el enlace de propiedades solo pueden establecer *propiedades*, no atributos. -Instead, you'd use property binding and write it like this: +En su lugar, puedes usar el enlace de propiedad y lo escribirías así: @@ -66,28 +60,28 @@ Instead, you'd use property binding and write it like this: {@a class-binding} -## Class binding +## Enlace de clase -Here's how to set the `class` attribute without a binding in plain HTML: +Aquí se explica cómo configurar el atributo `class` sin un enlace en HTML simple: ```html -
Some text
+
Algún texto
``` -You can also add and remove CSS class names from an element's `class` attribute with a **class binding**. +También puedes agregar y eliminar nombres de clase CSS del atributo `class` de un elemento con un **enlace de clase**. -To create a single class binding, start with the prefix `class` followed by a dot (`.`) and the name of the CSS class (for example, `[class.foo]="hasFoo"`). -Angular adds the class when the bound expression is truthy, and it removes the class when the expression is falsy (with the exception of `undefined`, see [styling delegation](#styling-delegation)). +Para crear un enlace de clase único, comienza con el prefijo `class` seguido de un punto (`.`) y el nombre de la clase CSS (por ejemplo, `[class.foo]="hasFoo"`). +Angular agrega la clase cuando la expresión enlazada es verdadera y elimina la clase cuando la expresión es falsa (con la excepción de `undefined`, vea [delegación de estilo](#styling-delegation)). -To create a binding to multiple classes, use a generic `[class]` binding without the dot (for example, `[class]="classExpr"`). -The expression can be a space-delimited string of class names, or you can format it as an object with class names as the keys and truthy/falsy expressions as the values. -With object format, Angular will add a class only if its associated value is truthy. +Para crear un enlace a varias clases, usa un enlace genérico `[class]` sin el punto (por ejemplo, `[class]="classExpr"`). +La expresión puede ser una string de nombres de clase delimitada por espacios, o puede formatearla como un objeto con nombres de clase como claves y expresiones de verdad / falsedad como valores. +Con el formato de objeto, Angular agregará una clase solo si su valor asociado es verdadero. -It's important to note that with any object-like expression (`object`, `Array`, `Map`, `Set`, etc), the identity of the object must change for the class list to be updated. -Updating the property without changing object identity will have no effect. +Es importante tener en cuenta que con cualquier expresión similar a un objeto (`object`,`Array`, `Map`, `Set`, etc.), la identidad del objeto debe cambiar para que se actualice la lista de clases. +Actualizar la propiedad sin cambiar la identidad del objeto no tendrá ningún efecto. -If there are multiple bindings to the same class name, conflicts are resolved using [styling precedence](#styling-precedence). +Si hay varios enlaces al mismo nombre de clase, los conflictos se resuelven usando [precedencia de estilo](#styling-precedence).