diff --git a/public/docs/ts/latest/guide/attribute-directives.jade b/public/docs/ts/latest/guide/attribute-directives.jade index 30106add..bbe72675 100644 --- a/public/docs/ts/latest/guide/attribute-directives.jade +++ b/public/docs/ts/latest/guide/attribute-directives.jade @@ -3,6 +3,8 @@ block includes :marked An **Attribute** directive changes the appearance or behavior of a DOM element. + + Una directiva de **Atributo** cambia la apariencia o el comportamiento de un elemento del DOM. :marked In this chapter we will @@ -10,59 +12,108 @@ block includes * [apply the attribute directive to an element in a template](#apply-directive) * [respond to user-initiated events](#respond-to-user) * [pass values into the directive using data binding](#bindings) - + + En este capítulo usted + * [escribirá una directiva de atributo para cambiar el color de fondo](#write-directive) + * [aplicará directiva de atributo a un elemento en una plantilla](#apply-directive) + * [responderá a eventeos de interacción del usuario](#respond-to-user) + * [pasará valores a la directiva usando el data binding](#bindings) + Try the <live-example></live-example>. - + + Pruebe el <live-example></live-example>. + ## Directives overview - + + ## Descripción general de las directivas. + There are three kinds of directives in Angular: 1. Components - 1. Structural directives + 1. Structural directives 1. Attribute directives - - A *Component* is really a directive with a template. + + Existen tres tipos de directivas en Angular: + 1. Componentes + 1. Directivas Estructurales + 1. Directivas de Atributo + + A *Component* is really a directive with a template. It's the most common of the three directives and we tend to write lots of them as we build applications. - - [*Structural* directives](structural-directives.html) can change the DOM layout by adding and removing DOM elements. + + Un *Componente* es en realidad una directiva con una plantilla. + Es la más común de las tres directivas y con es muy probable que escribirá muchas de ellas al construir sus aplicaciones. + + [*Structural* directives](structural-directives.html) can change the DOM layout by adding and removing DOM elements. [NgFor](template-syntax.html#ngFor) and [NgIf](template-syntax.html#ngIf) are two familiar examples. - + + Las [Directivas *Estructurales*](structural-directives.html) pueden cambiar el layout del DOM al agregar o quitar elementos del DOM. + NgFor](template-syntax.html#ngFor) y [NgIf](template-syntax.html#ngIf) son dos ejemplos familiares. + An *Attribute* directive can change the appearance or behavior of an element. The built-in [NgStyle](template-syntax.html#ngStyle) directive, for example, can change several element styles at the same time. - + + Una directiva de *Atributo* puede cambiar la apariencia o el comportamiento de un elemento. + La directiva [NgStyle](template-syntax.html#ngStyle), por ejemplo, + puede cambiar varios estilos del elemento al mismo tiempo. + We are going to write our own attribute directive to set an element's background color when the user hovers over that element. + + A continuación, escribirá su propia directiva de atributo para ponet el color de fondo de un elemento + cuando el usuario haga hover sobre el elemento. .l-sub-section :marked We don't need *any* directive to simply set the background color. We can set it with the special [Style Binding](template-syntax.html#style-binding) like this: + + Usted no necesita *ninguna* directiva para poner el color de fondo. + Lo puede hacer con el [Style Binding](template-syntax.html#style-binding) de esta manera: +makeExample('attribute-directives/ts/app/app.component.1.html','p-style-background') :marked That wouldn't be nearly as much fun as creating our own directive. - + + Aunqué no sería tan divertido como crear su propia directiva. + Besides, we're not just *setting* the color; we'll be *changing* the color in response to a user action, a mouse hover. + + Además, no solo se asignará el color; también se podrá *cambiar* el color + en respuesta a una acción del usuario, un mouse hover. .l-main-section a#write-directive :marked ## Build a simple attribute directive - An attribute directive minimally requires building a controller class annotated with + An attribute directive minimally requires building a controller class annotated with `@Directive`, which specifies the selector identifying - the attribute associated with the directive. + the attribute associated with the directive. The controller class implements the desired directive behavior. - + + ## Construir una directiva de atributo simple + Una directiva de atributo requiere como mínimo; construir una clase controlador con la anotación + `@Directive`, la cual especifica el selector que identifica + el atributo asociado con la directiva. + La clase controlador implementa el comportamiento deseado de la directiva. + Let's build a small illustrative example together. + + A continuación construirá una pequeño ejemplo ilustrativo. :marked ### Our first draft Create a new project folder (`attribute-directives`) and follow the steps in the [QuickStart](../quickstart.html). + + ### Primer borrador + Cree un nuevo folder de proyecto (`attribute-directives`) y siga los siguientes pasos en el [QuickStart](../quickstart.html). include ../_quickstart_repo :marked Create the following source file in the indicated folder with the given code: + + Cree los siguientes archivos fuente en el folder indicado con el siguiente código: +makeExample('app/highlight.directive.1.ts') block highlight-directive-1 @@ -73,31 +124,60 @@ block highlight-directive-1 so we can access the DOM element. We also need `Renderer` so we can change the DOM element's style. We don't need `Input` immediately but we will need it later in the chapter. - + + Comenzará por importar algunos símbolos del `core` de Angular. + Necesita el simbolo `Directive` para el decorador `@Directive`. + Necesita [inyectar](dependency-injection.html) `ElementRef` en el constructor de la directiva + para poder accesar al elemento DOM. + También se necesita `Renderer` para poder cambiar el estilo del elemento DOM. + No se necesita `Input` inmediatamente pero lo necesitará más adelante en el capítulo. + Then we define the directive metadata in a configuration object passed - as an argument to the `@Directive` decorator function. + as an argument to the `@Directive` decorator function. + + Después, se definen los metadatos de la directiva en objeto de configuración que se pasa + como un argumento al función del decorador `@Directive`. :marked `@Directive` requires a CSS selector to identify the HTML in the template that is associated with our directive. The [CSS selector for an attribute](https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors) is the attribute name in square brackets. - Our directive's selector is `[myHighlight]`. - Angular will locate all elements in the template that have an attribute named `myHighlight`. + Our directive's selector is `[myHighlight]`. + Angular will locate all elements in the template that have an attribute named `myHighlight`. + + `@Directive` requiere un selector CSS para identificar + el HTML en la plantilla que está asociada con la directiva. + El [selector CSS para un atributo](https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors) + es el nombre del atributo en corchetes. + El selector de su directiva es `[myHighlight]`. + Angular localizará todos los elementos en la plantilla que tengan un atributo llamado `myHighlight`. .l-sub-section :marked ### Why not call it "highlight"? *highlight* is a nicer name than *myHighlight* and, technically, it would work if we called it that. + + ### ¿Por qué no llamarlo "highlight"? + *highlight* es un mejor nombre que *myHighlight* y, técnicamente, funcionaría si lo llamáramos así. However, we recommend picking a selector name with a prefix to ensure that it cannot conflict with any standard HTML attribute, now or in the future. There is also less risk of colliding with a third-party directive name when we give ours a prefix. - + + Sin embargo, es recomendable escoger un nombre de selector con un prefijo para asegurar + que no tenga conflictos con ningún atributo estandar de HTML, ahora o en el futuro. + También hay menos riesgo de chocar con el nombre de una directiva de terceros cuando se le dé un prefijo. + We do **not** prefix our `highlight` directive name with **`ng`**. That prefix belongs to Angular. - + + **No** debe ponerle el prefijo **`ng`** a su directiva. + Ese prefijo le pertenece a Angular. + We need a prefix of our own, preferably short, and `my` will do for now. + + Se necesita un prefijo propio, preferiblemente corto y `my` servirá por ahora. p - | After the #[code @Directive] metadata comes the directive's controller class, which contains the logic for the directive. + | After the #[code @Directive] metadata comes the directive's controller class, which contains the logic for the directive. +ifDocsFor('ts') | We export `HighlightDirective` to make it accessible to other components. :marked @@ -106,171 +186,293 @@ p into the constructor. `ElementRef` is a service that grants us direct access to the DOM element through its `nativeElement` property and with `Renderer` we can set the element style. + + Angular crea una nueva instancia de la clase controlador de la directiva para + cada elemento que coincida, inyectando un `ElementRef` y un `Renderer` de Angular + en el constructor. + `ElementRef` es un servicio que le da acceso directo al elemento DOM + a travez de su propiedad `nativeElement` y con `Renderer` se puede poner el estilo del elemento. .l-main-section a#apply-directive :marked ## Apply the attribute directive The `AppComponent` in this sample is a test harness for our `HighlightDirective`. - Let's give it a new template that + Let's give it a new template that applies the directive as an attribute to a paragraph (`p`) element. In Angular terms, the `<p>` element will be the attribute **host**. + + ## Aplicar la directiva de atributo + El `AppComponent` en este ejemplo es un instrumento de prueba para su `HighlightDirective`. + Ahora se le dará una nueva plantilla que + aplica la directiva como un atributo al elemento de parrafo (`p`). + En términos de Angular, el elemento `<p>` será el atributo **host** (huésped). p - | We'll put the template in its own + | We'll put the template in its own code #[+adjExPath('app.component.html')] | file that looks like this: +makeExample('attribute-directives/ts/app/app.component.1.html',null,'app/app.component.html')(format=".") :marked - A separate template file is clearly overkill for a 2-line template. + A separate template file is clearly overkill for a 2-line template. Hang in there; we're going to expand it later. Meanwhile, we'll revise the `AppComponent` to reference this template. + + Una archivo de plantilla a parte para 2 lineas es claramente una exageración. + Tranquilo, ya lo expandirá más tarde. + Mientras tanto, se modificará el `AppComponent` para hacer referencia a esta plantilla. +makeExample('attribute-directives/ts/app/app.component.ts',null,'app/app.component.ts') :marked - We'll add an `import` statement to fetch the 'Highlight' directive and, - added that class to the `declarations` NgModule metadata so that Angular - will recognize our directive when it encounters `myHighlight` in the template. + We'll add an `import` statement to fetch the 'Highlight' directive and, + added that class to the `declarations` NgModule metadata so that Angular + will recognize our directive when it encounters `myHighlight` in the template. + + Escriba la sentencia `import` para traer la directiva 'Highlight' y + agregue esa clase al metadato de NgModule `declarations` para que Angular + reconozca su directiva cuando encuentre `myHighlight` en la plantilla. +makeExample('attribute-directives/ts/app/app.module.ts',null,'app/app.module.ts') :marked We run the app and see that our directive highlights the paragraph text. - + + Corra la aplicación y vea que su directiva resalta el texto del párrafo. + figure.image-display img(src="/resources/images/devguide/attribute-directives/first-highlight.png" alt="First Highlight") .l-sub-section :marked - ### Your directive isn't working? - - Did you remember to add the directive to the the `declarations` attribute of `@NgModule`? It is easy to forget! - + ### Your directive isn't working? + + ### ¿No funciona su directiva? + + Did you remember to add the directive to the `declarations` attribute of `@NgModule`? It is easy to forget! + + ¿Recordó agregar la directiva al atributo `declarations` del `@NgModule`? ¡Es facil olvidarlo! + Open the console in the browser tools and look for an error like this: + + Abra la consola en las herramientas del navegador y busque un error como este: code-example(format="nocode"). EXCEPTION: Template parse errors: Can't bind to 'myHighlight' since it isn't a known property of 'p'. :marked Angular detects that we're trying to bind to *something* but it doesn't know what. We have to tell it by listing `HighlightDirective` in the `declarations` metadata array. + + Angular detecta que se está tratando de hacer un bind a *algo* pero no sabe a que. + Se le tiene que indicar de esto listando `HighlightDirective en el arreglo de metadatos `declarations`. :marked Let's recap what happened. - + + Recapitulando lo que ha pasado. + Angular found the `myHighlight` attribute on the `<p>` element. It created - an instance of the `HighlightDirective` class, - injecting a reference to the element into the constructor + an instance of the `HighlightDirective` class, + injecting a reference to the element into the constructor where we set the `<p>` element's background style to yellow. + + Angular encontróel atributo `myHighlight` en el elemento `<p>`. Creo + una instancia de la clase `HighlightDirective`, + injectando una referencia al elemento dentro del constructor + donde se puso de color amarillo el fondo del elemento `<p>`. .l-main-section a#respond-to-user :marked ## Respond to user action - + + ## Responder a acciones del usuario + We are not satisfied to simply set an element color. Our directive should set the color in response to a user action. Specifically, we want to set the color when the user hovers over an element. - + + No es para estar satisfechos con simplemente cambiar el color de un elemento. + Su directiva debe poner el color en respuesta a una interaccion del usuario. + We'll need to 1. detect when the user hovers into and out of the element, 2. respond to those actions by setting and clearing the highlight color, respectively. - + + Para ello necesitará + 1. detectar cuando el usuario hace hover dentro y fuera del elemento, + 2. responder a estas acciones poniento y quitando el color del highlight, respectibamente. + We apply the `@HostListener` !{_decorator} to methods which are called when an event is raised. + + Aplique el !{_decorator} `@HostListener` a los métodos que son llamados cuando ocurre un evento. +makeExample('attribute-directives/ts/app/highlight.directive.2.ts','host')(format=".") .l-sub-section :marked The `@HostListener` !{_decorator} refers to the DOM element that hosts our attribute directive, the `<p>` in our case. - + + El !{_decorator} `@HostListener` refiere al elemento DOM que es el host de su directiva de atributo, `<p>` en su caso. + We could have attached event listeners by manipulating the host DOM element directly, but there are at least three problems with such an approach: - + + Podría haber agregado event listeners manipulando el elemento host del DOM directamente, pero + Hay por lo menos tres problemas con este enfoque: + 1. We have to write the listeners correctly. 1. We must *detach* our listener when the directive is destroyed to avoid memory leaks. 1. We'd be talking to DOM API directly which, we learned, is something to avoid. - - Let's roll with the `@HostListener` !{_decorator}. + + 1. Tendría que escribir listeners correctamente. + 1. Debería hacer el *detach* de sus listeners cuando la directiva fuera destruida para evitar memory leaks. + 1. Se estaría comunicando a la API del DOM directamente, lo cual, como ya ha aprendido, es algo que se debe evitar. + + Let's roll with the `@HostListener` !{_decorator}. :marked Now we implement the two mouse event handlers: + + Ahora implementará los dos event handlers del mouse: +makeExample('attribute-directives/ts/app/highlight.directive.2.ts','mouse-methods')(format=".") :marked Notice that they delegate to a helper method that sets the color via a private local variable, `#{_priv}el`. We revise the constructor to capture the `ElementRef.nativeElement` in this variable. + + Noté que le delegan a un método de ayuda que ponga el color via una variable local, `#{_priv}el`. + Revise que su constructor capture el `ElementRef.nativeElement` en esta variable. +makeExample('attribute-directives/ts/app/highlight.directive.2.ts','ctor')(format=".") :marked Here's the updated directive: + + Aquí está la directiva actualizada: +makeExample('app/highlight.directive.2.ts') :marked We run the app and confirm that the background color appears as we move the mouse over the `p` and disappears as we move out. + + Si corre su aplicación confirmará que el color de fondo aparece si mueve el mouse sobre el elemento `p` y + desaparece si lo mueve fuera. figure.image-display img(src="/resources/images/devguide/attribute-directives/highlight-directive-anim.gif" alt="Second Highlight") .l-main-section a#bindings :marked ## Configure the directive with binding - + + ## Configurar el binding de la directiva + Currently the highlight color is hard-coded within the directive. That's inflexible. We should set the color externally with a binding like this: + + Actualmente el color de highlight está en código duro dentro de su directiva. Esto es inflexible. + Usted debería poner el color externamente con un binding, de esta forma: +makeExample('attribute-directives/ts/app/app.component.html','pHost') :marked We'll extend our directive class with a bindable **input** `highlightColor` property and use it when we highlight text. - + + Ahora, extenderá la clase de su directiva con una propiedad `highlightColor` que es un **bindable input** y que se usará cuando se haga el highlight del texto. + Here is the final version of the class: + + Aquí está la evrsión final de la clase: +makeExcerpt('app/highlight.directive.ts', 'class') a#input :marked The new `highlightColor` property is called an *input* property because data flows from the binding expression into our directive. Notice the `@Input()` #{_decorator} applied to the property. + + La nueva propiedad `highlightColor` es llamada propiedad *input* porque los datos fluyen de la binding expression hacia la directiva. + Note el #{_decorator} `@Input()` aplicado a la propiedad. +makeExcerpt('app/highlight.directive.ts', 'color') :marked - `@Input` adds metadata to the class that makes the `highlightColor` property available for - property binding under the `myHighlight` alias. + `@Input` adds metadata to the class that makes the `highlightColor` property available for + property binding under the `myHighlight` alias. We must add this input metadata or Angular will reject the binding. See the [appendix](#why-input) below to learn why. + + `@Input` agrega el metadato a la clase que hace que la propiedad `highlightColor` esté disponible para + el binding de la propiedad bajo el alias de `myHighlight`. + Debe agregar este metadato input o Angular rechazará el binding. + Vea el [apendice](#why-input) debajo para aprender por qué. .l-sub-section :marked - ### @Input(_alias_) + ### @Input(_alias_) The developer who uses this directive expects to bind to the attribute name, `myHighlight`. The directive property name is `highlightColor`. That's a disconnect. - + + ### @Input(_alias_) + El desarrollador que utiliza esta directiva espera hacer el bind al nombre del atributo, `myHighlight`. + El nombre de la propiedad de la directiva es `highlightColor`. Ambos nombres discrepan. + We could resolve the discrepancy by renaming the property to `myHighlight` and define it as follows: + + Esto se puede resolver al renombrar la propiedad como `myHighlight` y definiendola como se muestra a continuación: +makeExcerpt('app/highlight.directive.ts', 'highlight', '') :marked - Maybe we don't want that property name inside the directive perhaps because it - doesn't express our intention well. + Maybe we don't want that property name inside the directive perhaps because it + doesn't express our intention well. We can **alias** the `highlightColor` property with the attribute name by passing `myHighlight` into the `@Input` #{_decorator}: + + Tal vez no se quiera el nombre de la propiedad dentro de la directiva, quiza porque + no expresa bien la intención de la directiva. + Puede poner el **alias** de la propiedad `highlightColor` con el nombre del atributo + pasando `myHighlight` al #{_decorator} `@Input`: +makeExcerpt('app/highlight.directive.ts', 'color', '') :marked Now that we're getting the highlight color as an input, we modify the `onMouseEnter()` method to use it instead of the hard-coded color name. We also define red as the default color to fallback on in case the user neglects to bind with a color. + + Ahora que ya obtiene el color del highlight como un input, puede modificar el método `onMouseEnter()` para usarlo + en lugar del nombre del color en código duro. + También se defina el color rojo (red) por defecto en casao + de que el usuario no haga el bind de un color. +makeExcerpt('attribute-directives/ts/app/highlight.directive.ts', 'mouse-enter', '') :marked - Now we'll update our `AppComponent` template to let + Now we'll update our `AppComponent` template to let users pick the highlight color and bind their choice to our directive. - + + Ahora actualice su plantilla `AppComponent` para permitir + a los usuarios escoger el color del highlight y puedan hacer el binding de su elección a su directiva. + Here is the updated template: + + Aquí está la plantilla actualizada: +makeExcerpt('attribute-directives/ts/app/app.component.html', 'v2', '') .l-sub-section :marked ### Where is the templated *color* property? - + + ### ¿Dónde está la propiedad *color* en la plantilla? + The eagle-eyed may notice that the radio button click handlers in the template set a `color` property - and we are binding that `color` to the directive. + and we are binding that `color` to the directive. We should expect to find a `color` on the host `AppComponent`. - + + Como se pudo dar cuenta los click handlers del radio button en la plantilla asignan una propiedad `color` + y se le hace un binding de ese `color` a la directiva. + Se debe esperar encontrar una propiedad `color` en el host `AppComponent`. + **We never defined a color property for the host *AppComponent***! And yet this code works. Where is the template `color` value going? - - Browser debugging reveals that Angular dynamically added a `color` property + + ¡**Usted nunca definio una propiedad color para el host *AppComponent***! + + Browser debugging reveals that Angular dynamically added a `color` property to the runtime instance of the `AppComponent`. - - This is *convenient* behavior but it is also *implicit* behavior that could be confusing. + + Al hacer el debug en el navegador revela que Angular agregó una propiedad `color` dinámicamente + a la instancia del `AppComponent` en tiempo de corrida. + + This is *convenient* behavior but it is also *implicit* behavior that could be confusing. While it's cool that this technique works, we recommend adding the `color` property to the `AppComponent`. + + Esto es un comportamiento *conveniente* pero también es un comportamiento *implicito* que podría ser confuso. + Aunque está bien que esta técnica funcione, es recomendable agregar la propiedad `color` al `AppComponent`. :marked Here is our second version of the directive in action. + + Aquí está la segunda versión de su directiva en acción. figure.image-display img(src="/resources/images/devguide/attribute-directives/highlight-directive-v2-anim.gif" alt="Highlight v.2") @@ -278,29 +480,51 @@ figure.image-display :marked ## Bind to a second property Our directive only has a single, customizable property. What if we had ***two properties***? - + + ## Bind a una segunda propiedad + Su directiva tiene una sola porpiedad con personalizable. ¿Qué pasa si tiene ***dos propiedades***? + Let's allow the template developer to set the default color, the color that prevails until the user picks a highlight color. We'll add a second **input** property to `HighlightDirective` called `defaultColor`: + + Se le permitirá al desarrollador de la plantilla poner el color default, el color que prevalece hasta que el usuario escoge un color para el highlight. + Se agregará una segunda propiedad **input** a `HighlightDirective` llamada `defaultColor`: +makeExample('attribute-directives/ts/app/highlight.directive.ts', 'defaultColor')(format=".") :marked The `defaultColor` property has a setter that overrides the hard-coded default color, "red". We don't need a getter. - + + La propiedad `defaultColor` tiene un setter que sobrescribe el color default que está en código duro, "red". + No se necesita un getter. + How do we bind to it? We already "burned" the `myHighlight` attribute name as a binding target. - - Remember that a *component is a directive too*. + + ¿Cómo se hace el bingin a defaultColor? Ya se utilizó el nombre de atributo `myHighlight` como un target del binding. + + Remember that a *component is a directive too*. We can add as many component property bindings as we need by stringing them along in the template - as in this example that sets the `a`, `b`, `c` properties to the string literals 'a', 'b', and 'c'. + as in this example that sets the `a`, `b`, `c` properties to the string literals 'a', 'b', and 'c'. + + Recuerde que un *componente es también una directiva*. + Se pueden agregar tantos bindings de propiedad de componentes como se necesiten ligandolas a lo largo de la plantilla. + como en este ejemplo que asigna las propiedades `a`, `b` y `c` los valores string 'a', 'b' y 'c'. code-example(format="." ). <my-component [a]="'a'" [b]="'b'" [c]="'c'"><my-component> :marked We do the same thing with an attribute directive. + + Se hace lo mismo con las directivas de atributo +makeExample('attribute-directives/ts/app/app.component.html', 'defaultColor')(format=".") :marked Here we're binding the user's color choice to the `myHighlight` attribute as we did before. We're *also* binding the literal string, 'violet', to the `defaultColor`. - + + Aquí se hace el binding del color del usuario al atributo `myHighlight` como se hizo anteriormente. + *También* se está haciendo el binding del string 'violet' al `defaultColor`. + Here is the final version of the directive in action. + + Aquí estaá la versión final de la directiva en acción. figure.image-display img(src="/resources/images/devguide/attribute-directives/highlight-directive-final-anim.gif" alt="Final Highlight") @@ -312,24 +536,32 @@ figure.image-display - [use that directive in a template](#apply-directive), - [respond to **events** to change behavior based on an event](#respond-to-user), - and [use **binding** to pass values to the attribute directive](#bindings). - + + ## Resumen + Ahora sabe como + - [construir una **directiva de atributo** simple, para agregar comportamiento a un atributo HTML](#write-directive), + - [usar esa directiva en una plantilla](#apply-directive), + - [responder a **eventos** para cambiar el comportamiento en base a un evento](#respond-to-user), + - y [usar **binding** para pasar valores a la directiva de atributo](#bindings). + The final source: - + + El código final: +makeTabs( - `attribute-directives/ts/app/app.component.ts, - attribute-directives/ts/app/app.component.html, - attribute-directives/ts/app/highlight.directive.ts, - attribute-directives/ts/app/app.module.ts, - attribute-directives/ts/app/main.ts, - attribute-directives/ts/index.html +`attribute-directives/ts/app/app.component.ts, +attribute-directives/ts/app/app.component.html, +attribute-directives/ts/app/highlight.directive.ts, +attribute-directives/ts/app/app.module.ts, +attribute-directives/ts/app/main.ts, +attribute-directives/ts/index.html `, - ',,full', - `app.component.ts, - app.component.html, - highlight.directive.ts, - app.module.ts, - main.ts, - index.html +',,full', +`app.component.ts, +app.component.html, +highlight.directive.ts, +app.module.ts, +main.ts, +index.html `) @@ -337,39 +569,75 @@ a#why-input .l-main-section :marked ### Appendix: Input properties - + + ### Apéndice + Earlier we declared the `highlightColor` property to be an ***input*** property of our `HighlightDirective` - We've seen properties in bindings before. + Al principio se declaró la propiedad `highlightColor` para que fuera una propiedad ***input*** para su + directiva `HighlightDirective` + + We've seen properties in bindings before. We never had to declare them as anything. Why now? - + + Usted ha visto propiedades en bindings anteriormente. + Usted nunca tuvo que declararlas como cualquier cosa. ¿Porqué ahora si? + Angular makes a subtle but important distinction between binding **sources** and **targets**. - + + Angular hace una sutil per importante distinción entre el binding **sources** y el **targets**. + In all previous bindings, the directive or component property was a binding ***source***. A property is a *source* if it appears in the template expression to the ***right*** of the equals (=). - + + En todos los bindings anteriores, la directiva o propiedad del componente era un binding ***source***. + Una propiedad es *source* si aparece en la expresión de la plantilla a la ***derecha*** del igual (=). + A property is a *target* when it appears in **square brackets** ([ ]) to the **left** of the equals (=) ... - as it is does when we bind to the `myHighlight` property of the `HighlightDirective`, + as it is does when we bind to the `myHighlight` property of the `HighlightDirective`, + + Una propiedad es *target* cuando aparece en **corchetes** ([ ]) a la **izquierda** del igual (=) ... +makeExample('attribute-directives/ts/app/app.component.html','pHost')(format=".") :marked The 'color' in `[myHighlight]="color"` is a binding ***source***. A source property doesn't require a declaration. - + + 'color' en `[myHighlight]="color"` es un binding ***source***. + The 'myHighlight' in `[myHighlight]="color"` *is* a binding ***target***. We must declare it as an *input* property. Angular rejects the binding with a clear error if we don't. - + + 'myHighlight' en `[myHighlight]="color"` *es* un binding ***target***. + Se debe declarar como una propiedad *input*. + Angular rechaza el bind con un error claro en caso de no hacerlo. + Angular treats a *target* property differently for a good reason. A component or directive in target position needs protection. - + + Angular trata la propiedad *target* de una manera diferente por buenas razones. + Un componente o directiva en la posición targetnecesita prtección. + Imagine that our `HighlightDirective` did truly wonderous things. - We graciously made a gift of it to the world. - + We graciously made a gift of it to the world. + + Imagine que su directiva `HighlightDirective` hiceiera cosas maravillosas. + Muy amablemente habría hecho usted un regalo al mundo. + To our surprise, some people — perhaps naively — - started binding to *every* property of our directive. + started binding to *every* property of our directive. Not just the one or two properties we expected them to target. *Every* property. That could really mess up our directive in ways we didn't anticipate and have no desire to support. - + + Para su sorpresa, alguna persona — tal vez inocentemente — + comenzara a hacer bindings a *todas* las propiedades de la directiva. + No solo las propiedades que se espera que sean target. *Cada* propiedad. + Eso podría hacer un desorden en la directiva de maneras que no se anticiparon y que no se deseaban. + The *input* declaration ensures that consumers of our directive can only bind to the properties of our public API ... nothing else. + + La delcaración *input* asegura que los consumidores de su directiva solo puedan hacer bind + a las propiedades de su API pública ... nada más. +